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.

Maritime & Geopolitics tab update

tilakpatel224a831f61e6b1
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 344067ba1..b9fe4d23b 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -781,6 +781,8 @@ set(STORAGE_SOURCES
src/storage/repositories/FiiDiiRepository.cpp
src/storage/repositories/IvHistoryRepository.cpp
src/storage/repositories/WatchlistRepository.cpp
+ src/storage/repositories/ScanWatchRepository.cpp
+ src/storage/repositories/ScanEventRepository.cpp
src/storage/repositories/NotesRepository.cpp
src/storage/repositories/NotebookRepository.cpp
src/storage/repositories/ReportRepository.cpp
@@ -788,6 +790,8 @@ set(STORAGE_SOURCES
src/storage/repositories/NewsMonitorRepository.cpp
src/storage/repositories/NewsArticleRepository.cpp
src/storage/repositories/RssFeedRepository.cpp
+ src/storage/repositories/FeedSubscriptionRepository.cpp
+ src/storage/repositories/FeedItemRepository.cpp
src/storage/repositories/PortfolioHoldingsRepository.cpp
src/storage/repositories/ChatRepository.cpp
src/storage/repositories/DashboardLayoutRepository.cpp
@@ -852,6 +856,11 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v037_cloud_sync.cpp
src/storage/sqlite/migrations/v038_notebooks.cpp
src/storage/sqlite/migrations/v039_algo_schema_fix.cpp
+ src/storage/sqlite/migrations/v040_paper_trading_realism.cpp
+ src/storage/sqlite/migrations/v041_scan_watches.cpp
+ src/storage/sqlite/migrations/v042_scan_watch_events.cpp
+ src/storage/sqlite/migrations/v043_feed_subscriptions.cpp
+ src/storage/sqlite/migrations/v044_feed_items.cpp
# Historical OHLCV data store (Historify, Phase 3 §13)
src/storage/HistoricalDataStore.cpp
@@ -1068,6 +1077,7 @@ set(ALGO_ENGINE_SOURCES
src/algo_engine/AlgoEngineProducer.cpp
src/algo_engine/AlgoScanner.cpp
src/algo_engine/CandleDataFetcher.cpp
+ src/algo_engine/ScanMonitor.cpp
src/algo_engine/BacktestEngine.cpp
)
@@ -1124,6 +1134,11 @@ set(SERVICE_SOURCES
src/services/news/NewsMonitorService.cpp
src/services/news/NewsNlpService.cpp
src/services/news/NewsCorrelationService.cpp
+ # Generalized feed monitor (reusable RSS/XML/JSON/CSV scraper engine)
+ src/services/feeds/FeedParseUtil.cpp
+ src/services/feeds/FeedScraper.cpp
+ src/services/feeds/FeedMonitor.cpp
+ src/services/feeds/FeedSelfTest.cpp
src/services/databento/DatabentoService.cpp
src/services/dbnomics/DBnomicsService.cpp
src/services/gov_data/GovDataService.cpp
@@ -1317,6 +1332,7 @@ set(UI_SOURCES
src/ui/command/QuickCommandBar.cpp
src/ui/command/CommandPalette.cpp
src/ui/notifications/NotificationService.cpp
+ src/ui/notifications/DesktopNotifier.cpp
src/ui/error/ErrorPipeline.cpp
src/ui/workspace/LayoutOpenDialog.cpp
@@ -1335,6 +1351,7 @@ set(UI_SOURCES
src/ui/widgets/algo/ConditionSection.cpp
src/ui/widgets/algo/RiskManagementPanel.cpp
src/ui/widgets/algo/SymbolSearchCombo.cpp
+ src/ui/widgets/algo/SymbolChipInput.cpp
)
# Screens
@@ -1501,6 +1518,13 @@ set(SCREEN_SOURCES
src/screens/equity_trading/AccountManagementDialog.cpp
src/screens/equity_trading/BroadcastOrderDialog.cpp
src/screens/equity_trading/OrderConfirmDialog.cpp
+ # Feed monitor (reusable across screens)
+ src/screens/common/feeds/FeedCardView.cpp
+ src/screens/common/feeds/FeedTableView.cpp
+ src/screens/common/feeds/FeedView.cpp
+ src/screens/common/feeds/FloatingFeedWindow.cpp
+ src/screens/common/feeds/FeedConfigDialog.cpp
+ src/screens/common/feeds/FeedPanel.cpp
# Action Center — pending-orders popover + status-bar badge (queued approvals).
src/screens/action_center/PendingOrdersPanel.cpp
src/screens/action_center/PendingOrdersBadge.cpp
@@ -1647,6 +1671,7 @@ set(SCREEN_SOURCES
src/screens/algo_trading/StrategyBuilderPanel.cpp
src/screens/algo_trading/StrategyListPanel.cpp
src/screens/algo_trading/ScannerPanel.cpp
+ src/screens/algo_trading/AlertsPanel.cpp
src/screens/algo_trading/DeploymentDashboard.cpp
src/screens/algo_trading/AlgoDeployDialog.cpp
@@ -1906,6 +1931,7 @@ set_source_files_properties(
src/screens/algo_trading/AlgoTradingScreen.cpp
src/screens/algo_trading/DeploymentDashboard.cpp
src/screens/algo_trading/ScannerPanel.cpp
+ src/screens/algo_trading/AlertsPanel.cpp
src/screens/algo_trading/StrategyBuilderPanel.cpp
src/screens/algo_trading/StrategyListPanel.cpp
src/screens/algo_trading/AlgoDeployDialog.cpp
@@ -1962,6 +1988,13 @@ set_source_files_properties(
src/screens/equity_trading/AccountManagementDialog.cpp
src/screens/equity_trading/BroadcastOrderDialog.cpp
src/screens/equity_trading/OrderConfirmDialog.cpp
+ # Feed monitor (reusable across screens)
+ src/screens/common/feeds/FeedCardView.cpp
+ src/screens/common/feeds/FeedTableView.cpp
+ src/screens/common/feeds/FeedView.cpp
+ src/screens/common/feeds/FloatingFeedWindow.cpp
+ src/screens/common/feeds/FeedConfigDialog.cpp
+ src/screens/common/feeds/FeedPanel.cpp
# Action Center — pending-orders popover + status-bar badge (queued approvals).
src/screens/action_center/PendingOrdersPanel.cpp
src/screens/action_center/PendingOrdersBadge.cpp
@@ -2258,6 +2291,8 @@ set_source_files_properties(
src/storage/repositories/ReportRepository.cpp
src/storage/repositories/SettingsRepository.cpp
src/storage/repositories/WatchlistRepository.cpp
+ src/storage/repositories/ScanWatchRepository.cpp
+ src/storage/repositories/ScanEventRepository.cpp
src/storage/repositories/WorkflowRepository.cpp
src/storage/repositories/CustomIndexRepository.cpp
src/storage/repositories/DataMappingRepository.cpp
@@ -2302,6 +2337,11 @@ set_source_files_properties(
src/storage/sqlite/migrations/v037_cloud_sync.cpp
src/storage/sqlite/migrations/v038_notebooks.cpp
src/storage/sqlite/migrations/v039_algo_schema_fix.cpp
+ src/storage/sqlite/migrations/v040_paper_trading_realism.cpp
+ src/storage/sqlite/migrations/v041_scan_watches.cpp
+ src/storage/sqlite/migrations/v042_scan_watch_events.cpp
+ src/storage/sqlite/migrations/v043_feed_subscriptions.cpp
+ src/storage/sqlite/migrations/v044_feed_items.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
@@ -2560,6 +2600,8 @@ set_source_files_properties(
src/storage/repositories/ReportRepository.cpp
src/storage/repositories/SettingsRepository.cpp
src/storage/repositories/WatchlistRepository.cpp
+ src/storage/repositories/ScanWatchRepository.cpp
+ src/storage/repositories/ScanEventRepository.cpp
src/storage/repositories/WorkflowRepository.cpp
src/storage/repositories/CustomIndexRepository.cpp
src/storage/repositories/DataMappingRepository.cpp
diff --git a/fincept-qt/fixscan.txt b/fincept-qt/fixscan.txt
deleted file mode 100644
index 2072d9768..000000000
--- a/fincept-qt/fixscan.txt
+++ /dev/null
@@ -1,143 +0,0 @@
-## A: where exchange_token is called (connect)
-src/screens/equity_trading/AccountManagementDialog.cpp:522: // Attempt token exchange asynchronously — exchange_token() makes a blocking
-src/screens/equity_trading/AccountManagementDialog.cpp:538: auto result = broker->exchange_token(api_key_val, api_secret_val, auth_code_val);
-src/screens/equity_trading/AccountManagementDialog.cpp:977: auto result = broker.exchange_token(api_key, api_secret, request_token);
-src/screens/equity_trading/AccountManagementDialog.cpp:1242: auto result = broker.exchange_token(client_id, api_secret, auth_code);
-src/screens/equity_trading/AccountManagementDialog.cpp:1461: auto result = broker.exchange_token(meta_token, QString(), auth_code_json);
-
-## B: credentials_saved signal + handlers
-src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp:205: connect(dlg, &CryptoCredentials::credentials_saved, this,
-src/screens/crypto_trading/CryptoCredentials.cpp:199: emit credentials_saved(api_key(), api_secret(), password());
-src/screens/polymarket/PolymarketScreen.cpp:204: connect(dlg, &PredictionAccountDialog::credentials_saved, this, [this](const QString& id) {
-src/screens/polymarket/PredictionAccountDialog.cpp:235: emit credentials_saved(QStringLiteral("polymarket"));
-src/screens/polymarket/PredictionAccountDialog.cpp:254: emit credentials_saved(QStringLiteral("polymarket"));
-src/screens/polymarket/PredictionAccountDialog.cpp:278: emit credentials_saved(QStringLiteral("kalshi"));
-src/screens/polymarket/PredictionAccountDialog.cpp:295: emit credentials_saved(QStringLiteral("kalshi"));
-src/screens/crypto_trading/CryptoCredentials.h:23: void credentials_saved(const QString& api_key, const QString& api_secret, const QString& password);
-src/screens/polymarket/PredictionAccountDialog.h:37: void credentials_saved(const QString& exchange_id);
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:125: // process (see crash report 2026-05-08-123609.ips). The credentials_saved
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:269: // crash report 2026-05-08-123609.ips). Defer focus to credentials_saved.
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:286: connect(dlg, &AccountManagementDialog::credentials_saved, this, [this](const QString& account_id) {
-src/screens/equity_trading/AccountManagementDialog.cpp:579: emit self->credentials_saved(account_id);
-src/screens/equity_trading/AccountManagementDialog.cpp:862: emit self->credentials_saved(acct);
-src/screens/equity_trading/AccountManagementDialog.cpp:992: emit self->credentials_saved(acct);
-src/screens/equity_trading/AccountManagementDialog.cpp:1263: emit self->credentials_saved(acct);
-src/screens/equity_trading/AccountManagementDialog.cpp:1477: emit self->credentials_saved(acct);
-src/screens/equity_trading/AccountManagementDialog.h:34: void credentials_saved(const QString& account_id);
-
-## C: equity_trading files
-AccountManagementDialog.cpp
-AccountManagementDialog.h
-BroadcastOrderDialog.cpp
-BroadcastOrderDialog.h
-EquityBottomPanel.cpp
-EquityBottomPanel.h
-EquityChart.cpp
-EquityChart.h
-EquityOrderBook.cpp
-EquityOrderBook.h
-EquityOrderEntry.cpp
-EquityOrderEntry.h
-EquityTickerBar.cpp
-EquityTickerBar.h
-EquityTradingScreen_Handlers.cpp
-EquityTradingScreen_Holdings.cpp
-EquityTradingScreen_Streams.cpp
-EquityTradingScreen.cpp
-EquityTradingScreen.h
-EquityTypes.h
-EquityWatchlist.cpp
-EquityWatchlist.h
-
-## D: ChainSubTab.cpp lines 230-320
- if (unders.isEmpty()) {
- show_empty_state("Databento configuration error.");
- return;
- }
- QString prefer;
- if (keep_selection && unders.contains(last_underlying_))
- prefer = last_underlying_;
- else
- prefer = unders.contains(QStringLiteral("SPY")) ? QStringLiteral("SPY") : unders.first();
- header_->set_underlyings(unders, prefer);
- rebuild_expiries_for_underlying(QStringLiteral("databento"), prefer, keep_selection);
- return;
- }
- const bool loaded = InstrumentService::instance().is_loaded(broker_id);
- LOG_INFO("FnoChain", QString("rebuild_picker_for_broker: is_loaded('%1')=%2").arg(broker_id).arg(loaded));
- if (!loaded) {
- show_empty_state(QString("Loading %1 instruments...").arg(broker_id));
- header_->set_underlyings({});
- header_->set_expiries({});
-
- QPointer<ChainSubTab> self = this;
- InstrumentService::instance().load_from_db_async(broker_id, [self, broker_id](int count) {
- if (!self) {
- LOG_WARN("FnoChain", QString("load_from_db_async callback: widget destroyed, broker='%1'").arg(broker_id));
- return;
- }
- LOG_INFO("FnoChain", QString("load_from_db_async callback: broker='%1' count=%2").arg(broker_id).arg(count));
- if (count > 0) {
- self->rebuild_picker_for_broker(broker_id, true);
- return;
- }
- QString account_id = find_account_for_broker(broker_id);
- LOG_INFO("FnoChain", QString("find_account_for_broker('%1') → '%2'").arg(broker_id, account_id));
- if (account_id.isEmpty()) {
- self->show_empty_state(QString("No account configured for %1. Connect one in Equity Trading.").arg(broker_id));
- return;
- }
- self->show_empty_state(QString("Downloading %1 instruments from broker...").arg(broker_id));
- auto creds = trading::AccountManager::instance().load_credentials(account_id);
- InstrumentService::instance().refresh(broker_id, creds);
- });
- return;
- }
- auto unders = OptionChainService::instance().list_underlyings(broker_id);
- LOG_INFO("FnoChain", QString("list_underlyings('%1') → %2 items").arg(broker_id).arg(unders.size()));
- if (unders.isEmpty()) {
- show_empty_state("No NFO instruments cached for " + broker_id + ".");
- header_->set_underlyings({});
- header_->set_expiries({});
- return;
- }
- QString prefer;
- if (keep_selection && unders.contains(last_underlying_))
- prefer = last_underlying_;
- else
- prefer = unders.contains("NIFTY") ? "NIFTY" : unders.first();
- LOG_INFO("FnoChain", QString("Setting underlyings for '%1', prefer='%2' (%3 items)")
- .arg(broker_id, prefer).arg(unders.size()));
- header_->set_underlyings(unders, prefer);
- LOG_INFO("FnoChain", "set_underlyings done, calling rebuild_expiries_for_underlying");
- rebuild_expiries_for_underlying(broker_id, prefer, keep_selection);
- LOG_INFO("FnoChain", "rebuild_expiries_for_underlying done");
-}
-
-void ChainSubTab::rebuild_expiries_for_underlying(const QString& broker_id, const QString& underlying,
- bool keep_selection) {
- if (broker_id == QStringLiteral("databento")) {
- auto cached = OptionChainService::instance().list_expiries(QStringLiteral("databento"), underlying);
- if (!cached.isEmpty()) {
- QString prefer;
- if (keep_selection && cached.contains(last_expiry_))
- prefer = last_expiry_;
- else
- prefer = cached.first();
- header_->set_expiries(cached, prefer);
- if (is_visible_)
- resubscribe();
- return;
- }
- header_->set_expiries({});
- show_empty_state(QString("Loading expiries for %1 from Databento...").arg(underlying));
- QPointer<ChainSubTab> self = this;
- OptionChainService::instance().list_databento_expiries(
- underlying,
- [self, underlying, keep_selection](const QStringList& exps) {
- if (!self) return;
- if (exps.isEmpty()) {
- self->show_empty_state(
- QString("No expiries found for %1. Check Databento API key and OPRA access.").arg(underlying));
- return;
- }
diff --git a/fincept-qt/scripts/ai_quant_lab/qlib_service.py b/fincept-qt/scripts/ai_quant_lab/qlib_service.py
index c896f9683..ecd5a194c 100644
--- a/fincept-qt/scripts/ai_quant_lab/qlib_service.py
+++ b/fincept-qt/scripts/ai_quant_lab/qlib_service.py
@@ -603,6 +603,62 @@ class QlibService:
"available_count": len(HANDLERS_AVAILABLE)
}
+ def get_factor_library(self) -> Dict[str, Any]:
+ """List built-in Qlib alpha factors with their expressions.
+
+ Pulls the real (name, expression) pairs from the Alpha158/Alpha360
+ feature loaders when qlib is installed; falls back to a curated set
+ of canonical alpha expressions otherwise so the UI is never empty.
+ Returns {"success", "factors":[{name, category, expression}, ...]}.
+ """
+ factors: List[Dict[str, Any]] = []
+ if QLIB_AVAILABLE:
+ try:
+ from qlib.contrib.data.loader import Alpha158DL, Alpha360DL
+ for category, loader in (("Alpha158", Alpha158DL), ("Alpha360", Alpha360DL)):
+ fields, names = loader.get_feature_config()
+ for name, expr in zip(names, fields):
+ factors.append({
+ "name": name,
+ "category": category,
+ "expression": expr,
+ })
+ except Exception as e:
+ print(f"Falling back to curated factor library: {e}", file=sys.stderr)
+ factors = []
+
+ if not factors:
+ # Curated fallback — canonical Qlib alpha expressions (Alpha158 style).
+ curated = [
+ ("KMID", "($close-$open)/$open"),
+ ("KLEN", "($high-$low)/$open"),
+ ("KUP", "($high-Greater($open,$close))/$open"),
+ ("KLOW", "(Less($open,$close)-$low)/$open"),
+ ("OPEN0", "$open/$close"),
+ ("HIGH0", "$high/$close"),
+ ("LOW0", "$low/$close"),
+ ("ROC5", "Ref($close,5)/$close"),
+ ("MA5", "Mean($close,5)/$close"),
+ ("MA20", "Mean($close,20)/$close"),
+ ("STD5", "Std($close,5)/$close"),
+ ("STD20", "Std($close,20)/$close"),
+ ("BETA5", "Slope($close,5)/$close"),
+ ("MAX5", "Max($high,5)/$close"),
+ ("MIN5", "Min($low,5)/$close"),
+ ("QTLU5", "Quantile($close,5,0.8)/$close"),
+ ("QTLD5", "Quantile($close,5,0.2)/$close"),
+ ("RSV5", "($close-Min($low,5))/(Max($high,5)-Min($low,5)+1e-12)"),
+ ("CORR5", "Corr($close,Log($volume+1),5)"),
+ ("CORD5", "Corr($close/Ref($close,1),Log($volume/Ref($volume,1)+1),5)"),
+ ("CNTP5", "Mean($close>Ref($close,1),5)"),
+ ("SUMP5", "Sum(Greater($close-Ref($close,1),0),5)/(Sum(Abs($close-Ref($close,1)),5)+1e-12)"),
+ ("VMA5", "Mean($volume,5)/($volume+1e-12)"),
+ ("VSTD5", "Std($volume,5)/($volume+1e-12)"),
+ ]
+ factors = [{"name": n, "category": "Alpha158", "expression": e} for n, e in curated]
+
+ return {"success": True, "factors": factors, "count": len(factors)}
+
def get_strategies(self) -> Dict[str, Any]:
"""Get available trading strategies"""
strategies = {
@@ -1237,7 +1293,7 @@ class QlibService:
}
def get_instruments(self,
- market: str = "csi300",
+ market: str = "all",
start_date: Optional[str] = None,
end_date: Optional[str] = None) -> Dict[str, Any]:
"""Get instruments list for a market index"""
@@ -1255,6 +1311,15 @@ class QlibService:
else:
instrument_list = []
+ if not instrument_list:
+ return {
+ "success": False,
+ "error": (f"No instruments found for market '{market}'. "
+ "The qlib market dataset is not downloaded. Run: "
+ "python -m qlib.run.get_data qlib_data "
+ "--target_dir ~/.qlib/qlib_data/us_data --region us"),
+ }
+
return {
"success": True,
"market": market,
@@ -1329,6 +1394,9 @@ def main():
elif command == "get_data_handlers":
result = service.get_data_handlers()
+ elif command == "get_factor_library":
+ result = service.get_factor_library()
+
elif command == "get_strategies":
result = service.get_strategies()
@@ -1454,7 +1522,7 @@ def main():
elif command == "get_instruments":
params = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
result = service.get_instruments(
- params.get("market", "csi300"),
+ params.get("market", "all"),
params.get("start_date"),
params.get("end_date")
)
diff --git a/fincept-qt/src/algo_engine/IndicatorEngine.cpp b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
index e4678c87d..69a729373 100644
--- a/fincept-qt/src/algo_engine/IndicatorEngine.cpp
+++ b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
@@ -3,6 +3,7 @@
#include <algorithm>
#include <cmath>
+#include <limits>
#include <numeric>
namespace fincept::algo {
@@ -159,6 +160,10 @@ IndicatorResult IndicatorEngine::compute(const QString& name,
// Volume
if (name == "OBV") return compute_obv(close, vol);
if (name == "CMF") return compute_cmf(high, low, close, vol, period);
+ if (name == "VOL_WIN_CHG") {
+ int window = params.value("window").toInt(10);
+ return compute_vol_win_chg(vol, window);
+ }
return make_error(QStringLiteral("Unknown indicator: ") + name);
}
@@ -785,6 +790,31 @@ IndicatorResult IndicatorEngine::compute_obv(const QVector<double>& close,
return make_result(obv, prev_obv);
}
+IndicatorResult IndicatorEngine::compute_vol_win_chg(const QVector<double>& volume, int window) {
+ if (window < 1)
+ return make_error(QStringLiteral("VOL_WIN_CHG: window must be >= 1"));
+ const int n = volume.size();
+ if (n < 2 * window)
+ return make_error(QStringLiteral("Insufficient data for VOL_WIN_CHG (need %1 bars)")
+ .arg(2 * window));
+ // Compute the windowed %-change at the current bar and at the previous bar so
+ // crossing/rising operators (which re-read the prior sample) stay consistent.
+ auto win_pct = [&](int last_index) -> double {
+ double sum_last = 0, sum_prev = 0;
+ for (int i = last_index - window + 1; i <= last_index; ++i)
+ sum_last += volume[i];
+ for (int i = last_index - 2 * window + 1; i <= last_index - window; ++i)
+ sum_prev += volume[i];
+ if (sum_prev <= 0.0)
+ return std::numeric_limits<double>::quiet_NaN();
+ return (sum_last / sum_prev - 1.0) * 100.0;
+ };
+ double curr = win_pct(n - 1);
+ double prev = (n >= 2 * window + 1) ? win_pct(n - 2)
+ : std::numeric_limits<double>::quiet_NaN();
+ return make_result(curr, prev);
+}
+
IndicatorResult IndicatorEngine::compute_cmf(const QVector<double>& high,
const QVector<double>& low,
const QVector<double>& close,
diff --git a/fincept-qt/src/algo_engine/IndicatorEngine.h b/fincept-qt/src/algo_engine/IndicatorEngine.h
index e458a4314..8e766aac0 100644
--- a/fincept-qt/src/algo_engine/IndicatorEngine.h
+++ b/fincept-qt/src/algo_engine/IndicatorEngine.h
@@ -82,6 +82,7 @@ private:
const QVector<double>& low,
const QVector<double>& close,
const QVector<double>& volume, int period);
+ static IndicatorResult compute_vol_win_chg(const QVector<double>& volume, int window);
// Stock attribute pseudo-indicators
static IndicatorResult compute_stock_attr(const QVector<OhlcvCandle>& candles,
diff --git a/fincept-qt/src/algo_engine/ScanMonitor.cpp b/fincept-qt/src/algo_engine/ScanMonitor.cpp
new file mode 100644
index 000000000..77997a06e
--- /dev/null
+++ b/fincept-qt/src/algo_engine/ScanMonitor.cpp
@@ -0,0 +1,166 @@
+// src/algo_engine/ScanMonitor.cpp
+#include "algo_engine/ScanMonitor.h"
+
+#include "algo_engine/CandleDataFetcher.h"
+#include "algo_engine/ConditionEvaluator.h"
+#include "core/logging/Logger.h"
+#include "services/notifications/NotificationService.h"
+#include "storage/repositories/ScanEventRepository.h"
+#include "ui/notifications/NotificationService.h"
+
+#include <QDateTime>
+#include <QJsonObject>
+#include <QStringList>
+#include <QTimer>
+
+namespace fincept::algo {
+
+using fincept::ui::ToastService;
+using fincept::notifications::NotificationService;
+using fincept::notifications::NotificationRequest;
+using fincept::notifications::NotifLevel;
+using fincept::notifications::NotifTrigger;
+
+ScanMonitor& ScanMonitor::instance() {
+ static ScanMonitor s;
+ return s;
+}
+
+void ScanMonitor::start() {
+ auto r = ScanWatchRepository::instance().list_active();
+ if (r.is_err()) {
+ LOG_ERROR("ScanMonitor", QString("load active watches: %1")
+ .arg(QString::fromStdString(r.error())));
+ return;
+ }
+ for (const auto& w : r.value())
+ start_watch(w);
+ LOG_INFO("ScanMonitor", QString("started %1 active watch(es)").arg(r.value().size()));
+}
+
+void ScanMonitor::start_watch(const ScanWatch& w) {
+ stop_watch(w.id); // idempotent
+ auto* run = new Runner();
+ run->watch = w;
+ run->timer = new QTimer(this);
+ const int interval_ms = qMax(30, w.interval_sec) * 1000; // floor 30s (rate limits)
+ run->timer->setInterval(interval_ms);
+ const QString id = w.id;
+ connect(run->timer, &QTimer::timeout, this, [this, id]() { poll(id); });
+ runners_.insert(id, run);
+ run->timer->start();
+ poll(id); // evaluate immediately on (re)start
+}
+
+void ScanMonitor::stop_watch(const QString& id) {
+ if (auto* run = runners_.take(id)) {
+ if (run->timer) {
+ run->timer->stop();
+ run->timer->deleteLater();
+ }
+ delete run;
+ }
+}
+
+void ScanMonitor::reload(const QString& id) {
+ auto r = ScanWatchRepository::instance().get(id);
+ if (r.is_err()) { stop_watch(id); return; }
+ const ScanWatch w = r.value();
+ if (!w.active) { stop_watch(id); return; }
+ start_watch(w);
+}
+
+void ScanMonitor::poll(const QString& id) {
+ auto it = runners_.find(id);
+ if (it == runners_.end()) return;
+ const ScanWatch& w = it.value()->watch;
+ if (w.symbols.isEmpty() || w.conditions.isEmpty()) return;
+
+ const DataSource src = data_source_from_string(w.data_source);
+ CandleDataFetcher::instance().fetch_multi(
+ w.symbols, w.timeframe, w.lookback_days, src, w.broker_id, w.account_id,
+ [this, id](const QHash<QString, QVector<OhlcvCandle>>& data, const QStringList& errors) {
+ Q_UNUSED(errors);
+ on_candles(id, data);
+ });
+}
+
+void ScanMonitor::on_candles(const QString& id,
+ const QHash<QString, QVector<OhlcvCandle>>& data) {
+ auto it = runners_.find(id);
+ if (it == runners_.end()) return; // watch removed mid-fetch
+ Runner* run = it.value();
+ const ScanWatch& w = run->watch;
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ const qint64 cooldown_ms = static_cast<qint64>(qMax(0, w.cooldown_min)) * 60000;
+ bool any_warming = false, any_fired = false;
+
+ for (auto sit = data.begin(); sit != data.end(); ++sit) {
+ const QString& sym = sit.key();
+ const auto& candles = sit.value();
+ SymState& st = run->states[sym];
+
+ if (candles.size() < 2) { any_warming = true; continue; }
+ auto eval = ConditionEvaluator::evaluate_group(w.conditions, w.logic, candles);
+
+ if (eval.triggered) {
+ if (st.armed && now - st.last_fired_ms >= cooldown_ms) {
+ QStringList parts;
+ for (const auto& d : eval.details)
+ parts << QString("%1 %2 %3").arg(d.indicator, d.op,
+ QString::number(d.target_value, 'f', 2));
+ dispatch(w, sym, parts.join(" & "));
+ st.last_fired_ms = now;
+ st.armed = false;
+ any_fired = true;
+ }
+ } else {
+ st.armed = true;
+ }
+ }
+
+ if (any_fired) {
+ // One-shot: once a watch triggers it leaves LIVE WATCHES. The fired event
+ // is already persisted in scan_watch_events (kept for ALERT HISTORY), so
+ // removing the watch row does not erase the history.
+ ScanWatchRepository::instance().remove(id);
+ emit watch_status_changed(id, QStringLiteral("triggered"));
+ QTimer::singleShot(0, this, [this, id]() { stop_watch(id); }); // stop runner after we return
+ return;
+ }
+ const QString status = any_warming ? QStringLiteral("warming") : QStringLiteral("watching");
+ ScanWatchRepository::instance().touch_status(id, status, now);
+ emit watch_status_changed(id, status);
+}
+
+void ScanMonitor::dispatch(const ScanWatch& w, const QString& symbol, const QString& detail) {
+ const QString msg = QString("%1 — %2").arg(symbol, detail);
+ const QJsonObject actions = w.actions;
+
+ if (actions.value("toast").toBool(true))
+ ToastService::instance().post(ToastService::Severity::Warning, msg, "scan:" + w.id);
+
+ if (actions.value("providers").toBool(false)) {
+ NotificationRequest req;
+ req.title = QString("Alert: %1").arg(w.name);
+ req.message = msg;
+ req.level = NotifLevel::Warning;
+ req.trigger = NotifTrigger::PriceAlert;
+ NotificationService::instance().send(req);
+ }
+
+ ScanWatchRepository::instance().touch_fired(w.id, QDateTime::currentMSecsSinceEpoch());
+ fincept::ScanEventRepository::instance().record(w.id, symbol, detail,
+ QDateTime::currentMSecsSinceEpoch());
+ LOG_INFO("ScanMonitor", QString("FIRE %1 / %2: %3").arg(w.name, symbol, detail));
+ emit watch_fired(w.id, symbol, detail);
+}
+
+void ScanMonitor::test_fire(const QString& id, const QString& symbol) {
+ auto r = ScanWatchRepository::instance().get(id);
+ if (r.is_err()) return;
+ dispatch(r.value(), symbol.isEmpty() ? QStringLiteral("TEST") : symbol,
+ QStringLiteral("test fire"));
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/ScanMonitor.h b/fincept-qt/src/algo_engine/ScanMonitor.h
new file mode 100644
index 000000000..768b2be97
--- /dev/null
+++ b/fincept-qt/src/algo_engine/ScanMonitor.h
@@ -0,0 +1,51 @@
+// src/algo_engine/ScanMonitor.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "storage/repositories/ScanWatchRepository.h"
+
+#include <QHash>
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+class QTimer;
+
+namespace fincept::algo {
+
+/// Background service that runs persisted ScanWatches: polls candles on a timer,
+/// evaluates each watch's conditions per symbol, edge+cooldown gates, and fires
+/// toast/provider alerts. Singleton; lives on the main thread.
+class ScanMonitor : public QObject {
+ Q_OBJECT
+ public:
+ static ScanMonitor& instance();
+
+ void start(); // load active watches, begin polling
+ void reload(const QString& id); // re-read one watch and (re)start/stop its runner
+ void stop_watch(const QString& id);
+ void test_fire(const QString& id, const QString& symbol);
+
+ signals:
+ void watch_fired(const QString& watch_id, const QString& symbol, const QString& detail);
+ void watch_status_changed(const QString& watch_id, const QString& status);
+
+ private:
+ ScanMonitor() = default;
+ Q_DISABLE_COPY(ScanMonitor)
+
+ struct SymState { bool armed = true; qint64 last_fired_ms = 0; };
+ struct Runner {
+ ScanWatch watch;
+ QTimer* timer = nullptr;
+ QHash<QString, SymState> states;
+ };
+
+ void start_watch(const ScanWatch& w);
+ void poll(const QString& id);
+ void on_candles(const QString& id, const QHash<QString, QVector<OhlcvCandle>>& data);
+ void dispatch(const ScanWatch& w, const QString& symbol, const QString& detail);
+
+ QHash<QString, Runner*> runners_;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 49fafab7b..97478f02c 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -1,5 +1,7 @@
#include "algo_engine/AlgoEngineProducer.h"
+#include "algo_engine/ScanMonitor.h"
#include "services/llm/LlmService.h"
+#include "ui/notifications/DesktopNotifier.h"
#include "app/MonitorPickerDialog.h"
#include "app/WindowFrame.h"
#include "app/TerminalShell.h"
@@ -24,6 +26,7 @@
#include "datahub/DataHubMetaTypes.h"
#include "mcp/McpInit.h"
#include "mcp/ToolSelfTest.h"
+#include "services/feeds/FeedSelfTest.h"
#include "network/http/HttpClient.h"
#include "python/PythonSetupManager.h"
#include "screens/launchpad/LaunchpadScreen.h"
@@ -707,6 +710,11 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v037();
fincept::register_migration_v038();
fincept::register_migration_v039();
+ fincept::register_migration_v040();
+ fincept::register_migration_v041();
+ fincept::register_migration_v042();
+ fincept::register_migration_v043();
+ fincept::register_migration_v044();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -860,8 +868,23 @@ int main(int argc, char* argv[]) {
return fincept::mcp::run_tool_selftest();
if (qstrcmp(argv[i], "--dump-tools") == 0)
return fincept::mcp::dump_tools_json();
+ if (qstrcmp(argv[i], "--selftest-feeds") == 0)
+ return fincept::feeds::run_feed_selftest();
}
+ // Start the scan-watch background service. Runs after Database::open() (which
+ // applies the scan_watches migration) and after bootstrap_auth() (broker
+ // creds, needed by the first candle poll), and after the headless self-test
+ // early-returns above so it is skipped on --selftest-tools / --dump-tools.
+ // Placed before the Python-setup branch so both GUI paths (setup screen and
+ // normal startup) start it exactly once. Candle fetching is native C++ (broker
+ // REST / native Yahoo), so it does not require the Python env to be ready.
+ fincept::algo::ScanMonitor::instance().start();
+
+ // Native desktop notifications (Win toast / macOS Notification Center / Linux
+ // libnotify) via a tray icon — also surfaces every in-app ToastService toast.
+ fincept::ui::DesktopNotifier::instance().init();
+
// ── Python environment check ─────────────────────────────────────────────
// check_status() fast path (sentinel + markers present) is synchronous and
// cheap. The slow path (first run) can spawn processes — but at this point
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
index c9a8733f5..20933aea0 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
@@ -816,15 +816,24 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
fd_fields->setStyleSheet(input_ss());
text_inputs_["fd_fields"] = fd_fields;
datavl->addWidget(build_input_row(tr("Fields"), fd_fields, data_tab));
- auto* fd_start = new QLineEdit(data_tab);
- fd_start->setPlaceholderText(tr("Start date (YYYY-MM-DD, e.g. 2019-01-01)"));
- fd_start->setStyleSheet(input_ss());
- text_inputs_["fd_start"] = fd_start;
+ const QDate fd_today = QDate::currentDate();
+ auto* fd_start = new QDateEdit(data_tab);
+ fd_start->setCalendarPopup(true);
+ fd_start->setDisplayFormat("yyyy-MM-dd");
+ fd_start->setMinimumDate(QDate(2000, 1, 1));
+ fd_start->setMaximumDate(fd_today);
+ fd_start->setDate(fd_today.addYears(-1));
+ fd_start->setStyleSheet(dateedit_ss());
+ date_inputs_["fd_start"] = fd_start;
datavl->addWidget(build_input_row(tr("Start Date"), fd_start, data_tab));
- auto* fd_end = new QLineEdit(data_tab);
- fd_end->setPlaceholderText(tr("End date (YYYY-MM-DD, e.g. 2020-11-10)"));
- fd_end->setStyleSheet(input_ss());
- text_inputs_["fd_end"] = fd_end;
+ auto* fd_end = new QDateEdit(data_tab);
+ fd_end->setCalendarPopup(true);
+ fd_end->setDisplayFormat("yyyy-MM-dd");
+ fd_end->setMinimumDate(QDate(2000, 1, 1));
+ fd_end->setMaximumDate(fd_today);
+ fd_end->setDate(fd_today);
+ fd_end->setStyleSheet(dateedit_ss());
+ date_inputs_["fd_end"] = fd_end;
datavl->addWidget(build_input_row(tr("End Date"), fd_end, data_tab));
auto* fd_run = make_run_button(tr("FETCH DATA"), data_tab);
connect(fd_run, &QPushButton::clicked, this, [this]() {
@@ -840,10 +849,8 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
if (!s.trimmed().isEmpty())
fields.append(s.trimmed());
params["fields"] = fields;
- if (!text_inputs_["fd_start"]->text().isEmpty())
- params["start_date"] = text_inputs_["fd_start"]->text().trimmed();
- if (!text_inputs_["fd_end"]->text().isEmpty())
- params["end_date"] = text_inputs_["fd_end"]->text().trimmed();
+ params["start_date"] = date_inputs_["fd_start"]->date().toString("yyyy-MM-dd");
+ params["end_date"] = date_inputs_["fd_end"]->date().toString("yyyy-MM-dd");
AIQuantLabService::instance().factor_get_data(params);
});
datavl->addWidget(fd_run);
@@ -855,24 +862,31 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
auto* calvl = new QVBoxLayout(cal_tab);
calvl->setContentsMargins(12, 12, 12, 12);
calvl->setSpacing(8);
- auto* cal_start = new QLineEdit(cal_tab);
- cal_start->setPlaceholderText(tr("Start date (YYYY-MM-DD)"));
- cal_start->setStyleSheet(input_ss());
- text_inputs_["fd_cal_start"] = cal_start;
+ const QDate cal_today = QDate::currentDate();
+ auto* cal_start = new QDateEdit(cal_tab);
+ cal_start->setCalendarPopup(true);
+ cal_start->setDisplayFormat("yyyy-MM-dd");
+ cal_start->setMinimumDate(QDate(2000, 1, 1));
+ cal_start->setMaximumDate(cal_today);
+ cal_start->setDate(cal_today.addYears(-1));
+ cal_start->setStyleSheet(dateedit_ss());
+ date_inputs_["fd_cal_start"] = cal_start;
calvl->addWidget(build_input_row(tr("Start Date"), cal_start, cal_tab));
- auto* cal_end = new QLineEdit(cal_tab);
- cal_end->setPlaceholderText(tr("End date (YYYY-MM-DD)"));
- cal_end->setStyleSheet(input_ss());
- text_inputs_["fd_cal_end"] = cal_end;
+ auto* cal_end = new QDateEdit(cal_tab);
+ cal_end->setCalendarPopup(true);
+ cal_end->setDisplayFormat("yyyy-MM-dd");
+ cal_end->setMinimumDate(QDate(2000, 1, 1));
+ cal_end->setMaximumDate(cal_today);
+ cal_end->setDate(cal_today);
+ cal_end->setStyleSheet(dateedit_ss());
+ date_inputs_["fd_cal_end"] = cal_end;
calvl->addWidget(build_input_row(tr("End Date"), cal_end, cal_tab));
auto* cal_run = make_run_button(tr("GET TRADING CALENDAR"), cal_tab);
connect(cal_run, &QPushButton::clicked, this, [this]() {
status_label_->setText(tr("Loading..."));
QJsonObject params;
- if (!text_inputs_["fd_cal_start"]->text().isEmpty())
- params["start_date"] = text_inputs_["fd_cal_start"]->text().trimmed();
- if (!text_inputs_["fd_cal_end"]->text().isEmpty())
- params["end_date"] = text_inputs_["fd_cal_end"]->text().trimmed();
+ params["start_date"] = date_inputs_["fd_cal_start"]->date().toString("yyyy-MM-dd");
+ params["end_date"] = date_inputs_["fd_cal_end"]->date().toString("yyyy-MM-dd");
AIQuantLabService::instance().factor_get_calendar(params);
});
calvl->addWidget(cal_run);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Styles.h b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Styles.h
index 881f70c25..00e3c2039 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Styles.h
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Styles.h
@@ -48,6 +48,23 @@ inline QString spinbox_ss() {
.arg(ui::colors::BORDER_BRIGHT());
}
+inline QString dateedit_ss() {
+ return QString("QDateEdit { background:%1; color:%2; border:1px solid %3;"
+ "padding:4px 6px; border-radius:2px; }"
+ "QDateEdit:focus { border-color:%4; }"
+ "QDateEdit::drop-down { border:none; width:18px; }"
+ "QCalendarWidget QWidget { background:%1; color:%2; }"
+ "QCalendarWidget QAbstractItemView { background:%1; color:%2;"
+ "selection-background-color:%5; selection-color:%2; }"
+ "QCalendarWidget QToolButton { background:%1; color:%2; }"
+ "QCalendarWidget QToolButton:hover { background:%5; }")
+ .arg(ui::colors::BG_RAISED())
+ .arg(ui::colors::TEXT_PRIMARY())
+ .arg(ui::colors::BORDER_MED())
+ .arg(ui::colors::BORDER_BRIGHT())
+ .arg(ui::colors::BG_HOVER());
+}
+
inline QString tab_ss(const QString& accent) {
return QString("QTabWidget::pane { border:1px solid %1; background:%2; }"
"QTabBar::tab { background:%3; color:%4; padding:6px 14px;"
diff --git a/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp b/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp
new file mode 100644
index 000000000..ec12b9ea9
--- /dev/null
+++ b/fincept-qt/src/screens/algo_trading/AlertsPanel.cpp
@@ -0,0 +1,421 @@
+// src/screens/algo_trading/AlertsPanel.cpp
+#include "screens/algo_trading/AlertsPanel.h"
+
+#include "algo_engine/ScanMonitor.h"
+#include "core/logging/Logger.h"
+#include "storage/repositories/ScanEventRepository.h"
+#include "storage/repositories/ScanWatchRepository.h"
+#include "trading/AccountManager.h"
+#include "ui/theme/Theme.h"
+
+#include <QDateTime>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QInputDialog>
+#include <QJsonObject>
+#include <QScrollArea>
+#include <QVBoxLayout>
+#include <functional>
+
+namespace {
+
+inline QString kMonoFont() { return QString("font-family: %1;").arg(fincept::ui::fonts::DATA_FAMILY); }
+inline QString kLabelStyle() {
+ return QString("color:%1; font-size:%2px; font-weight:700; letter-spacing:0.5px; %3"
+ " background:transparent; border:none;")
+ .arg(fincept::ui::colors::TEXT_SECONDARY()).arg(fincept::ui::fonts::TINY).arg(kMonoFont());
+}
+inline QString kSectionLabel() {
+ return QString("color:%1; font-size:%2px; font-weight:700; letter-spacing:0.5px; %3"
+ " background:transparent; border:none;")
+ .arg(fincept::ui::colors::AMBER()).arg(fincept::ui::fonts::TINY).arg(kMonoFont());
+}
+inline QString kComboStyle() {
+ return QString("QComboBox { background:%1; color:%2; border:1px solid %3; padding:4px 8px;"
+ " font-size:%4px; %5 } QComboBox::drop-down { border:none; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2; border:1px solid %3;"
+ " selection-background-color:%6; %5 }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::SMALL).arg(kMonoFont()).arg(fincept::ui::colors::BG_HOVER());
+}
+inline QString kSpinStyle() {
+ return QString("QSpinBox { background:%1; color:%2; border:1px solid %3; padding:4px 8px;"
+ " font-size:%4px; %5 } QSpinBox::up-button,QSpinBox::down-button { width:14px; }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::SMALL).arg(kMonoFont());
+}
+inline QString kEditStyle() {
+ return QString("QTextEdit,QLineEdit { background:%1; border:1px solid %2; color:%3; padding:6px;"
+ " font-size:%4px; %5 } QTextEdit:focus,QLineEdit:focus { border-color:%6; }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM(), fincept::ui::colors::TEXT_PRIMARY())
+ .arg(fincept::ui::fonts::SMALL).arg(kMonoFont()).arg(fincept::ui::colors::BORDER_BRIGHT());
+}
+
+} // namespace
+
+namespace fincept::screens {
+
+using namespace fincept::services::algo;
+
+static fincept::ScanWatch watch_from_form(fincept::ui::algo::ConditionSection* section,
+ fincept::ui::algo::SymbolChipInput* symbols_input,
+ QComboBox* timeframe,
+ QComboBox* data_source, QComboBox* account,
+ QSpinBox* interval, QSpinBox* cooldown,
+ QCheckBox* providers, const QString& name) {
+ fincept::ScanWatch w;
+ w.name = name;
+ w.conditions = section->conditions();
+ w.logic = section->combined_logic();
+ w.symbols = symbols_input->symbols();
+ w.timeframe = timeframe->currentText();
+ w.lookback_days = algo_default_lookback_days(w.timeframe); // auto — no UI field
+ w.data_source = data_source->currentData().toString();
+ w.account_id = account->currentData().toString();
+ if (!w.account_id.isEmpty())
+ w.broker_id = fincept::trading::AccountManager::instance().get_account(w.account_id).broker_id;
+ w.mode = QStringLiteral("poll");
+ w.interval_sec = interval->value();
+ w.cooldown_min = cooldown->value();
+ QJsonObject actions;
+ actions["toast"] = true;
+ actions["providers"] = providers->isChecked();
+ w.actions = actions;
+ w.active = true;
+ return w;
+}
+
+AlertsPanel::AlertsPanel(QWidget* parent) : QWidget(parent) {
+ build_ui();
+ connect(&fincept::algo::ScanMonitor::instance(),
+ &fincept::algo::ScanMonitor::watch_status_changed, this,
+ [this](const QString&, const QString&) { on_refresh_watches(); });
+ on_refresh_watches();
+ refresh_history();
+ LOG_INFO("AlgoTrading", "AlertsPanel constructed");
+}
+
+void AlertsPanel::build_ui() {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ auto* scroll = new QScrollArea(this);
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+ auto* content = new QWidget(this);
+ content->setStyleSheet(QString("background:%1;").arg(fincept::ui::colors::BG_BASE()));
+ auto* vl = new QVBoxLayout(content);
+ vl->setContentsMargins(16, 12, 16, 12);
+ vl->setSpacing(8);
+
+ cond_title_ = new QLabel(tr("ALERT CONDITIONS"), content);
+ cond_title_->setStyleSheet(kSectionLabel());
+ vl->addWidget(cond_title_);
+ section_ = new fincept::ui::algo::ConditionSection(
+ fincept::ui::algo::ConditionSection::Type::Entry, content);
+ vl->addWidget(section_);
+
+ sym_title_ = new QLabel(tr("SYMBOLS & FEED"), content);
+ sym_title_->setStyleSheet(kSectionLabel());
+ vl->addWidget(sym_title_);
+
+ symbols_input_ = new fincept::ui::algo::SymbolChipInput(content);
+ symbols_input_->setMinimumHeight(54);
+ vl->addWidget(symbols_input_);
+ connect(symbols_input_, &fincept::ui::algo::SymbolChipInput::price_resolved,
+ this, [this](const QString& s, double px) { prefill_close_from_price(s, px); });
+
+ auto* quick = new QHBoxLayout;
+ auto* nifty = new QPushButton("NIFTY 50", content);
+ nifty->setCursor(Qt::PointingHandCursor);
+ nifty->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:1px solid %3;"
+ " font-size:%4px; font-weight:700; %5 padding:2px 10px; }"
+ "QPushButton:hover { background:%6; color:%7; }")
+ .arg(fincept::ui::colors::BG_RAISED(), fincept::ui::colors::TEXT_SECONDARY(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::TINY).arg(kMonoFont())
+ .arg(fincept::ui::colors::BG_HOVER(), fincept::ui::colors::TEXT_PRIMARY()));
+ connect(nifty, &QPushButton::clicked, this, [this]() { symbols_input_->set_symbols(nifty50_symbols()); });
+ auto* bn = new QPushButton("BANK NIFTY", content);
+ bn->setCursor(Qt::PointingHandCursor);
+ bn->setStyleSheet(nifty->styleSheet());
+ connect(bn, &QPushButton::clicked, this, [this]() { symbols_input_->set_symbols(bank_nifty_symbols()); });
+ quick->addWidget(nifty); quick->addWidget(bn); quick->addStretch();
+ vl->addLayout(quick);
+
+ auto* grid = new QHBoxLayout;
+ auto* col1 = new QVBoxLayout; auto* col2 = new QVBoxLayout;
+
+ tf_lbl_ = new QLabel(tr("TIMEFRAME"), content); tf_lbl_->setStyleSheet(kLabelStyle());
+ timeframe_combo_ = new QComboBox(content);
+ timeframe_combo_->addItems(algo_timeframes());
+ timeframe_combo_->setCurrentIndex(algo_timeframes().indexOf("1m"));
+ timeframe_combo_->setStyleSheet(kComboStyle());
+ col1->addWidget(tf_lbl_); col1->addWidget(timeframe_combo_);
+
+ ds_lbl_ = new QLabel(tr("DATA SOURCE"), content); ds_lbl_->setStyleSheet(kLabelStyle());
+ data_source_combo_ = new QComboBox(content);
+ data_source_combo_->addItem(tr("Broker Only"), "Broker");
+ data_source_combo_->addItem(tr("Auto (Broker → YFinance)"), "Auto");
+ data_source_combo_->addItem(tr("YFinance Only"), "YFinance");
+ data_source_combo_->setStyleSheet(kComboStyle());
+ col1->addWidget(ds_lbl_); col1->addWidget(data_source_combo_);
+
+ acct_lbl_ = new QLabel(tr("BROKER ACCOUNT"), content); acct_lbl_->setStyleSheet(kLabelStyle());
+ account_combo_ = new QComboBox(content);
+ account_combo_->addItem(tr("None (use YFinance fallback)"), "");
+ for (const auto& acct : fincept::trading::AccountManager::instance().list_accounts())
+ account_combo_->addItem(QString("%1 (%2)").arg(acct.display_name, acct.broker_id), acct.account_id);
+ account_combo_->setStyleSheet(kComboStyle());
+ col1->addWidget(acct_lbl_); col1->addWidget(account_combo_);
+ connect(data_source_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int) {
+ const bool show = data_source_combo_->currentData().toString() != "YFinance";
+ account_combo_->setVisible(show); acct_lbl_->setVisible(show);
+ });
+
+ iv_lbl_ = new QLabel(tr("POLL INTERVAL (SEC)"), content); iv_lbl_->setStyleSheet(kLabelStyle());
+ interval_spin_ = new QSpinBox(content); interval_spin_->setRange(30, 86400); interval_spin_->setValue(60);
+ interval_spin_->setStyleSheet(kSpinStyle());
+ col2->addWidget(iv_lbl_); col2->addWidget(interval_spin_);
+
+ cd_lbl_ = new QLabel(tr("COOLDOWN (MIN)"), content); cd_lbl_->setStyleSheet(kLabelStyle());
+ cooldown_spin_ = new QSpinBox(content); cooldown_spin_->setRange(0, 1440); cooldown_spin_->setValue(15);
+ cooldown_spin_->setStyleSheet(kSpinStyle());
+ col2->addWidget(cd_lbl_); col2->addWidget(cooldown_spin_);
+
+ providers_chk_ = new QCheckBox(tr("Send to external providers"), content);
+ providers_chk_->setStyleSheet(kLabelStyle());
+ col2->addWidget(providers_chk_);
+ col2->addStretch();
+
+ grid->addLayout(col1, 1); grid->addLayout(col2, 1);
+ vl->addLayout(grid);
+
+ name_lbl_ = new QLabel(tr("WATCH NAME"), content); name_lbl_->setStyleSheet(kLabelStyle());
+ name_edit_ = new QLineEdit(content); name_edit_->setStyleSheet(kEditStyle());
+ name_edit_->setPlaceholderText(tr("My Volume Watch"));
+ vl->addWidget(name_lbl_); vl->addWidget(name_edit_);
+
+ save_btn_ = new QPushButton(tr("SAVE WATCH"), content);
+ save_btn_->setCursor(Qt::PointingHandCursor);
+ save_btn_->setFixedHeight(36);
+ save_btn_->setStyleSheet(QString("QPushButton { background:rgba(255,196,0,0.1); color:#FFC400;"
+ " border:1px solid #FFC400; font-size:%1px; font-weight:700; %2 padding:6px 24px; }"
+ "QPushButton:hover { background:#FFC400; color:%3; }")
+ .arg(fincept::ui::fonts::DATA).arg(kMonoFont()).arg(fincept::ui::colors::BG_BASE()));
+ connect(save_btn_, &QPushButton::clicked, this, &AlertsPanel::on_save_watch);
+ vl->addWidget(save_btn_);
+
+ status_label_ = new QLabel("", content);
+ status_label_->setWordWrap(true);
+ status_label_->setStyleSheet(kLabelStyle());
+ vl->addWidget(status_label_);
+
+ watches_title_ = new QLabel(tr("LIVE WATCHES"), content);
+ watches_title_->setStyleSheet(kSectionLabel());
+ vl->addWidget(watches_title_);
+
+ watches_table_ = new QTableWidget(0, 5, content);
+ watches_table_->setHorizontalHeaderLabels({tr("NAME"), tr("SYMBOLS"), tr("STATUS"), tr("ACTIVE"), tr("ACTIONS")});
+ watches_table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
+ watches_table_->setColumnWidth(0, 140); watches_table_->setColumnWidth(2, 90);
+ watches_table_->setColumnWidth(3, 70); watches_table_->setColumnWidth(4, 130);
+ watches_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ watches_table_->verticalHeader()->setVisible(false);
+ watches_table_->setMinimumHeight(160);
+ watches_table_->setStyleSheet(QString("QTableWidget { background:%1; border:1px solid %2;"
+ " gridline-color:%2; font-size:%3px; font-family:%4; color:%5; }"
+ "QHeaderView::section { background:%6; color:%7; font-size:%3px; font-weight:700;"
+ " font-family:%4; padding:4px 8px; border:none; border-bottom:1px solid %2; }")
+ .arg(fincept::ui::colors::BG_BASE(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::SMALL).arg(fincept::ui::fonts::DATA_FAMILY)
+ .arg(fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::BG_RAISED(),
+ fincept::ui::colors::TEXT_TERTIARY()));
+ vl->addWidget(watches_table_);
+
+ auto* hist_divider = new QFrame(content);
+ hist_divider->setFrameShape(QFrame::HLine);
+ hist_divider->setFixedHeight(1);
+ hist_divider->setStyleSheet(QString("background:%1; border:none;").arg(fincept::ui::colors::BORDER_DIM()));
+ vl->addSpacing(10);
+ vl->addWidget(hist_divider);
+ vl->addSpacing(10);
+
+ history_title_ = new QLabel(tr("ALERT HISTORY"), content);
+ history_title_->setStyleSheet(kSectionLabel());
+ vl->addWidget(history_title_);
+ history_table_ = new QTableWidget(0, 3, content);
+ history_table_->setHorizontalHeaderLabels({tr("TIME"), tr("SYMBOL"), tr("DETAIL")});
+ history_table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
+ history_table_->setColumnWidth(0, 150); history_table_->setColumnWidth(1, 120);
+ history_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ history_table_->verticalHeader()->setVisible(false);
+ history_table_->setMinimumHeight(120);
+ history_table_->setStyleSheet(watches_table_->styleSheet());
+ vl->addWidget(history_table_);
+
+ vl->addStretch();
+
+ scroll->setWidget(content);
+ root->addWidget(scroll);
+}
+
+void AlertsPanel::on_save_watch() {
+ if (section_->conditions().isEmpty()) {
+ status_label_->setText(tr("Add at least one condition before saving a watch."));
+ return;
+ }
+ QString name = name_edit_->text().trimmed();
+ if (name.isEmpty()) name = tr("Watch %1").arg(watches_table_->rowCount() + 1);
+ auto w = watch_from_form(section_, symbols_input_, timeframe_combo_, data_source_combo_,
+ account_combo_, interval_spin_, cooldown_spin_, providers_chk_, name);
+ if (w.symbols.isEmpty()) {
+ status_label_->setText(tr("Enter at least one symbol."));
+ return;
+ }
+ // Editing an existing watch → UPDATE in place + restart its monitor.
+ if (!editing_id_.isEmpty()) {
+ w.id = editing_id_;
+ auto r = fincept::ScanWatchRepository::instance().update(w);
+ if (r.is_err()) {
+ status_label_->setText(tr("Update failed: %1").arg(QString::fromStdString(r.error())));
+ return;
+ }
+ fincept::algo::ScanMonitor::instance().reload(editing_id_);
+ status_label_->setText(tr("Watch '%1' updated and re-watching.").arg(name));
+ editing_id_.clear();
+ save_btn_->setText(tr("SAVE WATCH"));
+ name_edit_->clear();
+ on_refresh_watches();
+ return;
+ }
+ auto r = fincept::ScanWatchRepository::instance().create(w);
+ if (r.is_err()) {
+ status_label_->setText(tr("Save failed: %1").arg(QString::fromStdString(r.error())));
+ return;
+ }
+ fincept::algo::ScanMonitor::instance().reload(r.value().id);
+ status_label_->setText(tr("Watch '%1' saved and monitoring.").arg(name));
+ name_edit_->clear();
+ on_refresh_watches();
+}
+
+void AlertsPanel::load_watch(const fincept::ScanWatch& w) {
+ section_->set_conditions(w.conditions, w.logic);
+ symbols_input_->set_symbols(w.symbols);
+ if (int i = timeframe_combo_->findText(w.timeframe); i >= 0) timeframe_combo_->setCurrentIndex(i);
+ if (int i = data_source_combo_->findData(w.data_source); i >= 0) data_source_combo_->setCurrentIndex(i);
+ if (int i = account_combo_->findData(w.account_id); i >= 0) account_combo_->setCurrentIndex(i);
+ interval_spin_->setValue(w.interval_sec);
+ cooldown_spin_->setValue(w.cooldown_min);
+ providers_chk_->setChecked(w.actions.value("providers").toBool(false));
+ name_edit_->setText(w.name);
+ editing_id_ = w.id;
+ save_btn_->setText(tr("UPDATE WATCH"));
+ status_label_->setText(tr("Editing '%1' — change conditions/symbols and press UPDATE WATCH.").arg(w.name));
+}
+
+void AlertsPanel::on_refresh_watches() {
+ watches_table_->setRowCount(0);
+ watches_table_->setColumnWidth(4, 200); // fit Edit / Test / Delete
+ auto r = fincept::ScanWatchRepository::instance().list_all();
+ if (r.is_err()) return;
+ for (const auto& w : r.value()) {
+ const int row = watches_table_->rowCount();
+ watches_table_->insertRow(row);
+ watches_table_->setItem(row, 0, new QTableWidgetItem(w.name));
+ watches_table_->setItem(row, 1, new QTableWidgetItem(w.symbols.join(", ")));
+ watches_table_->setItem(row, 2, new QTableWidgetItem(w.status));
+ auto* active = new QCheckBox(watches_table_);
+ active->setChecked(w.active);
+ const QString id = w.id;
+ connect(active, &QCheckBox::toggled, this, [id](bool on) {
+ fincept::ScanWatchRepository::instance().set_active(id, on);
+ fincept::algo::ScanMonitor::instance().reload(id);
+ });
+ watches_table_->setCellWidget(row, 3, active);
+ auto* cell = new QWidget(watches_table_);
+ auto* hl = new QHBoxLayout(cell); hl->setContentsMargins(2, 0, 2, 0);
+ auto* edit = new QPushButton(tr("Edit"), cell);
+ connect(edit, &QPushButton::clicked, this, [this, w]() { load_watch(w); });
+ auto* test = new QPushButton(tr("Test"), cell);
+ connect(test, &QPushButton::clicked, this, [id]() { fincept::algo::ScanMonitor::instance().test_fire(id, QString()); });
+ auto* del = new QPushButton(tr("Delete"), cell);
+ connect(del, &QPushButton::clicked, this, [this, id]() {
+ fincept::algo::ScanMonitor::instance().stop_watch(id);
+ fincept::ScanWatchRepository::instance().remove(id);
+ // Keep the fired history: deleting a live watch must NOT erase its
+ // already-triggered events from ALERT HISTORY.
+ on_refresh_watches();
+ });
+ hl->addWidget(edit); hl->addWidget(test); hl->addWidget(del);
+ watches_table_->setCellWidget(row, 4, cell);
+ }
+ refresh_history();
+}
+
+void AlertsPanel::refresh_history() {
+ history_table_->setRowCount(0);
+ auto r = fincept::ScanEventRepository::instance().recent(50);
+ if (r.is_err()) return;
+ for (const auto& e : r.value()) {
+ const int row = history_table_->rowCount();
+ history_table_->insertRow(row);
+ history_table_->setItem(row, 0, new QTableWidgetItem(
+ QDateTime::fromMSecsSinceEpoch(e.fired_at).toString("yyyy-MM-dd HH:mm:ss")));
+ history_table_->setItem(row, 1, new QTableWidgetItem(e.symbol));
+ history_table_->setItem(row, 2, new QTableWidgetItem(e.detail));
+ }
+}
+
+void AlertsPanel::prefill_close_from_price(const QString& /*symbol*/, double price) {
+ if (price <= 0) return;
+ QJsonArray conds = section_->conditions();
+ bool changed = false;
+ std::function<void(QJsonArray&)> walk = [&](QJsonArray& arr) {
+ for (int i = 0; i < arr.size(); ++i) {
+ QJsonObject o = arr[i].toObject();
+ if (o.contains("children")) { QJsonArray ch = o.value("children").toArray(); walk(ch); o["children"] = ch; }
+ else if (o.value("indicator").toString() == "CLOSE"
+ && o.value("compare_mode").toString("value") == "value"
+ && qFuzzyIsNull(o.value("value").toDouble())) {
+ o["value"] = price; changed = true;
+ }
+ arr[i] = o;
+ }
+ };
+ walk(conds);
+ if (changed) section_->set_conditions(conds, section_->combined_logic());
+}
+
+void AlertsPanel::prefill(const QJsonArray& conditions, const QString& logic,
+ const QStringList& symbols, const QString& timeframe,
+ const QString& data_source, const QString& account_id) {
+ section_->set_conditions(conditions, logic);
+ symbols_input_->set_symbols(symbols);
+ if (int i = timeframe_combo_->findText(timeframe); i >= 0) timeframe_combo_->setCurrentIndex(i);
+ if (int i = data_source_combo_->findData(data_source); i >= 0) data_source_combo_->setCurrentIndex(i);
+ if (int i = account_combo_->findData(account_id); i >= 0) account_combo_->setCurrentIndex(i);
+ editing_id_.clear();
+ save_btn_->setText(tr("SAVE WATCH"));
+ status_label_->setText(tr("Pre-filled from Scanner — name it and SAVE WATCH."));
+}
+
+void AlertsPanel::changeEvent(QEvent* e) {
+ if (e->type() == QEvent::LanguageChange) retranslateUi();
+ QWidget::changeEvent(e);
+}
+
+void AlertsPanel::retranslateUi() {
+ if (cond_title_) cond_title_->setText(tr("ALERT CONDITIONS"));
+ if (sym_title_) sym_title_->setText(tr("SYMBOLS & FEED"));
+ if (tf_lbl_) tf_lbl_->setText(tr("TIMEFRAME"));
+ if (ds_lbl_) ds_lbl_->setText(tr("DATA SOURCE"));
+ if (acct_lbl_) acct_lbl_->setText(tr("BROKER ACCOUNT"));
+ if (iv_lbl_) iv_lbl_->setText(tr("POLL INTERVAL (SEC)"));
+ if (cd_lbl_) cd_lbl_->setText(tr("COOLDOWN (MIN)"));
+ if (name_lbl_) name_lbl_->setText(tr("WATCH NAME"));
+ if (providers_chk_) providers_chk_->setText(tr("Send to external providers"));
+ if (save_btn_) save_btn_->setText(tr("SAVE WATCH"));
+ if (watches_title_) watches_title_->setText(tr("LIVE WATCHES"));
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/AlertsPanel.h b/fincept-qt/src/screens/algo_trading/AlertsPanel.h
new file mode 100644
index 000000000..c512eaf04
--- /dev/null
+++ b/fincept-qt/src/screens/algo_trading/AlertsPanel.h
@@ -0,0 +1,75 @@
+// src/screens/algo_trading/AlertsPanel.h
+#pragma once
+#include "algo_engine/ScanMonitor.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+#include "storage/repositories/ScanWatchRepository.h"
+#include "ui/widgets/algo/ConditionSection.h"
+#include "ui/widgets/algo/SymbolChipInput.h"
+
+#include <QCheckBox>
+#include <QComboBox>
+#include <QEvent>
+#include <QJsonArray>
+#include <QLabel>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QSpinBox>
+#include <QTableWidget>
+#include <QWidget>
+
+namespace fincept::screens {
+
+/// Alert/watch manager — build a condition, save it as a background watch, and
+/// manage running watches. Reuses ScanWatchRepository + ScanMonitor.
+class AlertsPanel : public QWidget {
+ Q_OBJECT
+ public:
+ explicit AlertsPanel(QWidget* parent = nullptr);
+
+ void prefill(const QJsonArray& conditions, const QString& logic,
+ const QStringList& symbols, const QString& timeframe,
+ const QString& data_source, const QString& account_id);
+
+ private slots:
+ void on_save_watch();
+ void on_refresh_watches();
+
+ protected:
+ void changeEvent(QEvent* event) override;
+
+ private:
+ void build_ui();
+ void retranslateUi();
+
+ fincept::ui::algo::ConditionSection* section_ = nullptr;
+ fincept::ui::algo::SymbolChipInput* symbols_input_ = nullptr;
+ QComboBox* timeframe_combo_ = nullptr;
+ QComboBox* data_source_combo_ = nullptr;
+ QComboBox* account_combo_ = nullptr;
+ QSpinBox* interval_spin_ = nullptr;
+ QSpinBox* cooldown_spin_ = nullptr;
+ QCheckBox* providers_chk_ = nullptr;
+ QLineEdit* name_edit_ = nullptr;
+ QPushButton* save_btn_ = nullptr;
+ QTableWidget* watches_table_ = nullptr;
+ QTableWidget* history_table_ = nullptr;
+ QLabel* status_label_ = nullptr;
+ QString editing_id_; // non-empty when editing an existing watch
+
+ QLabel* cond_title_ = nullptr;
+ QLabel* sym_title_ = nullptr;
+ QLabel* tf_lbl_ = nullptr;
+ QLabel* ds_lbl_ = nullptr;
+ QLabel* acct_lbl_ = nullptr;
+ QLabel* iv_lbl_ = nullptr;
+ QLabel* cd_lbl_ = nullptr;
+ QLabel* name_lbl_ = nullptr;
+ QLabel* watches_title_ = nullptr;
+ QLabel* history_title_ = nullptr;
+
+ void prefill_close_from_price(const QString& symbol, double price);
+ void refresh_history();
+ void load_watch(const fincept::ScanWatch& w); // load an existing watch into the form for editing
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
index c7e44f30a..3f330deec 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -4,6 +4,7 @@
#include "algo_engine/AlgoEngine.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
+#include "screens/algo_trading/AlertsPanel.h"
#include "screens/algo_trading/DeploymentDashboard.h"
#include "screens/algo_trading/ScannerPanel.h"
#include "screens/algo_trading/StrategyBuilderPanel.h"
@@ -12,6 +13,7 @@
#include "ui/theme/Theme.h"
#include <QHBoxLayout>
+#include <QJsonArray>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -24,7 +26,7 @@ AlgoTradingScreen::AlgoTradingScreen(QWidget* parent) : QWidget(parent) {
poll_timer_ = new QTimer(this);
poll_timer_->setInterval(5000);
connect(poll_timer_, &QTimer::timeout, this, [this]() {
- if (active_tab_ == 3)
+ if (active_tab_ == 4)
fincept::algo::AlgoEngine::instance().list_deployments();
});
@@ -67,12 +69,14 @@ void AlgoTradingScreen::build_ui() {
builder_ = new StrategyBuilderPanel(this);
strategies_ = new StrategyListPanel(this);
scanner_ = new ScannerPanel(this);
+ alerts_ = new AlertsPanel(this);
dashboard_ = new DeploymentDashboard(this);
- content_stack_->addWidget(builder_);
- content_stack_->addWidget(strategies_);
- content_stack_->addWidget(scanner_);
- content_stack_->addWidget(dashboard_);
+ content_stack_->addWidget(builder_); // 0
+ content_stack_->addWidget(strategies_); // 1
+ content_stack_->addWidget(scanner_); // 2
+ content_stack_->addWidget(alerts_); // 3
+ content_stack_->addWidget(dashboard_); // 4
root->addWidget(content_stack_, 1);
// "Edit" in My Strategies opens the Builder (tab 0) pre-filled with that strategy.
@@ -89,9 +93,18 @@ 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)
+ // Scanner → Alerts hand-off: pre-fills the AlertsPanel with the scan's conditions
+ // and switches to the ALERTS tab. ScannerPanel::create_alert_requested is added in R3.
+ connect(scanner_, &ScannerPanel::create_alert_requested, this,
+ [this](const QJsonArray& conds, const QString& logic, const QStringList& syms,
+ const QString& tf, const QString& ds, const QString& acct) {
+ on_tab_changed(3); // ALERTS
+ alerts_->prefill(conds, logic, syms, tf, ds, acct);
+ });
+
+ // Deploying from the Builder jumps to the Dashboard (tab 4); on_tab_changed(4)
// refreshes list_deployments() so the just-persisted row shows immediately.
- connect(builder_, &StrategyBuilderPanel::deployed, this, [this]() { on_tab_changed(3); });
+ connect(builder_, &StrategyBuilderPanel::deployed, this, [this]() { on_tab_changed(4); });
root->addWidget(build_status_bar());
setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
@@ -120,8 +133,8 @@ QWidget* AlgoTradingScreen::build_top_bar() {
hl->addWidget(div);
// Tab buttons
- QStringList tabs = {tr("BUILDER"), tr("MY STRATEGIES"), tr("SCANNER"), tr("DASHBOARD")};
- QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#00D66F"};
+ QStringList tabs = {tr("BUILDER"), tr("MY STRATEGIES"), tr("SCANNER"), tr("ALERTS"), tr("DASHBOARD")};
+ QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#FF4081", "#00D66F"};
for (int i = 0; i < tabs.size(); ++i) {
auto* btn = new QPushButton(tabs[i], bar);
@@ -190,12 +203,12 @@ void AlgoTradingScreen::on_tab_changed(int index) {
// Refresh data when switching tabs
if (index == 1)
AlgoTradingService::instance().list_strategies();
- if (index == 3)
+ if (index == 4)
fincept::algo::AlgoEngine::instance().list_deployments();
}
void AlgoTradingScreen::update_tab_buttons() {
- QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#00D66F"};
+ QStringList colors = {"#FF6B35", "#00E5FF", "#FFC400", "#FF4081", "#00D66F"};
for (int i = 0; i < tab_buttons_.size(); ++i) {
bool active = (i == active_tab_);
tab_buttons_[i]->setStyleSheet(
@@ -228,11 +241,12 @@ void AlgoTradingScreen::retranslateUi() {
if (deploy_count_label_) deploy_count_label_->setText(tr("%1 LIVE").arg(active_deployments_));
// Tab button labels — fixed order matches build_top_bar().
- if (tab_buttons_.size() == 4) {
+ if (tab_buttons_.size() == 5) {
tab_buttons_[0]->setText(tr("BUILDER"));
tab_buttons_[1]->setText(tr("MY STRATEGIES"));
tab_buttons_[2]->setText(tr("SCANNER"));
- tab_buttons_[3]->setText(tr("DASHBOARD"));
+ tab_buttons_[3]->setText(tr("ALERTS"));
+ tab_buttons_[4]->setText(tr("DASHBOARD"));
}
}
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
index 6d6b41b31..b01351a97 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.h
@@ -1,5 +1,6 @@
// src/screens/algo_trading/AlgoTradingScreen.h
#pragma once
+#include "screens/algo_trading/AlertsPanel.h"
#include "screens/common/IStatefulScreen.h"
#include "services/algo_trading/AlgoTradingTypes.h"
@@ -19,8 +20,8 @@ class StrategyListPanel;
class ScannerPanel;
class DeploymentDashboard;
-/// Algo Trading screen — 4-tab trading system builder.
-/// Tabs: Builder, My Strategies, Scanner, Dashboard
+/// Algo Trading screen — 5-tab trading system builder.
+/// Tabs: Builder, My Strategies, Scanner, Alerts, Dashboard
class AlgoTradingScreen : public QWidget, public IStatefulScreen {
Q_OBJECT
public:
@@ -50,6 +51,7 @@ class AlgoTradingScreen : public QWidget, public IStatefulScreen {
StrategyBuilderPanel* builder_ = nullptr;
StrategyListPanel* strategies_ = nullptr;
ScannerPanel* scanner_ = nullptr;
+ AlertsPanel* alerts_ = nullptr;
DeploymentDashboard* dashboard_ = nullptr;
QVector<QPushButton*> tab_buttons_;
diff --git a/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp b/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp
index 06f00fca8..25793d930 100644
--- a/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp
@@ -9,12 +9,13 @@
#include "ui/theme/Theme.h"
#include <QComboBox>
-#include <QDoubleSpinBox>
#include <QHBoxLayout>
#include <QHeaderView>
+#include <QJsonObject>
#include <QPushButton>
#include <QScrollArea>
#include <QTableWidget>
+#include <functional>
// ── Shared style constants ──────────────────────────────────────────────────
@@ -52,26 +53,17 @@ inline QString kComboStyle() {
.arg(fincept::ui::colors::BG_HOVER());
}
-inline QString kSpinStyle() {
- return QString("QDoubleSpinBox { background: %1; color: %2; border: 1px solid %3; padding: 4px 8px;"
- " font-size: %4px; %5 }"
- "QDoubleSpinBox::up-button, QDoubleSpinBox::down-button { width: 14px; }"
- "QSpinBox { background: %1; color: %2; border: 1px solid %3; padding: 4px 8px;"
- " font-size: %4px; %5 }"
- "QSpinBox::up-button, QSpinBox::down-button { width: 14px; }")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont());
-}
-
-inline QString kTextEditStyle() {
- return QString("QTextEdit { background: %1; border: 1px solid %2; color: %3; padding: 6px;"
- " font-size: %4px; %5 }"
- "QTextEdit:focus { border-color: %6; }")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM(), fincept::ui::colors::TEXT_PRIMARY())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::BORDER_BRIGHT());
+static QVector<QPair<QString, int>> range_options_for(const QString& tf) {
+ if (tf == QStringLiteral("live")) return {};
+ const int cap = fincept::services::algo::algo_default_lookback_days(tf);
+ const QVector<QPair<QString, int>> ladder = {
+ {QStringLiteral("Today"), 1}, {QStringLiteral("5D"), 5}, {QStringLiteral("1M"), 30},
+ {QStringLiteral("6M"), 180}, {QStringLiteral("1Y"), 365}};
+ QVector<QPair<QString, int>> out;
+ for (const auto& o : ladder)
+ if (o.second < cap) out.append(o);
+ out.append({QStringLiteral("Max"), cap});
+ return out;
}
} // namespace
@@ -80,109 +72,6 @@ namespace fincept::screens {
using namespace fincept::services::algo;
-// ── Helper: build a condition row ───────────────────────────────────────────
-
-static QWidget* build_condition_row(QVBoxLayout* /*owner_layout*/, QWidget* parent) {
- auto* row = new QWidget(parent);
- row->setStyleSheet(QString("background: %1; border: 1px solid %2;")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM()));
- auto* hl = new QHBoxLayout(row);
- hl->setContentsMargins(6, 4, 6, 4);
- hl->setSpacing(4);
-
- // Indicator
- auto* ind_combo = new QComboBox(row);
- ind_combo->setStyleSheet(kComboStyle());
- ind_combo->setFixedHeight(28);
- ind_combo->setMinimumWidth(120);
- const auto indicators = algo_indicators();
- for (const auto& ind : indicators)
- ind_combo->addItem(ind.label, ind.id);
-
- // Field
- auto* field_combo = new QComboBox(row);
- field_combo->setStyleSheet(kComboStyle());
- field_combo->setFixedHeight(28);
- field_combo->setMinimumWidth(90);
- QObject::connect(ind_combo, QOverload<int>::of(&QComboBox::currentIndexChanged), row,
- [field_combo, indicators](int idx) {
- field_combo->clear();
- if (idx >= 0 && idx < indicators.size())
- field_combo->addItems(indicators[idx].fields);
- });
-
- // Operator
- auto* op_combo = new QComboBox(row);
- op_combo->setStyleSheet(kComboStyle());
- op_combo->setFixedHeight(28);
- op_combo->setMinimumWidth(100);
- op_combo->addItems(algo_operators());
-
- // Value
- auto* val_spin = new QDoubleSpinBox(row);
- val_spin->setStyleSheet(kSpinStyle());
- val_spin->setFixedHeight(28);
- val_spin->setMinimumWidth(90);
- val_spin->setRange(-1e9, 1e9);
- val_spin->setDecimals(4);
- val_spin->setValue(0);
-
- // Remove
- auto* rm_btn = new QPushButton("X", row);
- rm_btn->setFixedSize(28, 28);
- rm_btn->setCursor(Qt::PointingHandCursor);
- rm_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %2;"
- " font-size: %3px; font-weight: 700; %4 }"
- "QPushButton:hover { color: %5; border-color: %5; }")
- .arg(fincept::ui::colors::TEXT_TERTIARY(), fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::NEGATIVE()));
- QObject::connect(rm_btn, &QPushButton::clicked, row, [row]() { row->deleteLater(); });
-
- hl->addWidget(ind_combo);
- hl->addWidget(field_combo);
- hl->addWidget(op_combo);
- hl->addWidget(val_spin);
- hl->addWidget(rm_btn);
-
- if (ind_combo->count() > 0)
- emit ind_combo->currentIndexChanged(0);
-
- row->setProperty("ind_combo", QVariant::fromValue(static_cast<QObject*>(ind_combo)));
- row->setProperty("field_combo", QVariant::fromValue(static_cast<QObject*>(field_combo)));
- row->setProperty("op_combo", QVariant::fromValue(static_cast<QObject*>(op_combo)));
- row->setProperty("val_spin", QVariant::fromValue(static_cast<QObject*>(val_spin)));
-
- return row;
-}
-
-static QJsonArray gather_from_layout(QVBoxLayout* layout) {
- QJsonArray arr;
- for (int i = 0; i < layout->count(); ++i) {
- auto* item = layout->itemAt(i);
- auto* row = item ? item->widget() : nullptr;
- if (!row)
- continue;
-
- auto* ind_combo = qobject_cast<QComboBox*>(row->property("ind_combo").value<QObject*>());
- auto* field_combo = qobject_cast<QComboBox*>(row->property("field_combo").value<QObject*>());
- auto* op_combo = qobject_cast<QComboBox*>(row->property("op_combo").value<QObject*>());
- auto* val_spin = qobject_cast<QDoubleSpinBox*>(row->property("val_spin").value<QObject*>());
- if (!ind_combo || !field_combo || !op_combo || !val_spin)
- continue;
-
- QJsonObject cond;
- cond["indicator"] = ind_combo->currentData().toString();
- cond["field"] = field_combo->currentText();
- cond["operator"] = op_combo->currentText();
- cond["value"] = val_spin->value();
- cond["params"] = QJsonObject{};
- arr.append(cond);
- }
- return arr;
-}
-
// ── Constructor ─────────────────────────────────────────────────────────────
ScannerPanel::ScannerPanel(QWidget* parent) : QWidget(parent) {
@@ -204,52 +93,33 @@ void ScannerPanel::connect_service() {
// ── Apply preset ────────────────────────────────────────────────────────────
void ScannerPanel::apply_preset(int index) {
- // Clear existing conditions
- while (conditions_layout_->count() > 0) {
- auto* item = conditions_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
-
const auto presets = scanner_presets();
- if (index <= 0 || index > presets.size())
+ if (index <= 0 || index > presets.size()) {
+ section_->clear_all();
return; // index 0 = "Custom"
-
- const auto& preset = presets[index - 1];
- const auto indicators = algo_indicators();
-
- for (const auto& cval : preset.conditions) {
- QJsonObject cond = cval.toObject();
- auto* row = build_condition_row(conditions_layout_, nullptr);
-
- auto* ind_combo = qobject_cast<QComboBox*>(row->property("ind_combo").value<QObject*>());
- auto* op_combo = qobject_cast<QComboBox*>(row->property("op_combo").value<QObject*>());
- auto* val_spin = qobject_cast<QDoubleSpinBox*>(row->property("val_spin").value<QObject*>());
-
- if (ind_combo) {
- QString ind_id = cond["indicator"].toString();
- for (int i = 0; i < ind_combo->count(); ++i) {
- if (ind_combo->itemData(i).toString() == ind_id) {
- ind_combo->setCurrentIndex(i);
- break;
- }
- }
- }
- if (op_combo) {
- int op_idx = op_combo->findText(cond["operator"].toString());
- if (op_idx >= 0)
- op_combo->setCurrentIndex(op_idx);
- }
- if (val_spin)
- val_spin->setValue(cond["value"].toDouble());
-
- conditions_layout_->addWidget(row);
}
-
+ const auto& preset = presets[index - 1];
+ section_->set_conditions(preset.conditions, QStringLiteral("AND"));
LOG_INFO("AlgoTrading", QString("Applied scanner preset: %1").arg(preset.name));
}
+// ── Range helper ─────────────────────────────────────────────────────────────
+
+void ScannerPanel::rebuild_range_options() {
+ const QString tf = timeframe_combo_->currentText();
+ const auto opts = range_options_for(tf);
+ const bool live = opts.isEmpty();
+ range_lbl_->setVisible(!live);
+ range_combo_->setVisible(!live);
+ if (live) return;
+ const QString prev = range_combo_->currentText();
+ range_combo_->clear();
+ for (const auto& o : opts)
+ range_combo_->addItem(o.first, o.second);
+ const int idx = range_combo_->findText(prev);
+ range_combo_->setCurrentIndex(idx >= 0 ? idx : 0);
+}
+
// ── Build UI ────────────────────────────────────────────────────────────────
void ScannerPanel::build_ui() {
@@ -302,46 +172,11 @@ void ScannerPanel::build_ui() {
connect(preset_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ScannerPanel::apply_preset);
left_vl->addWidget(preset_combo_);
- // Logic combo
- auto* logic_row = new QHBoxLayout;
- logic_row->setSpacing(8);
- logic_lbl_ = new QLabel(tr("LOGIC:"), left_col);
- logic_lbl_->setStyleSheet(kLabelStyle());
- logic_row->addWidget(logic_lbl_);
-
- logic_combo_ = new QComboBox(left_col);
- // "AND"/"OR" are passed verbatim to the scan engine as the combine logic —
- // they are code values, not display strings, so they are not translated.
- logic_combo_->addItems({"AND", "OR"});
- logic_combo_->setStyleSheet(kComboStyle());
- logic_combo_->setFixedHeight(26);
- logic_combo_->setFixedWidth(80);
- logic_row->addWidget(logic_combo_);
- logic_row->addStretch();
- left_vl->addLayout(logic_row);
-
- // Conditions container
- auto* cond_container = new QWidget(left_col);
- conditions_layout_ = new QVBoxLayout(cond_container);
- conditions_layout_->setContentsMargins(0, 0, 0, 0);
- conditions_layout_->setSpacing(4);
- left_vl->addWidget(cond_container);
-
- // Add condition button
- add_cond_btn_ = new QPushButton(tr("+ ADD CONDITION"), left_col);
- add_cond_btn_->setCursor(Qt::PointingHandCursor);
- add_cond_btn_->setFixedHeight(28);
- add_cond_btn_->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px dashed %2;"
- " font-size: %3px; font-weight: 700; %4 }"
- "QPushButton:hover { color: %5; border-color: %5; }")
- .arg(fincept::ui::colors::TEXT_TERTIARY(), fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::AMBER()));
- connect(add_cond_btn_, &QPushButton::clicked, this, [this, cond_container]() {
- conditions_layout_->addWidget(build_condition_row(conditions_layout_, cond_container));
- });
- left_vl->addWidget(add_cond_btn_);
+ // Rich condition builder (shared with Strategy Builder): params, offsets,
+ // indicator-vs-indicator RHS, nested AND/OR. Replaces the old flat rows.
+ section_ = new fincept::ui::algo::ConditionSection(
+ fincept::ui::algo::ConditionSection::Type::Entry, left_col);
+ left_vl->addWidget(section_);
left_vl->addStretch();
columns->addWidget(left_col, 1);
@@ -361,12 +196,11 @@ void ScannerPanel::build_ui() {
sym_lbl_->setStyleSheet(kLabelStyle());
right_vl->addWidget(sym_lbl_);
- symbols_edit_ = new QTextEdit(right_col);
- symbols_edit_->setStyleSheet(kTextEditStyle());
- symbols_edit_->setFixedHeight(120);
- // Placeholder shows literal example ticker symbols (data) — left untranslated.
- symbols_edit_->setPlaceholderText("RELIANCE\nTCS\nINFY\n...");
- right_vl->addWidget(symbols_edit_);
+ symbols_input_ = new fincept::ui::algo::SymbolChipInput(right_col);
+ symbols_input_->setMinimumHeight(54);
+ right_vl->addWidget(symbols_input_);
+ connect(symbols_input_, &fincept::ui::algo::SymbolChipInput::price_resolved,
+ this, [this](const QString& s, double px) { prefill_close_from_price(s, px); });
// Quick-add buttons
auto* quick_row = new QHBoxLayout;
@@ -384,7 +218,7 @@ void ScannerPanel::build_ui() {
.arg(kMonoFont())
.arg(fincept::ui::colors::BG_HOVER(), fincept::ui::colors::TEXT_PRIMARY()));
connect(nifty_btn, &QPushButton::clicked, this,
- [this]() { symbols_edit_->setPlainText(nifty50_symbols().join("\n")); });
+ [this]() { symbols_input_->set_symbols(nifty50_symbols()); });
quick_row->addWidget(nifty_btn);
auto* banknifty_btn = new QPushButton("BANK NIFTY", right_col);
@@ -392,7 +226,7 @@ void ScannerPanel::build_ui() {
banknifty_btn->setFixedHeight(26);
banknifty_btn->setStyleSheet(nifty_btn->styleSheet());
connect(banknifty_btn, &QPushButton::clicked, this,
- [this]() { symbols_edit_->setPlainText(bank_nifty_symbols().join("\n")); });
+ [this]() { symbols_input_->set_symbols(bank_nifty_symbols()); });
quick_row->addWidget(banknifty_btn);
quick_row->addStretch();
@@ -410,17 +244,19 @@ void ScannerPanel::build_ui() {
timeframe_combo_->setCurrentIndex(algo_timeframes().indexOf("1d"));
right_vl->addWidget(timeframe_combo_);
- // Lookback
- lb_lbl_ = new QLabel(tr("LOOKBACK (DAYS)"), right_col);
- lb_lbl_->setStyleSheet(kLabelStyle());
- right_vl->addWidget(lb_lbl_);
+ // Range (replaces lookback spinbox — adapts to timeframe)
+ range_lbl_ = new QLabel(tr("RANGE"), right_col);
+ range_lbl_->setStyleSheet(kLabelStyle());
+ right_vl->addWidget(range_lbl_);
- lookback_spin_ = new QSpinBox(right_col);
- lookback_spin_->setStyleSheet(kSpinStyle());
- lookback_spin_->setFixedHeight(30);
- lookback_spin_->setRange(1, 3650);
- lookback_spin_->setValue(365);
- right_vl->addWidget(lookback_spin_);
+ range_combo_ = new QComboBox(right_col);
+ range_combo_->setStyleSheet(kComboStyle());
+ range_combo_->setFixedHeight(30);
+ right_vl->addWidget(range_combo_);
+
+ connect(timeframe_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ [this](int) { rebuild_range_options(); });
+ rebuild_range_options();
// Data source
ds_lbl_ = new QLabel(tr("DATA SOURCE"), right_col);
@@ -478,6 +314,27 @@ void ScannerPanel::build_ui() {
connect(scan_btn_, &QPushButton::clicked, this, &ScannerPanel::on_scan);
main_vl->addWidget(scan_btn_);
+ // + CREATE ALERT button
+ auto* create_alert_btn = new QPushButton(tr("+ CREATE ALERT"), content);
+ create_alert_btn->setCursor(Qt::PointingHandCursor);
+ create_alert_btn->setFixedHeight(38);
+ create_alert_btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1;"
+ " border:1px solid %2; font-size:%3px; font-weight:700; %4 padding:6px 24px; }"
+ "QPushButton:hover { color:%5; border-color:%5; }")
+ .arg(fincept::ui::colors::TEXT_SECONDARY(), fincept::ui::colors::BORDER_DIM())
+ .arg(fincept::ui::fonts::DATA).arg(QString("font-family:%1;").arg(fincept::ui::fonts::DATA_FAMILY))
+ .arg(fincept::ui::colors::AMBER()));
+ connect(create_alert_btn, &QPushButton::clicked, this, [this]() {
+ const QJsonArray conds = section_->conditions();
+ if (conds.isEmpty()) { status_label_->setText(tr("Add a condition first.")); return; }
+ QStringList syms = symbols_input_->symbols();
+ emit create_alert_requested(conds, section_->combined_logic(), syms,
+ timeframe_combo_->currentText(),
+ data_source_combo_->currentData().toString(),
+ account_combo_->currentData().toString());
+ });
+ main_vl->addWidget(create_alert_btn);
+
// Status
status_label_ = new QLabel("", content);
status_label_->setWordWrap(true);
@@ -528,6 +385,7 @@ void ScannerPanel::build_ui() {
.arg(fincept::ui::colors::TEXT_TERTIARY())
.arg(fincept::ui::colors::BG_HOVER()));
main_vl->addWidget(results_table_);
+
main_vl->addStretch();
scroll->setWidget(content);
@@ -537,7 +395,7 @@ void ScannerPanel::build_ui() {
// ── Slots ───────────────────────────────────────────────────────────────────
void ScannerPanel::on_scan() {
- QJsonArray conditions = gather_from_layout(conditions_layout_);
+ QJsonArray conditions = section_->conditions();
if (conditions.isEmpty()) {
status_label_->setText(tr("Add at least one scan condition."));
status_label_->setStyleSheet(QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
@@ -548,8 +406,8 @@ void ScannerPanel::on_scan() {
}
// Parse symbols
- QString raw = symbols_edit_->toPlainText().trimmed();
- if (raw.isEmpty()) {
+ QStringList symbols = symbols_input_->symbols();
+ if (symbols.isEmpty()) {
status_label_->setText(tr("Enter symbols to scan."));
status_label_->setStyleSheet(QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
.arg(fincept::ui::colors::NEGATIVE())
@@ -558,13 +416,6 @@ void ScannerPanel::on_scan() {
return;
}
- QStringList symbols;
- for (const auto& line : raw.split(QRegularExpression("[,\\n\\r]+"), Qt::SkipEmptyParts)) {
- QString s = line.trimmed().toUpper();
- if (!s.isEmpty())
- symbols.append(s);
- }
-
status_label_->setText(tr("Scanning %1 symbols...").arg(symbols.size()));
status_label_->setStyleSheet(QString("color: #FFC400; font-size: %1px; %2 background: transparent; border: none;")
.arg(fincept::ui::fonts::SMALL)
@@ -582,9 +433,13 @@ void ScannerPanel::on_scan() {
}
}
+ const int lookback_days = range_combo_->isVisible()
+ ? range_combo_->currentData().toInt()
+ : algo_default_lookback_days(timeframe_combo_->currentText());
+
fincept::algo::AlgoScanner::instance().scan(
conditions, symbols, timeframe_combo_->currentText(),
- lookback_spin_->value(), logic_combo_->currentText(),
+ lookback_days, section_->combined_logic(),
source, broker_id, account_id);
LOG_INFO("AlgoTrading",
@@ -704,12 +559,10 @@ void ScannerPanel::changeEvent(QEvent* event) {
void ScannerPanel::retranslateUi() {
if (cond_title_) cond_title_->setText(tr("SCAN CONDITIONS"));
if (preset_lbl_) preset_lbl_->setText(tr("PRESET"));
- if (logic_lbl_) logic_lbl_->setText(tr("LOGIC:"));
- if (add_cond_btn_) add_cond_btn_->setText(tr("+ ADD CONDITION"));
if (sym_title_) sym_title_->setText(tr("SYMBOLS & PARAMETERS"));
if (sym_lbl_) sym_lbl_->setText(tr("SYMBOLS (comma or newline separated)"));
if (tf_lbl_) tf_lbl_->setText(tr("TIMEFRAME"));
- if (lb_lbl_) lb_lbl_->setText(tr("LOOKBACK (DAYS)"));
+ if (range_lbl_) range_lbl_->setText(tr("RANGE"));
if (ds_lbl_) ds_lbl_->setText(tr("DATA SOURCE"));
if (acct_lbl_) acct_lbl_->setText(tr("BROKER ACCOUNT"));
if (scan_btn_) scan_btn_->setText(tr("SCAN MARKET"));
@@ -738,4 +591,26 @@ void ScannerPanel::retranslateUi() {
// Result-row signal labels (BULLISH/BEARISH/NEUTRAL) re-render on the next scan.
}
+// ── CLOSE pre-fill helper ─────────────────────────────────────────────────────
+
+void ScannerPanel::prefill_close_from_price(const QString& /*symbol*/, double price) {
+ if (price <= 0) return;
+ QJsonArray conds = section_->conditions();
+ bool changed = false;
+ std::function<void(QJsonArray&)> walk = [&](QJsonArray& arr) {
+ for (int i = 0; i < arr.size(); ++i) {
+ QJsonObject o = arr[i].toObject();
+ if (o.contains("children")) { QJsonArray ch = o.value("children").toArray(); walk(ch); o["children"] = ch; }
+ else if (o.value("indicator").toString() == "CLOSE"
+ && o.value("compare_mode").toString("value") == "value"
+ && qFuzzyIsNull(o.value("value").toDouble())) {
+ o["value"] = price; changed = true;
+ }
+ arr[i] = o;
+ }
+ };
+ walk(conds);
+ if (changed) section_->set_conditions(conds, section_->combined_logic());
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/ScannerPanel.h b/fincept-qt/src/screens/algo_trading/ScannerPanel.h
index 160b2c877..980f73b6f 100644
--- a/fincept-qt/src/screens/algo_trading/ScannerPanel.h
+++ b/fincept-qt/src/screens/algo_trading/ScannerPanel.h
@@ -1,6 +1,8 @@
// src/screens/algo_trading/ScannerPanel.h
#pragma once
#include "services/algo_trading/AlgoTradingTypes.h"
+#include "ui/widgets/algo/ConditionSection.h"
+#include "ui/widgets/algo/SymbolChipInput.h"
#include <QComboBox>
#include <QEvent>
@@ -22,6 +24,11 @@ class ScannerPanel : public QWidget {
public:
explicit ScannerPanel(QWidget* parent = nullptr);
+ signals:
+ void create_alert_requested(const QJsonArray& conditions, const QString& logic,
+ const QStringList& symbols, const QString& timeframe,
+ const QString& data_source, const QString& account_id);
+
private slots:
void on_scan();
void on_scan_result(const QJsonObject& data);
@@ -35,13 +42,14 @@ class ScannerPanel : public QWidget {
void connect_service();
void apply_preset(int index);
void retranslateUi();
+ void rebuild_range_options();
+ void prefill_close_from_price(const QString& symbol, double price);
- QVBoxLayout* conditions_layout_ = nullptr;
- QTextEdit* symbols_edit_ = nullptr;
+ fincept::ui::algo::ConditionSection* section_ = nullptr;
+ fincept::ui::algo::SymbolChipInput* symbols_input_ = nullptr;
QComboBox* timeframe_combo_ = nullptr;
- QSpinBox* lookback_spin_ = nullptr;
+ QComboBox* range_combo_ = nullptr;
QComboBox* preset_combo_ = nullptr;
- QComboBox* logic_combo_ = nullptr;
QComboBox* data_source_combo_ = nullptr;
QComboBox* account_combo_ = nullptr;
QTableWidget* results_table_ = nullptr;
@@ -50,12 +58,10 @@ class ScannerPanel : public QWidget {
// Static text-bearing widgets cached for retranslateUi.
QLabel* cond_title_ = nullptr;
QLabel* preset_lbl_ = nullptr;
- QLabel* logic_lbl_ = nullptr;
- QPushButton* add_cond_btn_ = nullptr;
QLabel* sym_title_ = nullptr;
QLabel* sym_lbl_ = nullptr;
QLabel* tf_lbl_ = nullptr;
- QLabel* lb_lbl_ = nullptr;
+ QLabel* range_lbl_ = nullptr;
QLabel* ds_lbl_ = nullptr;
QLabel* acct_lbl_ = nullptr;
QPushButton* scan_btn_ = nullptr;
diff --git a/fincept-qt/src/screens/common/feeds/FeedCardView.cpp b/fincept-qt/src/screens/common/feeds/FeedCardView.cpp
new file mode 100644
index 000000000..ce8f6ca21
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedCardView.cpp
@@ -0,0 +1,116 @@
+#include "screens/common/feeds/FeedCardView.h"
+
+#include "ui/theme/Theme.h"
+
+#include <QDateTime>
+#include <QDesktopServices>
+#include <QFrame>
+#include <QLabel>
+#include <QMouseEvent>
+#include <QScrollArea>
+#include <QUrl>
+#include <QVBoxLayout>
+
+#include <utility>
+
+namespace fincept::feeds {
+
+namespace {
+
+QString relative_time(qint64 ts) {
+ if (ts == 0)
+ return {};
+ const qint64 d = QDateTime::currentSecsSinceEpoch() - ts;
+ if (d < 60)
+ return QStringLiteral("just now");
+ if (d < 3600)
+ return QString("%1m ago").arg(d / 60);
+ if (d < 86400)
+ return QString("%1h ago").arg(d / 3600);
+ return QString("%1d ago").arg(d / 86400);
+}
+
+/// A QFrame that opens a URL on left-click.
+class ClickableCard : public QFrame {
+ public:
+ ClickableCard(QString url, QWidget* parent) : QFrame(parent), url_(std::move(url)) {
+ setCursor(url_.isEmpty() ? Qt::ArrowCursor : Qt::PointingHandCursor);
+ }
+
+ protected:
+ void mousePressEvent(QMouseEvent* e) override {
+ if (e->button() == Qt::LeftButton && !url_.isEmpty())
+ QDesktopServices::openUrl(QUrl(url_));
+ QFrame::mousePressEvent(e);
+ }
+
+ private:
+ QString url_;
+};
+
+} // namespace
+
+FeedCardView::FeedCardView(QWidget* parent) : QWidget(parent) {
+ auto* outer = new QVBoxLayout(this);
+ outer->setContentsMargins(0, 0, 0, 0);
+ scroll_ = new QScrollArea(this);
+ scroll_->setWidgetResizable(true);
+ scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ scroll_->setFrameShape(QFrame::NoFrame);
+ auto* host = new QWidget;
+ list_ = new QVBoxLayout(host);
+ list_->setContentsMargins(6, 6, 6, 6);
+ list_->setSpacing(6);
+ list_->addStretch();
+ scroll_->setWidget(host);
+ outer->addWidget(scroll_);
+}
+
+QWidget* FeedCardView::build_card(const FeedItem& it) {
+ using namespace fincept::ui;
+ auto* card = new ClickableCard(it.link, nullptr);
+ card->setObjectName("feedCard");
+ card->setStyleSheet(QString("#feedCard{background:%1;border:1px solid %2;border-radius:4px;}"
+ "#feedCard:hover{background:%3;}")
+ .arg(colors::BG_SURFACE(), colors::BORDER_MED(), colors::BG_HOVER()));
+ auto* v = new QVBoxLayout(card);
+ v->setContentsMargins(8, 6, 8, 6);
+ v->setSpacing(3);
+
+ const QString rel = relative_time(it.sort_ts);
+ const QString when = rel.isEmpty() ? it.time : rel; // fall back to the absolute string
+ auto* meta = new QLabel(when.isEmpty() ? QString("● %1").arg(it.source)
+ : QString("● %1 · %2").arg(it.source, when));
+ meta->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;").arg(colors::TEXT_TERTIARY()));
+ if (!it.time.isEmpty())
+ meta->setToolTip(it.time); // absolute parsed timestamp on hover
+ v->addWidget(meta);
+
+ auto* title = new QLabel(it.title);
+ title->setWordWrap(true);
+ title->setStyleSheet(QString("color:%1;font-size:12px;font-weight:600;").arg(colors::TEXT_PRIMARY()));
+ v->addWidget(title);
+
+ if (!it.summary.isEmpty()) {
+ auto* sum = new QLabel(it.summary);
+ sum->setWordWrap(true);
+ sum->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
+ v->addWidget(sum);
+ }
+ return card;
+}
+
+void FeedCardView::set_items(const QVector<FeedItem>& items) {
+ // Clear existing cards (keep the trailing stretch at the end).
+ while (list_->count() > 1) {
+ QLayoutItem* item = list_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ int idx = 0;
+ for (const auto& it : items)
+ list_->insertWidget(idx++, build_card(it));
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedCardView.h b/fincept-qt/src/screens/common/feeds/FeedCardView.h
new file mode 100644
index 000000000..0125c14c4
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedCardView.h
@@ -0,0 +1,26 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+
+#include <QVector>
+#include <QWidget>
+
+class QVBoxLayout;
+class QScrollArea;
+
+namespace fincept::feeds {
+
+/// Renders feed items as news-style cards in a vertical scroll area.
+/// Source dot + relative time, bold title, dim summary; click -> open link.
+class FeedCardView : public QWidget {
+ Q_OBJECT
+ public:
+ explicit FeedCardView(QWidget* parent = nullptr);
+ void set_items(const QVector<FeedItem>& items);
+
+ private:
+ QWidget* build_card(const FeedItem& it);
+ QScrollArea* scroll_ = nullptr;
+ QVBoxLayout* list_ = nullptr;
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp b/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp
new file mode 100644
index 000000000..3392959f1
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedConfigDialog.cpp
@@ -0,0 +1,354 @@
+#include "screens/common/feeds/FeedConfigDialog.h"
+
+#include "services/feeds/FeedMonitor.h"
+
+#include <QCheckBox>
+#include <QComboBox>
+#include <QDialogButtonBox>
+#include <QFormLayout>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QLineEdit>
+#include <QMessageBox>
+#include <QPointer>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QSpinBox>
+#include <QToolButton>
+#include <QUuid>
+#include <QVBoxLayout>
+
+namespace fincept::feeds {
+
+namespace {
+
+// Best-guess semantic role for a discovered tag path.
+QString guess_role(const QString& path) {
+ const QString p = path.toLower();
+ if (p.contains("title") || p == "headline" || p == "name")
+ return "title";
+ if (p.contains("desc") || p.contains("summary") || p.contains("abstract") || p.contains("content") ||
+ p.contains("encoded"))
+ return "summary";
+ if (p == "link" || p.contains("url") || p.contains("href") || p == "guid" || p == "id")
+ return "link";
+ if (p.contains("pubdate") || p.contains("published") || p.contains("updated") || p == "date" ||
+ p.contains("time") || p.contains("created"))
+ return "time";
+ return {};
+}
+
+// Human-friendly default column name from a tag path.
+QString pretty_label(const QString& path) {
+ QString s = path;
+ const int at = s.indexOf('@');
+ if (at > 0)
+ s = s.left(at); // drop attribute suffix for the label
+ const int dot = s.lastIndexOf('.');
+ if (dot >= 0)
+ s = s.mid(dot + 1);
+ s.replace('_', ' ').replace('-', ' ');
+ if (!s.isEmpty())
+ s[0] = s[0].toUpper();
+ return s;
+}
+
+} // namespace
+
+FeedConfigDialog::FeedConfigDialog(const FeedSubscription& initial, QWidget* parent)
+ : QDialog(parent), sub_(initial) {
+ setWindowTitle(initial.id.isEmpty() ? tr("Add Feed") : tr("Edit Feed"));
+ setMinimumWidth(520);
+
+ auto* root = new QVBoxLayout(this);
+ auto* form = new QFormLayout;
+
+ name_ = new QLineEdit;
+ url_ = new QLineEdit;
+ url_->setPlaceholderText(QStringLiteral("https://example.com/feed.xml"));
+ refresh_ = new QSpinBox;
+ refresh_->setRange(15, 86400);
+ refresh_->setSuffix(tr(" s"));
+ refresh_->setValue(300);
+ display_ = new QComboBox;
+ display_->addItems({tr("Cards"), tr("Table")});
+ parse_ = new QComboBox;
+ parse_->addItems({tr("Auto"), tr("Manual")});
+ format_ = new QComboBox;
+ format_->addItems({"auto", "rss", "atom", "xml", "json", "csv"});
+ persist_ = new QCheckBox(tr("Store history (offline cache + past items)"));
+ persist_->setChecked(true);
+ persist_->setToolTip(tr("Keep fetched items in the local database so they show when the feed is "
+ "unreachable, and can be queried later."));
+
+ form->addRow(tr("Name"), name_);
+ form->addRow(tr("URL"), url_);
+ form->addRow(tr("Refresh"), refresh_);
+ form->addRow(tr("Display"), display_);
+ form->addRow(tr("Parse"), parse_);
+ form->addRow(tr("Format"), format_);
+ form->addRow(QString(), persist_);
+ root->addLayout(form);
+
+ // ── Manual-mapping section ───────────────────────────────────────────────
+ manual_box_ = new QWidget;
+ auto* mv = new QVBoxLayout(manual_box_);
+ mv->setContentsMargins(0, 6, 0, 0);
+ mv->setSpacing(6);
+
+ auto* recRow = new QHBoxLayout;
+ recRow->addWidget(new QLabel(tr("Records")));
+ item_combo_ = new QComboBox;
+ item_combo_->setEditable(true);
+ item_combo_->setToolTip(tr("The repeating tag/element that marks one entry (auto-filled by Discover)."));
+ recRow->addWidget(item_combo_, 1);
+ mv->addLayout(recRow);
+
+ auto* discRow = new QHBoxLayout;
+ auto* discoverBtn = new QPushButton(tr("🔍 Discover fields from feed"));
+ discoverBtn->setCursor(Qt::PointingHandCursor);
+ discRow->addWidget(discoverBtn);
+ discover_status_ = new QLabel;
+ discover_status_->setStyleSheet("color:#888;");
+ discRow->addWidget(discover_status_, 1);
+ mv->addLayout(discRow);
+
+ auto* hint = new QLabel(tr("Pick what each tag is, rename it, or remove it. Add your own with “+ Add field”."));
+ hint->setWordWrap(true);
+ hint->setStyleSheet("color:#888;font-size:10px;");
+ mv->addWidget(hint);
+
+ auto* scroll = new QScrollArea;
+ scroll->setWidgetResizable(true);
+ scroll->setMinimumHeight(160);
+ scroll->setFrameShape(QFrame::StyledPanel);
+ auto* fieldsHost = new QWidget;
+ fields_layout_ = new QVBoxLayout(fieldsHost);
+ fields_layout_->setContentsMargins(4, 4, 4, 4);
+ fields_layout_->setSpacing(3);
+ fields_layout_->addStretch(); // rows insert before this so they stay top-aligned
+ scroll->setWidget(fieldsHost);
+ mv->addWidget(scroll, 1);
+
+ auto* addFieldBtn = new QPushButton(tr("+ Add field"));
+ addFieldBtn->setCursor(Qt::PointingHandCursor);
+ mv->addWidget(addFieldBtn, 0, Qt::AlignLeft);
+
+ root->addWidget(manual_box_);
+
+ // ── Test + buttons ───────────────────────────────────────────────────────
+ auto* testBtn = new QPushButton(tr("Test / Preview"));
+ test_result_ = new QLabel;
+ test_result_->setWordWrap(true);
+ root->addWidget(testBtn);
+ root->addWidget(test_result_);
+
+ auto* bb = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
+ if (!initial.id.isEmpty()) { // existing feed -> offer Delete
+ auto* del = bb->addButton(tr("Delete"), QDialogButtonBox::DestructiveRole);
+ del->setCursor(Qt::PointingHandCursor);
+ connect(del, &QPushButton::clicked, this, [this]() {
+ const auto r = QMessageBox::question(
+ this, tr("Delete feed"),
+ tr("Delete this feed and its stored history? This cannot be undone."),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (r == QMessageBox::Yes) {
+ delete_requested_ = true;
+ accept();
+ }
+ });
+ }
+ root->addWidget(bb);
+
+ apply(initial);
+ update_manual_visibility();
+ connect(parse_, &QComboBox::currentIndexChanged, this, [this]() { update_manual_visibility(); });
+ connect(discoverBtn, &QPushButton::clicked, this, &FeedConfigDialog::on_discover);
+ connect(addFieldBtn, &QPushButton::clicked, this, [this]() { add_field_row({}); });
+ connect(testBtn, &QPushButton::clicked, this, &FeedConfigDialog::on_test);
+ connect(bb, &QDialogButtonBox::accepted, this, [this]() {
+ sub_ = collect();
+ accept();
+ });
+ connect(bb, &QDialogButtonBox::rejected, this, &QDialog::reject);
+}
+
+void FeedConfigDialog::update_manual_visibility() {
+ manual_box_->setVisible(parse_->currentIndex() == 1);
+}
+
+QWidget* FeedConfigDialog::add_field_row(const MappedField& f) {
+ auto* row = new QWidget;
+ auto* hl = new QHBoxLayout(row);
+ hl->setContentsMargins(0, 0, 0, 0);
+ hl->setSpacing(4);
+
+ auto* role = new QComboBox;
+ role->setObjectName("role");
+ role->addItem(tr("Column"), "");
+ role->addItem(tr("Title"), "title");
+ role->addItem(tr("Summary"), "summary");
+ role->addItem(tr("Link"), "link");
+ role->addItem(tr("Time"), "time");
+ const int ri = role->findData(f.role);
+ role->setCurrentIndex(ri < 0 ? 0 : ri);
+ role->setFixedWidth(92);
+ role->setToolTip(tr("Title/Summary/Link/Time feed the card view; Column shows only in the table."));
+ hl->addWidget(role);
+
+ auto* label = new QLineEdit(f.label);
+ label->setObjectName("label");
+ label->setPlaceholderText(tr("Display name"));
+ hl->addWidget(label, 1);
+
+ auto* source = new QComboBox;
+ source->setObjectName("source");
+ source->setEditable(true);
+ source->addItems(discovered_paths_);
+ if (!f.path.isEmpty() && source->findText(f.path) < 0)
+ source->insertItem(0, f.path);
+ source->setCurrentText(f.path);
+ source->setToolTip(tr("Which feed tag to read this from."));
+ hl->addWidget(source, 1);
+
+ auto* rm = new QToolButton;
+ rm->setText(QStringLiteral("✕"));
+ rm->setToolTip(tr("Remove"));
+ rm->setAutoRaise(true);
+ rm->setCursor(Qt::PointingHandCursor);
+ hl->addWidget(rm);
+
+ // Insert before the trailing stretch so rows stay top-aligned.
+ fields_layout_->insertWidget(fields_layout_->count() - 1, row);
+ field_rows_.append(row);
+ connect(rm, &QToolButton::clicked, this, [this, row]() {
+ field_rows_.removeOne(row);
+ row->deleteLater();
+ });
+ return row;
+}
+
+void FeedConfigDialog::clear_field_rows() {
+ for (QWidget* row : field_rows_)
+ row->deleteLater();
+ field_rows_.clear();
+}
+
+void FeedConfigDialog::apply(const FeedSubscription& s) {
+ name_->setText(s.name);
+ url_->setText(s.url);
+ refresh_->setValue(qMax(15, s.refresh_sec));
+ display_->setCurrentIndex(s.display_mode == DisplayMode::Table ? 1 : 0);
+ parse_->setCurrentIndex(s.parse_mode == ParseMode::Manual ? 1 : 0);
+ format_->setCurrentText(to_token(s.format));
+ persist_->setChecked(s.persist);
+ item_combo_->setCurrentText(s.mapping.item_selector);
+
+ discovered_paths_.clear();
+ for (const auto& f : s.mapping.fields)
+ if (!f.path.isEmpty() && !discovered_paths_.contains(f.path))
+ discovered_paths_ << f.path;
+ clear_field_rows();
+ for (const auto& f : s.mapping.fields)
+ add_field_row(f);
+}
+
+FeedSubscription FeedConfigDialog::collect() const {
+ FeedSubscription s = sub_;
+ if (s.id.isEmpty())
+ s.id = "feed-" + QUuid::createUuid().toString(QUuid::WithoutBraces);
+ s.name = name_->text().trimmed();
+ s.url = url_->text().trimmed();
+ s.refresh_sec = refresh_->value();
+ s.display_mode = display_->currentIndex() == 1 ? DisplayMode::Table : DisplayMode::Cards;
+ s.parse_mode = parse_->currentIndex() == 1 ? ParseMode::Manual : ParseMode::Auto;
+ s.format = feed_format_from(format_->currentText());
+ s.persist = persist_->isChecked();
+
+ FieldMapping m;
+ m.item_selector = item_combo_->currentText().trimmed();
+ for (QWidget* row : field_rows_) {
+ auto* source = row->findChild<QComboBox*>("source");
+ if (!source)
+ continue;
+ const QString path = source->currentText().trimmed();
+ if (path.isEmpty())
+ continue;
+ auto* role = row->findChild<QComboBox*>("role");
+ auto* label = row->findChild<QLineEdit*>("label");
+ MappedField f;
+ f.path = path;
+ f.role = role ? role->currentData().toString() : QString();
+ f.label = label ? label->text().trimmed() : QString();
+ if (f.label.isEmpty())
+ f.label = pretty_label(path);
+ m.fields.append(f);
+ }
+ s.mapping = m;
+ s.enabled = true;
+ if (s.name.isEmpty())
+ s.name = s.url;
+ return s;
+}
+
+void FeedConfigDialog::on_discover() {
+ discover_status_->setText(tr("Discovering…"));
+ QPointer<FeedConfigDialog> self(this);
+ FeedMonitor::instance().discover(collect(), [self](bool ok, const QString& msg, const DiscoveredSchema& schema) {
+ if (!self)
+ return;
+ self->discover_status_->setText((ok ? QStringLiteral("✓ ") : QStringLiteral("✗ ")) + msg);
+ if (ok)
+ self->apply_discovery(schema);
+ });
+}
+
+void FeedConfigDialog::apply_discovery(const DiscoveredSchema& schema) {
+ // Repeating-record selector.
+ const QString keepItem = item_combo_->currentText();
+ item_combo_->clear();
+ item_combo_->addItems(schema.item_options);
+ const QString chosen = schema.item_selector.isEmpty() ? keepItem : schema.item_selector;
+ if (!chosen.isEmpty()) {
+ if (item_combo_->findText(chosen) < 0)
+ item_combo_->insertItem(0, chosen);
+ item_combo_->setCurrentText(chosen);
+ }
+
+ // Available tags for every row's dropdown.
+ discovered_paths_.clear();
+ for (const auto& d : schema.fields)
+ discovered_paths_ << d.path;
+
+ // Rebuild rows with smart defaults; show a sample value as the source tooltip.
+ clear_field_rows();
+ for (const auto& d : schema.fields) {
+ MappedField f;
+ f.path = d.path;
+ f.role = guess_role(d.path);
+ f.label = pretty_label(d.path);
+ QWidget* row = add_field_row(f);
+ if (auto* src = row->findChild<QComboBox*>("source"))
+ if (!d.sample.isEmpty())
+ src->setToolTip(tr("e.g. %1").arg(d.sample));
+ }
+
+ // Reflect the detected format so parsing matches.
+ if (!schema.format.isEmpty()) {
+ const int fi = format_->findText(schema.format);
+ if (fi >= 0)
+ format_->setCurrentIndex(fi);
+ }
+}
+
+void FeedConfigDialog::on_test() {
+ test_result_->setText(tr("Testing…"));
+ FeedMonitor::instance().fetch_once(collect(), [this](bool ok, const QString& msg, const QVector<FeedItem>& items) {
+ QString detail = msg;
+ for (int i = 0; i < items.size() && i < 3; ++i)
+ detail += "\n• " + (items[i].title.isEmpty() ? items[i].link : items[i].title);
+ test_result_->setText((ok ? QStringLiteral("✓ ") : QStringLiteral("✗ ")) + detail);
+ });
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedConfigDialog.h b/fincept-qt/src/screens/common/feeds/FeedConfigDialog.h
new file mode 100644
index 000000000..94f8287f3
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedConfigDialog.h
@@ -0,0 +1,60 @@
+#pragma once
+#include "services/feeds/FeedScraper.h" // DiscoveredSchema
+#include "services/feeds/FeedTypes.h"
+
+#include <QDialog>
+#include <QStringList>
+#include <QVector>
+
+class QLineEdit;
+class QComboBox;
+class QSpinBox;
+class QLabel;
+class QWidget;
+class QVBoxLayout;
+class QCheckBox;
+
+namespace fincept::feeds {
+
+/// Add/edit one FeedSubscription. Manual parse mode offers one-click field discovery
+/// — fetch the feed once, list every tag, and let the user pick/rename/role them via
+/// dropdowns (no path syntax). Fields are unlimited and fully editable.
+class FeedConfigDialog : public QDialog {
+ Q_OBJECT
+ public:
+ explicit FeedConfigDialog(const FeedSubscription& initial, QWidget* parent = nullptr);
+ FeedSubscription result_subscription() const { return sub_; }
+ bool delete_requested() const { return delete_requested_; }
+
+ private:
+ FeedSubscription collect() const; // read widgets -> FeedSubscription
+ void apply(const FeedSubscription& s);
+ void on_test();
+ void on_discover();
+ void apply_discovery(const DiscoveredSchema& schema);
+ void update_manual_visibility();
+ QWidget* add_field_row(const MappedField& f); // append a mapping row, return container
+ void clear_field_rows();
+
+ FeedSubscription sub_;
+ QLineEdit* name_ = nullptr;
+ QLineEdit* url_ = nullptr;
+ QSpinBox* refresh_ = nullptr;
+ QComboBox* display_ = nullptr;
+ QComboBox* parse_ = nullptr;
+ QComboBox* format_ = nullptr;
+ QCheckBox* persist_ = nullptr; // store items for offline cache + history
+
+ // Manual-mapping section
+ QWidget* manual_box_ = nullptr;
+ QComboBox* item_combo_ = nullptr; // repeating record selector (editable)
+ QLabel* discover_status_ = nullptr;
+ QVBoxLayout* fields_layout_ = nullptr; // holds the row widgets + a trailing stretch
+ QVector<QWidget*> field_rows_;
+ QStringList discovered_paths_; // populates each row's source dropdown
+
+ QLabel* test_result_ = nullptr;
+ bool delete_requested_ = false;
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedPanel.cpp b/fincept-qt/src/screens/common/feeds/FeedPanel.cpp
new file mode 100644
index 000000000..d435beeb1
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedPanel.cpp
@@ -0,0 +1,168 @@
+#include "screens/common/feeds/FeedPanel.h"
+
+#include "screens/common/feeds/FeedConfigDialog.h"
+#include "screens/common/feeds/FeedView.h"
+#include "screens/common/feeds/FloatingFeedWindow.h"
+#include "services/feeds/FeedMonitor.h"
+#include "ui/theme/Theme.h"
+
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QShowEvent>
+#include <QVBoxLayout>
+
+namespace fincept::feeds {
+
+FeedPanel::FeedPanel(QWidget* parent) : QWidget(parent) {
+ setObjectName("feedPanel");
+ setStyleSheet(QString("#feedPanel{background:%1;}").arg(fincept::ui::colors::BG_BASE()));
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ auto* bar = new QWidget;
+ bar->setObjectName("feedToolbar");
+ bar->setFixedHeight(30);
+ bar->setStyleSheet(QString("#feedToolbar{background:%1;border-bottom:1px solid %2;}")
+ .arg(fincept::ui::colors::BG_RAISED(), fincept::ui::colors::BORDER_DIM()));
+ auto* bl = new QHBoxLayout(bar);
+ bl->setContentsMargins(6, 0, 6, 0);
+ auto* heading = new QLabel(tr("FEEDS"));
+ heading->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;").arg(fincept::ui::colors::TEXT_TERTIARY()));
+ bl->addWidget(heading);
+ bl->addStretch();
+ auto* add = new QPushButton(tr("+ Add Feed"));
+ add->setCursor(Qt::PointingHandCursor);
+ bl->addWidget(add);
+ root->addWidget(bar);
+
+ auto* scroll = new QScrollArea;
+ scroll->setWidgetResizable(true);
+ scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ scroll->setFrameShape(QFrame::NoFrame);
+ auto* host = new QWidget;
+ stack_ = new QVBoxLayout(host);
+ stack_->setContentsMargins(0, 0, 0, 0);
+ stack_->setSpacing(4);
+ scroll->setWidget(host);
+ root->addWidget(scroll, 1);
+
+ connect(add, &QPushButton::clicked, this, [this]() { open_config({}); });
+ connect(&FeedMonitor::instance(), &FeedMonitor::subscriptions_changed, this, [this]() { rebuild(); });
+}
+
+void FeedPanel::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ if (!first_shown_) {
+ first_shown_ = true;
+ FeedMonitor::instance().ensure_loaded();
+ rebuild();
+ }
+}
+
+void FeedPanel::rebuild() {
+ const auto subs = FeedMonitor::instance().subscriptions();
+
+ // Remove all existing items (views or the empty-state placeholder).
+ while (stack_->count() > 0) {
+ QLayoutItem* item = stack_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ docked_.clear();
+
+ int idx = 0;
+ for (const auto& sub : subs) {
+ if (!sub.enabled || floating_.contains(sub.id))
+ continue;
+ auto* view = new FeedView(sub);
+ connect(view, &FeedView::pop_out_requested, this, [this](const QString& id) { pop_out(id); });
+ connect(view, &FeedView::config_requested, this, [this](const QString& id) { open_config(id); });
+ // Stretch factor 1 so feeds share and fill the full column height (a single
+ // feed fills 100%); minimum height keeps many feeds usable and overflows
+ // into the scroll area instead of collapsing.
+ stack_->insertWidget(idx++, view, 1);
+ docked_.insert(sub.id, view);
+ }
+
+ // Keep open floating windows in sync with config edits (name / display mode).
+ for (auto it = floating_.begin(); it != floating_.end(); ++it)
+ for (const auto& s : subs)
+ if (s.id == it.key()) {
+ it.value()->view()->set_subscription(s);
+ break;
+ }
+
+ // Empty state only when nothing is visible anywhere (no docked, no floating).
+ if (idx == 0 && floating_.isEmpty()) {
+ auto* empty = new QLabel(tr("No feeds configured.\nClick “+ Add Feed”."));
+ empty->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
+ empty->setContentsMargins(8, 16, 8, 8);
+ empty->setStyleSheet(QString("color:%1;font-size:11px;").arg(fincept::ui::colors::TEXT_TERTIARY()));
+ stack_->addWidget(empty);
+ stack_->addStretch();
+ }
+}
+
+void FeedPanel::open_config(const QString& feed_id) {
+ FeedSubscription initial;
+ if (!feed_id.isEmpty()) {
+ for (const auto& s : FeedMonitor::instance().subscriptions())
+ if (s.id == feed_id) {
+ initial = s;
+ break;
+ }
+ }
+ FeedConfigDialog dlg(initial, this);
+ if (dlg.exec() == QDialog::Accepted) {
+ if (dlg.delete_requested()) {
+ if (!feed_id.isEmpty()) {
+ if (floating_.contains(feed_id))
+ floating_[feed_id]->close(); // closeEvent -> closed -> remove from floating_
+ FeedMonitor::instance().remove(feed_id);
+ }
+ return;
+ }
+ const FeedSubscription s = dlg.result_subscription();
+ if (!s.url.isEmpty())
+ FeedMonitor::instance().add_or_update(s);
+ }
+}
+
+void FeedPanel::pop_out(const QString& feed_id) {
+ if (floating_.contains(feed_id)) {
+ floating_[feed_id]->raise();
+ floating_[feed_id]->activateWindow();
+ return;
+ }
+ FeedSubscription sub;
+ for (const auto& s : FeedMonitor::instance().subscriptions())
+ if (s.id == feed_id) {
+ sub = s;
+ break;
+ }
+ if (sub.id.isEmpty())
+ return;
+ auto* win = new FloatingFeedWindow(sub);
+ win->setAttribute(Qt::WA_DeleteOnClose);
+ // Wire the floating view's header buttons (the docked panel normally does this in
+ // rebuild(); a floating view has no docked counterpart, so do it here).
+ connect(win->view(), &FeedView::config_requested, this, [this](const QString& id) { open_config(id); });
+ connect(win->view(), &FeedView::pop_in_requested, this, [this](const QString& id) {
+ if (floating_.contains(id))
+ floating_[id]->close(); // closeEvent -> closed -> remove + rebuild (re-docks)
+ });
+ connect(win, &FloatingFeedWindow::closed, this, [this](const QString& id) {
+ floating_.remove(id);
+ rebuild();
+ });
+ floating_.insert(feed_id, win);
+ win->show();
+ rebuild(); // remove from docked stack while floating
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedPanel.h b/fincept-qt/src/screens/common/feeds/FeedPanel.h
new file mode 100644
index 000000000..d1b0a52f3
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedPanel.h
@@ -0,0 +1,36 @@
+#pragma once
+#include <QHash>
+#include <QWidget>
+
+class QVBoxLayout;
+class QShowEvent;
+
+namespace fincept::feeds {
+
+class FeedView;
+class FloatingFeedWindow;
+
+/// Reusable feed section: add-feed toolbar + a vertical stack of FeedViews (one per
+/// enabled subscription). Drop into any screen's layout. Calls
+/// FeedMonitor::ensure_loaded() on first show. Owns floating windows for popped-out
+/// feeds and skips them in the docked stack while floating.
+class FeedPanel : public QWidget {
+ Q_OBJECT
+ public:
+ explicit FeedPanel(QWidget* parent = nullptr);
+
+ protected:
+ void showEvent(QShowEvent* e) override;
+
+ private:
+ void rebuild();
+ void open_config(const QString& feed_id); // empty id = add new
+ void pop_out(const QString& feed_id);
+
+ QVBoxLayout* stack_ = nullptr;
+ QHash<QString, FeedView*> docked_;
+ QHash<QString, FloatingFeedWindow*> floating_;
+ bool first_shown_ = false;
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedTableView.cpp b/fincept-qt/src/screens/common/feeds/FeedTableView.cpp
new file mode 100644
index 000000000..1fc943a6c
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedTableView.cpp
@@ -0,0 +1,46 @@
+#include "screens/common/feeds/FeedTableView.h"
+
+#include "ui/tables/DataTable.h"
+
+#include <QDesktopServices>
+#include <QTableWidget>
+#include <QUrl>
+#include <QVBoxLayout>
+
+namespace fincept::feeds {
+
+FeedTableView::FeedTableView(QWidget* parent) : QWidget(parent) {
+ auto* lay = new QVBoxLayout(this);
+ lay->setContentsMargins(0, 0, 0, 0);
+ table_ = new ui::DataTable(this);
+ lay->addWidget(table_);
+ connect(table_, &QTableWidget::cellDoubleClicked, this, [this](int r, int) {
+ if (r >= 0 && r < items_.size() && !items_[r].link.isEmpty())
+ QDesktopServices::openUrl(QUrl(items_[r].link));
+ });
+}
+
+void FeedTableView::set_items(const QVector<FeedItem>& items) {
+ items_ = items;
+ QStringList extraCols;
+ for (const auto& it : items)
+ for (auto k = it.fields.begin(); k != it.fields.end(); ++k)
+ if (!extraCols.contains(k.key()))
+ extraCols.append(k.key());
+
+ QStringList headers{tr("Time"), tr("Title")};
+ headers += extraCols;
+ table_->set_headers(headers);
+
+ QVector<QStringList> rows;
+ rows.reserve(items.size());
+ for (const auto& it : items) {
+ QStringList row{it.time, it.title};
+ for (const auto& c : extraCols)
+ row << it.fields.value(c);
+ rows.append(row);
+ }
+ table_->set_data(rows);
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedTableView.h b/fincept-qt/src/screens/common/feeds/FeedTableView.h
new file mode 100644
index 000000000..f068a4904
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedTableView.h
@@ -0,0 +1,26 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+
+#include <QVector>
+#include <QWidget>
+
+namespace fincept::ui {
+class DataTable;
+}
+
+namespace fincept::feeds {
+
+/// Renders feed items as a sortable table. Columns: Time, Title, + any mapped
+/// extra fields (union across items, stable order). Double-click a row -> open link.
+class FeedTableView : public QWidget {
+ Q_OBJECT
+ public:
+ explicit FeedTableView(QWidget* parent = nullptr);
+ void set_items(const QVector<FeedItem>& items);
+
+ private:
+ ui::DataTable* table_ = nullptr;
+ QVector<FeedItem> items_;
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedView.cpp b/fincept-qt/src/screens/common/feeds/FeedView.cpp
new file mode 100644
index 000000000..563ccf414
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedView.cpp
@@ -0,0 +1,132 @@
+#include "screens/common/feeds/FeedView.h"
+
+#include "screens/common/feeds/FeedCardView.h"
+#include "screens/common/feeds/FeedTableView.h"
+#include "services/feeds/FeedMonitor.h"
+#include "ui/theme/Theme.h"
+
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QStackedWidget>
+#include <QToolButton>
+#include <QVBoxLayout>
+
+#include <utility>
+
+namespace fincept::feeds {
+
+namespace {
+
+QString dot_color(FeedStatus s) {
+ using namespace fincept::ui;
+ switch (s) {
+ case FeedStatus::Ok: return colors::GREEN();
+ case FeedStatus::Fetching: return colors::AMBER();
+ case FeedStatus::Error: return colors::RED();
+ default: return colors::TEXT_TERTIARY();
+ }
+}
+
+} // namespace
+
+FeedView::FeedView(FeedSubscription sub, QWidget* parent) : QWidget(parent), sub_(std::move(sub)) {
+ // Keep a sensible floor so several stacked feeds stay readable and overflow into
+ // the panel's scroll area instead of collapsing to the header.
+ setMinimumHeight(160);
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ auto* header = new QWidget;
+ header->setObjectName("feedHeader");
+ header->setStyleSheet(QString("#feedHeader{background:%1;border-bottom:1px solid %2;}")
+ .arg(fincept::ui::colors::BG_RAISED(), fincept::ui::colors::BORDER_DIM()));
+ auto* h = new QHBoxLayout(header);
+ h->setContentsMargins(6, 3, 4, 3);
+ h->setSpacing(4);
+
+ status_dot_ = new QLabel("●");
+ status_dot_->setStyleSheet(QString("color:%1;").arg(dot_color(FeedStatus::Idle)));
+ h->addWidget(status_dot_);
+
+ title_ = new QLabel(sub_.name);
+ title_->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;").arg(fincept::ui::colors::TEXT_PRIMARY()));
+ h->addWidget(title_, 1);
+
+ auto mkBtn = [&](const QString& glyph, const QString& tip) {
+ auto* b = new QToolButton;
+ b->setText(glyph);
+ b->setToolTip(tip);
+ b->setCursor(Qt::PointingHandCursor);
+ b->setAutoRaise(true);
+ h->addWidget(b);
+ return b;
+ };
+ connect(mkBtn(QStringLiteral("⟳"), tr("Refresh now")), &QToolButton::clicked, this,
+ [this]() { FeedMonitor::instance().refresh_now(sub_.id); });
+ popout_btn_ = mkBtn(QStringLiteral("⧉"), tr("Pop out"));
+ connect(popout_btn_, &QToolButton::clicked, this, [this]() {
+ if (floating_mode_)
+ emit pop_in_requested(sub_.id);
+ else
+ emit pop_out_requested(sub_.id);
+ });
+ connect(mkBtn(QStringLiteral("⚙"), tr("Configure")), &QToolButton::clicked, this,
+ [this]() { emit config_requested(sub_.id); });
+
+ root->addWidget(header);
+
+ body_ = new QStackedWidget;
+ cards_ = new FeedCardView;
+ table_ = new FeedTableView;
+ body_->addWidget(cards_);
+ body_->addWidget(table_);
+ root->addWidget(body_, 1);
+ rebuild_body();
+
+ auto& mon = FeedMonitor::instance();
+ connect(&mon, &FeedMonitor::feed_updated, this, &FeedView::on_updated);
+ connect(&mon, &FeedMonitor::feed_status, this, &FeedView::on_status);
+ on_updated(sub_.id, mon.cached_items(sub_.id)); // seed
+ on_status(sub_.id, mon.status(sub_.id), {});
+}
+
+void FeedView::rebuild_body() {
+ body_->setCurrentWidget(sub_.display_mode == DisplayMode::Table ? static_cast<QWidget*>(table_)
+ : static_cast<QWidget*>(cards_));
+}
+
+void FeedView::set_subscription(const FeedSubscription& sub) {
+ sub_ = sub;
+ title_->setText(sub_.name);
+ rebuild_body();
+ on_updated(sub_.id, FeedMonitor::instance().cached_items(sub_.id));
+}
+
+void FeedView::set_floating(bool floating) {
+ floating_mode_ = floating;
+ if (!popout_btn_)
+ return;
+ popout_btn_->setText(floating ? QStringLiteral("⤓") : QStringLiteral("⧉"));
+ popout_btn_->setToolTip(floating ? tr("Dock back into panel") : tr("Pop out"));
+}
+
+void FeedView::on_updated(const QString& id, const QVector<FeedItem>& items) {
+ if (id != sub_.id)
+ return;
+ if (sub_.display_mode == DisplayMode::Table)
+ table_->set_items(items);
+ else
+ cards_->set_items(items);
+}
+
+void FeedView::on_status(const QString& id, FeedStatus st, const QString& msg) {
+ if (id != sub_.id)
+ return;
+ status_dot_->setStyleSheet(QString("color:%1;").arg(dot_color(st)));
+ if (!msg.isEmpty())
+ status_dot_->setToolTip(msg);
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FeedView.h b/fincept-qt/src/screens/common/feeds/FeedView.h
new file mode 100644
index 000000000..0cbb2ac9a
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FeedView.h
@@ -0,0 +1,48 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+
+#include <QVector>
+#include <QWidget>
+
+class QLabel;
+class QStackedWidget;
+class QToolButton;
+
+namespace fincept::feeds {
+
+class FeedCardView;
+class FeedTableView;
+
+/// One feed: header (name, status dot, ⟳ refresh, ⧉ pop-out/⤓ dock-back, ⚙ config) +
+/// body (cards or table per sub.display_mode). Subscribes to FeedMonitor filtered by id.
+class FeedView : public QWidget {
+ Q_OBJECT
+ public:
+ explicit FeedView(FeedSubscription sub, QWidget* parent = nullptr);
+ QString feed_id() const { return sub_.id; }
+ void set_subscription(const FeedSubscription& sub); // re-render on display-mode/name change
+ // Floating mode flips the ⧉ pop-out button into a ⤓ "dock back" button
+ // (emits pop_in_requested instead of pop_out_requested).
+ void set_floating(bool floating);
+
+ signals:
+ void pop_out_requested(const QString& feed_id);
+ void pop_in_requested(const QString& feed_id);
+ void config_requested(const QString& feed_id);
+
+ private:
+ void on_updated(const QString& id, const QVector<FeedItem>& items);
+ void on_status(const QString& id, FeedStatus st, const QString& msg);
+ void rebuild_body();
+
+ FeedSubscription sub_;
+ QLabel* title_ = nullptr;
+ QLabel* status_dot_ = nullptr;
+ QToolButton* popout_btn_ = nullptr;
+ QStackedWidget* body_ = nullptr;
+ FeedCardView* cards_ = nullptr;
+ FeedTableView* table_ = nullptr;
+ bool floating_mode_ = false;
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FloatingFeedWindow.cpp b/fincept-qt/src/screens/common/feeds/FloatingFeedWindow.cpp
new file mode 100644
index 000000000..d11fac85b
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FloatingFeedWindow.cpp
@@ -0,0 +1,29 @@
+#include "screens/common/feeds/FloatingFeedWindow.h"
+
+#include "screens/common/feeds/FeedView.h"
+#include "ui/theme/Theme.h"
+
+#include <QCloseEvent>
+#include <QVBoxLayout>
+
+namespace fincept::feeds {
+
+FloatingFeedWindow::FloatingFeedWindow(const FeedSubscription& sub, QWidget* parent)
+ : QWidget(parent, Qt::Window), feed_id_(sub.id) {
+ setWindowTitle(QString("Feed — %1").arg(sub.name));
+ setObjectName("floatingFeedWindow");
+ setStyleSheet(QString("#floatingFeedWindow{background:%1;}").arg(fincept::ui::colors::BG_BASE()));
+ resize(380, 520);
+ auto* lay = new QVBoxLayout(this);
+ lay->setContentsMargins(0, 0, 0, 0);
+ view_ = new FeedView(sub, this);
+ view_->set_floating(true); // ⧉ becomes a ⤓ "dock back" button
+ lay->addWidget(view_);
+}
+
+void FloatingFeedWindow::closeEvent(QCloseEvent* e) {
+ emit closed(feed_id_);
+ QWidget::closeEvent(e);
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/common/feeds/FloatingFeedWindow.h b/fincept-qt/src/screens/common/feeds/FloatingFeedWindow.h
new file mode 100644
index 000000000..64993d6fa
--- /dev/null
+++ b/fincept-qt/src/screens/common/feeds/FloatingFeedWindow.h
@@ -0,0 +1,32 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+
+#include <QWidget>
+
+class QCloseEvent;
+
+namespace fincept::feeds {
+
+class FeedView;
+
+/// Top-level window hosting one FeedView (per-feed pop-out). Emits closed() so the
+/// host panel can re-dock the feed. Self-managed; not tied to the ADS dock system.
+class FloatingFeedWindow : public QWidget {
+ Q_OBJECT
+ public:
+ explicit FloatingFeedWindow(const FeedSubscription& sub, QWidget* parent = nullptr);
+ QString feed_id() const { return feed_id_; }
+ FeedView* view() const { return view_; }
+
+ signals:
+ void closed(const QString& feed_id);
+
+ protected:
+ void closeEvent(QCloseEvent* e) override;
+
+ private:
+ QString feed_id_;
+ FeedView* view_ = nullptr;
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
index a72d8e99a..2da11041a 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
@@ -992,16 +992,23 @@ void AccountManagementDialog::on_connect_zerodha_browser() {
// BUG 1 FIX: persist key+secret now.
persist_zerodha_creds_before_auth();
- // Tear down any prior server
+ // Tear down any prior server. stop() closes the listening socket
+ // synchronously so the fixed redirect port is freed *now*; deleteLater()
+ // alone defers the close to the next event-loop pass, so the start() below
+ // would still see the old socket bound, fall back to an ephemeral port, and
+ // the broker's redirect to the registered :5010 would hit nothing.
if (z_redirect_server_) {
+ z_redirect_server_->stop();
z_redirect_server_->deleteLater();
z_redirect_server_ = nullptr;
}
z_redirect_server_ = new trading::auth::RedirectServer(this);
// Must match the redirect URL shown in the setup steps above (127.0.0.1:5010).
+ // Reject the ephemeral fallback: Kite redirects to the fixed registered URL,
+ // so a random port can never receive the callback — route to manual instead.
constexpr quint16 kZerodhaPort = 5010;
- if (!z_redirect_server_->start(kZerodhaPort, 120)) {
+ if (!z_redirect_server_->start(kZerodhaPort, 120) || z_redirect_server_->port() != kZerodhaPort) {
z_status_->setText(tr("Port 5010 busy - use manual paste fallback"));
z_status_->setStyleSheet(QString("color:%1;").arg(colors::NEGATIVE()));
z_redirect_server_->deleteLater();
@@ -1258,8 +1265,14 @@ void AccountManagementDialog::on_connect_fyers_browser() {
creds.api_secret = api_secret;
AccountManager::instance().save_credentials(selected_account_id_, creds);
- // Tear down any prior server
+ // Tear down any prior server. stop() closes the listening socket
+ // synchronously so port 5011 is freed *now*; deleteLater() alone defers the
+ // close to the next event-loop pass, so the start() below would still see
+ // the old socket bound, fall back to an ephemeral port, and Fyers' redirect
+ // to the registered http://127.0.0.1:5011/ would hit nothing (the browser
+ // then shows "could not connect", which looks like a network error).
if (f_redirect_server_) {
+ f_redirect_server_->stop();
f_redirect_server_->deleteLater();
f_redirect_server_ = nullptr;
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index 815dc6746..69fdec707 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -4,14 +4,20 @@
#include "ui/theme/Theme.h"
#include <QDate>
+#include <QDateEdit>
#include <QDateTime>
#include <QDialog>
+#include <QFrame>
+#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLineEdit>
+#include <QLocale>
+#include <QMenu>
#include <QMessageBox>
#include <QPointer>
#include <QPushButton>
+#include <QScrollArea>
#include <QScrollBar>
#include <QSplitter>
#include <QStackedWidget>
@@ -21,6 +27,58 @@
namespace fincept::screens::equity {
+namespace {
+
+// Funds card slots (order must match setup_funds_tab + retranslateUi + set_funds_view).
+enum FundCard {
+ FC_Available = 0,
+ FC_UsedMargin,
+ FC_TotalEquity,
+ FC_RealizedPnl,
+ FC_UnrealizedPnl,
+ FC_HoldingsValue,
+ FC_OpeningBalance,
+ FC_MarginUtil,
+ FC_Collateral,
+};
+
+// Stats card slots (order must match setup_stats_tab + retranslateUi + set_stats_view).
+enum StatCard {
+ SC_NetPnl = 0,
+ SC_TodayPnl,
+ SC_ReturnPct,
+ SC_WinRate,
+ SC_ProfitFactor,
+ SC_TotalTrades,
+ SC_AvgWin,
+ SC_AvgLoss,
+ SC_Turnover,
+ SC_LargestWin,
+ SC_LargestLoss,
+ SC_TotalFees,
+};
+
+// Money with the connected broker's currency symbol and locale-aware grouping
+// (Indian lakh grouping for ₹). `signed_pfx` prepends an explicit +/- for P&L.
+QString fmt_money(double v, const QString& sym, bool signed_pfx = false) {
+ const QLocale loc = (sym == QString::fromUtf8("₹")) ? QLocale(QLocale::English, QLocale::India)
+ : QLocale(QLocale::English, QLocale::UnitedStates);
+ const QString mag = loc.toString(qAbs(v), 'f', 2);
+ const QString prefix = v < 0 ? QStringLiteral("-") : (signed_pfx ? QStringLiteral("+") : QString());
+ return prefix + sym + mag;
+}
+
+QColor order_status_color(const QString& status) {
+ const QString s = status.toLower();
+ if (s == "filled" || s == "complete" || s == "completed")
+ return {fincept::ui::colors::POSITIVE()};
+ if (s == "rejected" || s == "cancelled" || s == "canceled")
+ return {fincept::ui::colors::NEGATIVE()};
+ return {fincept::ui::colors::AMBER()}; // pending / partial / open / accepted
+}
+
+} // namespace
+
EquityBottomPanel::EquityBottomPanel(QWidget* parent) : QWidget(parent) {
setObjectName("eqBottomPanel");
@@ -119,16 +177,15 @@ void EquityBottomPanel::retranslateUi() {
// Table headers
if (positions_table_)
- positions_table_->setHorizontalHeaderLabels(
- {tr("Symbol"), tr("Opened"), tr("Side"), tr("Qty"), tr("Avg Price"), tr("LTP"), tr("P&L"), tr("P&L %")});
+ positions_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Product"), tr("Opened"), tr("Side"), tr("Qty"),
+ tr("Avg Price"), tr("LTP"), tr("P&L"), tr("P&L %"), tr("Action")});
if (holdings_table_)
holdings_table_->setHorizontalHeaderLabels(
{tr("Symbol"), tr("Qty"), tr("Avg Price"), tr("LTP"), tr("Invested"), tr("Current"), tr("P&L"),
tr("P&L %")});
if (orders_table_)
- orders_table_->setHorizontalHeaderLabels(
- {tr("Order ID"), tr("Symbol"), tr("Side"), tr("Type"), tr("Qty"), tr("Price"), tr("Status"), tr("Time"),
- tr("Action")});
+ orders_table_->setHorizontalHeaderLabels({tr("Order ID"), tr("Symbol"), tr("Product"), tr("Side"), tr("Type"),
+ tr("Qty"), tr("Price"), tr("Status"), tr("Time"), tr("Action")});
if (auctions_table_)
auctions_table_->setHorizontalHeaderLabels(
{tr("Date"), tr("Type"), tr("Time"), tr("Price"), tr("Size"), tr("Exchange")});
@@ -151,17 +208,20 @@ void EquityBottomPanel::retranslateUi() {
if (holdings_pnl_caption_) holdings_pnl_caption_->setText(tr("TOTAL P&L"));
if (holdings_pnl_pct_caption_) holdings_pnl_pct_caption_->setText(tr("RETURN %"));
- // Funds row captions
- if (available_caption_) available_caption_->setText(tr("Available Balance"));
- if (used_margin_caption_) used_margin_caption_->setText(tr("Used Margin"));
- if (total_caption_) total_caption_->setText(tr("Total Balance"));
- if (collateral_caption_) collateral_caption_->setText(tr("Collateral"));
-
- // Stats row captions
- const QString stat_labels[] = {tr("Total P&L"), tr("Win Rate"), tr("Total Trades"), tr("Largest Win"),
- tr("Largest Loss")};
- for (int i = 0; i < 5; ++i)
- if (stat_captions_[i]) stat_captions_[i]->setText(stat_labels[i]);
+ // Funds card captions
+ const QString fund_caps[kFundCards] = {tr("AVAILABLE BALANCE"), tr("USED MARGIN"), tr("TOTAL EQUITY"),
+ tr("REALIZED P&L"), tr("UNREALIZED P&L"), tr("HOLDINGS VALUE"),
+ tr("OPENING BALANCE"), tr("MARGIN USED %"), tr("COLLATERAL")};
+ for (int i = 0; i < kFundCards; ++i)
+ if (fund_card_cap_[i]) fund_card_cap_[i]->setText(fund_caps[i]);
+
+ // Stats card captions
+ const QString stat_caps[kStatCards] = {tr("NET P&L"), tr("TODAY'S P&L"), tr("RETURN %"),
+ tr("WIN RATE"), tr("PROFIT FACTOR"), tr("TOTAL TRADES"),
+ tr("AVG WIN"), tr("AVG LOSS"), tr("TURNOVER"),
+ tr("LARGEST WIN"), tr("LARGEST LOSS"), tr("TOTAL CHARGES")};
+ for (int i = 0; i < kStatCards; ++i)
+ if (stat_card_cap_[i]) stat_card_cap_[i]->setText(stat_caps[i]);
// The calendar clock banner ("● MARKET OPEN/CLOSED/--") is live data driven
// by set_clock(); it re-renders in the new language on the next clock tick,
@@ -193,7 +253,63 @@ void EquityBottomPanel::setup_positions_tab() {
.arg(fincept::ui::colors::PANEL(), fincept::ui::colors::BORDER()));
auto* bar_layout = new QHBoxLayout(action_bar);
bar_layout->setContentsMargins(12, 4, 12, 4);
- bar_layout->setSpacing(8);
+ bar_layout->setSpacing(10);
+
+ // Net total P&L across the open (intraday) positions.
+ positions_total_pnl_label_ = new QLabel(tr("Total P&L --"));
+ positions_total_pnl_label_->setStyleSheet(
+ QString("font-size:11px;font-weight:700;color:%1;").arg(fincept::ui::colors::TEXT_PRIMARY()));
+ bar_layout->addWidget(positions_total_pnl_label_);
+
+ // Small square-off button for a P&L group (winners / losers).
+ auto make_group_btn = [](const QString& color, const QString& tip) {
+ auto* b = new QPushButton(QString::fromUtf8("✕"));
+ b->setCursor(Qt::PointingHandCursor);
+ b->setEnabled(false);
+ b->setFixedHeight(18);
+ b->setToolTip(tip);
+ b->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %1;"
+ "padding:0 6px;font-size:10px;font-weight:700;border-radius:2px;}"
+ "QPushButton:hover:enabled{background:%1;color:#000;}"
+ "QPushButton:disabled{color:%2;border-color:%2;}")
+ .arg(color, fincept::ui::colors::TEXT_SECONDARY()));
+ return b;
+ };
+
+ // Winners group: count + sum, with a square-off-profits button.
+ positions_win_label_ = new QLabel(QString::fromUtf8("▲ 0"));
+ positions_win_label_->setStyleSheet(
+ QString("font-size:11px;font-weight:600;color:%1;").arg(fincept::ui::colors::POSITIVE()));
+ bar_layout->addWidget(positions_win_label_);
+ win_squareoff_btn_ = make_group_btn(fincept::ui::colors::POSITIVE(), tr("Square off all winning positions"));
+ connect(win_squareoff_btn_, &QPushButton::clicked, this, [this]() {
+ if (account_id_.isEmpty())
+ return;
+ auto answer = QMessageBox::warning(this, tr("Square Off Winning Positions"),
+ tr("This will close ALL positions currently in profit.\n\nAre you sure?"),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer == QMessageBox::Yes)
+ emit square_off_group_requested(account_id_, 1);
+ });
+ bar_layout->addWidget(win_squareoff_btn_);
+
+ // Losers group: count + sum, with a cut-losses button.
+ positions_loss_label_ = new QLabel(QString::fromUtf8("▼ 0"));
+ positions_loss_label_->setStyleSheet(
+ QString("font-size:11px;font-weight:600;color:%1;").arg(fincept::ui::colors::NEGATIVE()));
+ bar_layout->addWidget(positions_loss_label_);
+ loss_squareoff_btn_ = make_group_btn(fincept::ui::colors::NEGATIVE(), tr("Square off all losing positions"));
+ connect(loss_squareoff_btn_, &QPushButton::clicked, this, [this]() {
+ if (account_id_.isEmpty())
+ return;
+ auto answer = QMessageBox::warning(this, tr("Square Off Losing Positions"),
+ tr("This will close ALL positions currently in loss.\n\nAre you sure?"),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer == QMessageBox::Yes)
+ emit square_off_group_requested(account_id_, -1);
+ });
+ bar_layout->addWidget(loss_squareoff_btn_);
+
bar_layout->addStretch(1);
close_all_btn_ = new QPushButton(tr("SQUARE OFF ALL"));
@@ -218,15 +334,39 @@ void EquityBottomPanel::setup_positions_tab() {
positions_table_ = new QTableWidget;
positions_table_->setObjectName("eqTable");
- positions_table_->setColumnCount(8);
- positions_table_->setHorizontalHeaderLabels(
- {tr("Symbol"), tr("Opened"), tr("Side"), tr("Qty"), tr("Avg Price"), tr("LTP"), tr("P&L"), tr("P&L %")});
+ positions_table_->setColumnCount(10);
+ positions_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Product"), tr("Opened"), tr("Side"), tr("Qty"),
+ tr("Avg Price"), tr("LTP"), tr("P&L"), tr("P&L %"), tr("Action")});
positions_table_->verticalHeader()->setVisible(false);
positions_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
positions_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
positions_table_->setShowGrid(false);
positions_table_->horizontalHeader()->setStretchLastSection(true);
positions_table_->verticalHeader()->setDefaultSectionSize(22);
+
+ // Right-click a row → Buy (add) / Sell (reduce) for that symbol. Symbol +
+ // product are read from the row items so it stays correct regardless of order.
+ positions_table_->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(positions_table_, &QTableWidget::customContextMenuRequested, this, [this](const QPoint& p) {
+ const int row = positions_table_->rowAt(p.y());
+ if (row < 0)
+ return;
+ auto* sym_item = positions_table_->item(row, 0);
+ if (!sym_item || sym_item->text().isEmpty())
+ return;
+ const QString symbol = sym_item->text();
+ auto* prod_item = positions_table_->item(row, 1);
+ const QString product = prod_item && !prod_item->text().isEmpty() ? prod_item->text() : QStringLiteral("MIS");
+ QMenu menu(this);
+ QAction* buy = menu.addAction(tr("Buy / Add %1").arg(symbol));
+ QAction* sell = menu.addAction(tr("Sell / Reduce %1").arg(symbol));
+ QAction* chosen = menu.exec(positions_table_->viewport()->mapToGlobal(p));
+ if (chosen == buy)
+ emit trade_symbol_requested(symbol, product, true);
+ else if (chosen == sell)
+ emit trade_symbol_requested(symbol, product, false);
+ });
+
vlay->addWidget(positions_table_, 1);
positions_tab_idx_ = tabs_->addTab(container, tr("POSITIONS"));
@@ -311,6 +451,27 @@ void EquityBottomPanel::setup_holdings_tab() {
holdings_table_->verticalScrollBar()->setSingleStep(8);
holdings_table_->horizontalScrollBar()->setSingleStep(16);
+ // Right-click a holding → Buy (add) / Sell (reduce). Holdings are delivery, so
+ // the resulting order uses the CNC product.
+ holdings_table_->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(holdings_table_, &QTableWidget::customContextMenuRequested, this, [this](const QPoint& p) {
+ const int row = holdings_table_->rowAt(p.y());
+ if (row < 0)
+ return;
+ auto* sym_item = holdings_table_->item(row, 0);
+ if (!sym_item || sym_item->text().isEmpty())
+ return;
+ const QString symbol = sym_item->text();
+ QMenu menu(this);
+ QAction* buy = menu.addAction(tr("Buy / Add %1").arg(symbol));
+ QAction* sell = menu.addAction(tr("Sell / Reduce %1").arg(symbol));
+ QAction* chosen = menu.exec(holdings_table_->viewport()->mapToGlobal(p));
+ if (chosen == buy)
+ emit trade_symbol_requested(symbol, QStringLiteral("CNC"), true);
+ else if (chosen == sell)
+ emit trade_symbol_requested(symbol, QStringLiteral("CNC"), false);
+ });
+
v->addWidget(holdings_table_, 1);
holdings_tab_idx_ = tabs_->addTab(tab, tr("HOLDINGS"));
}
@@ -331,6 +492,26 @@ void EquityBottomPanel::setup_orders_tab() {
auto* bar_layout = new QHBoxLayout(action_bar);
bar_layout->setContentsMargins(12, 4, 12, 4);
bar_layout->setSpacing(8);
+
+ // Per-day order book: pick a date to view that IST day's orders (default today,
+ // so each session starts empty instead of accumulating every past order).
+ auto* date_lbl = new QLabel(tr("DATE"));
+ date_lbl->setStyleSheet(
+ QString("color:%1;font-size:10px;font-weight:600;letter-spacing:0.5px;").arg(fincept::ui::colors::TEXT_SECONDARY()));
+ orders_date_edit_ = new QDateEdit(QDate::currentDate());
+ orders_date_edit_->setObjectName("eqOrdersDate");
+ orders_date_edit_->setCalendarPopup(true);
+ orders_date_edit_->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
+ orders_date_edit_->setMaximumDate(QDate::currentDate());
+ orders_date_edit_->setStyleSheet(
+ QString("QDateEdit{background:%1;color:%2;border:1px solid %3;padding:2px 6px;font-size:11px;border-radius:2px;}")
+ .arg(fincept::ui::colors::BG_BASE(), fincept::ui::colors::TEXT_PRIMARY(), fincept::ui::colors::BORDER()));
+ connect(orders_date_edit_, &QDateEdit::dateChanged, this, [this](const QDate& d) {
+ if (!suppress_orders_date_signal_)
+ emit orders_day_changed(d);
+ });
+ bar_layout->addWidget(date_lbl);
+ bar_layout->addWidget(orders_date_edit_);
bar_layout->addStretch(1);
cancel_all_btn_ = new QPushButton(tr("CANCEL ALL ORDERS"));
@@ -355,10 +536,9 @@ void EquityBottomPanel::setup_orders_tab() {
orders_table_ = new QTableWidget;
orders_table_->setObjectName("eqTable");
- orders_table_->setColumnCount(9);
- orders_table_->setHorizontalHeaderLabels(
- {tr("Order ID"), tr("Symbol"), tr("Side"), tr("Type"), tr("Qty"), tr("Price"), tr("Status"), tr("Time"),
- tr("Action")});
+ orders_table_->setColumnCount(10);
+ orders_table_->setHorizontalHeaderLabels({tr("Order ID"), tr("Symbol"), tr("Product"), tr("Side"), tr("Type"),
+ tr("Qty"), tr("Price"), tr("Status"), tr("Time"), tr("Action")});
orders_table_->verticalHeader()->setVisible(false);
orders_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
orders_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
@@ -372,62 +552,87 @@ void EquityBottomPanel::setup_orders_tab() {
// ── Funds Tab ──────────────────────────────────────────────────────────────
-void EquityBottomPanel::setup_funds_tab() {
- auto* widget = new QWidget(this);
- auto* layout = new QVBoxLayout(widget);
- layout->setContentsMargins(12, 12, 12, 12);
- layout->setSpacing(8);
-
- auto make_row = [&](const QString& label, QLabel*& caption_out) -> QLabel* {
- auto* row = new QHBoxLayout;
- auto* lbl = new QLabel(label);
- lbl->setObjectName("eqOeLabel");
- caption_out = lbl;
- auto* val = new QLabel("--");
- val->setObjectName("eqOeBalance");
- val->setAlignment(Qt::AlignRight);
- row->addWidget(lbl);
- row->addStretch();
- row->addWidget(val);
- layout->addLayout(row);
- return val;
- };
-
- available_label_ = make_row(tr("Available Balance"), available_caption_);
- used_margin_label_ = make_row(tr("Used Margin"), used_margin_caption_);
- total_label_ = make_row(tr("Total Balance"), total_caption_);
- collateral_label_ = make_row(tr("Collateral"), collateral_caption_);
+// Build one metric card (caption + value) into a grid; stash the value/caption
+// labels so the data setters and retranslateUi can reach them by slot index.
+static QFrame* make_metric_card(const QString& caption, QLabel*& cap_out, QLabel*& val_out) {
+ auto* card = new QFrame;
+ card->setObjectName("eqMetricCard");
+ card->setStyleSheet(QString("#eqMetricCard{background:%1;border:1px solid %2;border-radius:4px;}")
+ .arg(fincept::ui::colors::PANEL(), fincept::ui::colors::BORDER()));
+ auto* cv = new QVBoxLayout(card);
+ cv->setContentsMargins(12, 8, 12, 8);
+ cv->setSpacing(3);
+ auto* cap = new QLabel(caption);
+ cap->setStyleSheet(
+ QString("color:%1;font-size:10px;letter-spacing:0.5px;font-weight:600;").arg(fincept::ui::colors::TEXT_SECONDARY()));
+ auto* val = new QLabel(QStringLiteral("--"));
+ val->setStyleSheet(QString("color:%1;font-size:15px;font-weight:700;").arg(fincept::ui::colors::TEXT_PRIMARY()));
+ cv->addWidget(cap);
+ cv->addWidget(val);
+ cap_out = cap;
+ val_out = val;
+ return card;
+}
- layout->addStretch();
- funds_tab_idx_ = tabs_->addTab(widget, tr("FUNDS"));
+void EquityBottomPanel::setup_funds_tab() {
+ auto* scroll = new QScrollArea;
+ scroll->setObjectName("eqFundsScroll");
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+
+ auto* widget = new QWidget;
+ auto* outer = new QVBoxLayout(widget);
+ outer->setContentsMargins(12, 12, 12, 12);
+ outer->setSpacing(10);
+
+ auto* grid = new QGridLayout;
+ grid->setHorizontalSpacing(10);
+ grid->setVerticalSpacing(10);
+
+ const QString caps[kFundCards] = {tr("AVAILABLE BALANCE"), tr("USED MARGIN"), tr("TOTAL EQUITY"),
+ tr("REALIZED P&L"), tr("UNREALIZED P&L"), tr("HOLDINGS VALUE"),
+ tr("OPENING BALANCE"), tr("MARGIN USED %"), tr("COLLATERAL")};
+ for (int i = 0; i < kFundCards; ++i)
+ grid->addWidget(make_metric_card(caps[i], fund_card_cap_[i], fund_card_val_[i]), i / 3, i % 3);
+ for (int c = 0; c < 3; ++c)
+ grid->setColumnStretch(c, 1);
+
+ outer->addLayout(grid);
+ outer->addStretch(1);
+ scroll->setWidget(widget);
+ funds_tab_idx_ = tabs_->addTab(scroll, tr("FUNDS"));
}
// ── Stats Tab ──────────────────────────────────────────────────────────────
void EquityBottomPanel::setup_stats_tab() {
- auto* widget = new QWidget(this);
- auto* layout = new QVBoxLayout(widget);
- layout->setContentsMargins(12, 12, 12, 12);
- layout->setSpacing(8);
-
- const QString stat_labels[] = {tr("Total P&L"), tr("Win Rate"), tr("Total Trades"), tr("Largest Win"),
- tr("Largest Loss")};
- for (int i = 0; i < 5; ++i) {
- auto* row = new QHBoxLayout;
- auto* lbl = new QLabel(stat_labels[i]);
- lbl->setObjectName("eqOeLabel");
- stat_captions_[i] = lbl;
- stat_values_[i] = new QLabel("--");
- stat_values_[i]->setObjectName("eqOeBalance");
- stat_values_[i]->setAlignment(Qt::AlignRight);
- row->addWidget(lbl);
- row->addStretch();
- row->addWidget(stat_values_[i]);
- layout->addLayout(row);
- }
-
- layout->addStretch();
- stats_tab_idx_ = tabs_->addTab(widget, tr("STATS"));
+ auto* scroll = new QScrollArea;
+ scroll->setObjectName("eqStatsScroll");
+ scroll->setWidgetResizable(true);
+ scroll->setFrameShape(QFrame::NoFrame);
+
+ auto* widget = new QWidget;
+ auto* outer = new QVBoxLayout(widget);
+ outer->setContentsMargins(12, 12, 12, 12);
+ outer->setSpacing(10);
+
+ auto* grid = new QGridLayout;
+ grid->setHorizontalSpacing(10);
+ grid->setVerticalSpacing(10);
+
+ const QString caps[kStatCards] = {tr("NET P&L"), tr("TODAY'S P&L"), tr("RETURN %"),
+ tr("WIN RATE"), tr("PROFIT FACTOR"), tr("TOTAL TRADES"),
+ tr("AVG WIN"), tr("AVG LOSS"), tr("TURNOVER"),
+ tr("LARGEST WIN"), tr("LARGEST LOSS"), tr("TOTAL CHARGES")};
+ for (int i = 0; i < kStatCards; ++i)
+ grid->addWidget(make_metric_card(caps[i], stat_card_cap_[i], stat_card_val_[i]), i / 3, i % 3);
+ for (int c = 0; c < 3; ++c)
+ grid->setColumnStretch(c, 1);
+
+ outer->addLayout(grid);
+ outer->addStretch(1);
+ scroll->setWidget(widget);
+ stats_tab_idx_ = tabs_->addTab(scroll, tr("STATS"));
}
// ── Data Setters ───────────────────────────────────────────────────────────
@@ -440,44 +645,117 @@ void EquityBottomPanel::set_account_id(const QString& account_id) {
account_id_ = account_id;
}
+void EquityBottomPanel::set_currency(const QString& sym) {
+ if (!sym.isEmpty())
+ currency_sym_ = sym;
+}
+
+void EquityBottomPanel::set_us_market_tabs_visible(bool visible) {
+ if (time_sales_tab_idx_ >= 0)
+ tabs_->setTabVisible(time_sales_tab_idx_, visible);
+ if (auctions_tab_idx_ >= 0)
+ tabs_->setTabVisible(auctions_tab_idx_, visible);
+ if (calendar_tab_idx_ >= 0)
+ tabs_->setTabVisible(calendar_tab_idx_, visible);
+}
+
+void EquityBottomPanel::update_positions_summary() {
+ double total = 0.0, win_sum = 0.0, loss_sum = 0.0;
+ int win_n = 0, loss_n = 0;
+ auto accum = [&](double pnl) {
+ total += pnl;
+ if (pnl > 0.0) {
+ win_sum += pnl;
+ ++win_n;
+ } else if (pnl < 0.0) {
+ loss_sum += pnl;
+ ++loss_n;
+ }
+ };
+ if (is_paper_)
+ for (const auto& p : last_paper_positions_)
+ accum(p.unrealized_pnl);
+ else
+ for (const auto& p : last_positions_)
+ accum(p.pnl);
+
+ const QString pos = fincept::ui::colors::POSITIVE();
+ const QString neg = fincept::ui::colors::NEGATIVE();
+ const QString pri = fincept::ui::colors::TEXT_PRIMARY();
+ if (positions_total_pnl_label_) {
+ positions_total_pnl_label_->setText(tr("Total P&L %1").arg(fmt_money(total, currency_sym_, true)));
+ positions_total_pnl_label_->setStyleSheet(
+ QString("font-size:11px;font-weight:700;color:%1;").arg(total > 0 ? pos : (total < 0 ? neg : pri)));
+ }
+ if (positions_win_label_)
+ positions_win_label_->setText(
+ QString::fromUtf8("▲ %1 %2").arg(win_n).arg(fmt_money(win_sum, currency_sym_, true)));
+ if (positions_loss_label_)
+ positions_loss_label_->setText(
+ QString::fromUtf8("▼ %1 %2").arg(loss_n).arg(fmt_money(loss_sum, currency_sym_, true)));
+ if (win_squareoff_btn_)
+ win_squareoff_btn_->setEnabled(win_n > 0);
+ if (loss_squareoff_btn_)
+ loss_squareoff_btn_->setEnabled(loss_n > 0);
+}
+
void EquityBottomPanel::set_paper_positions(const QVector<trading::PtPosition>& positions) {
last_paper_positions_ = positions; // keep row-aligned for live-quote patching
+ const QColor pos_color(fincept::ui::colors::POSITIVE());
+ const QColor neg_color(fincept::ui::colors::NEGATIVE());
positions_table_->setRowCount(positions.size());
for (int i = 0; i < positions.size(); ++i) {
const auto& p = positions[i];
ensure_item(positions_table_, i, 0)->setText(p.symbol);
+ ensure_item(positions_table_, i, 1)->setText(p.product.isEmpty() ? QStringLiteral("MIS") : p.product.toUpper());
- // Col 1 — "Opened": parse ISO timestamp, convert to local time, fall back to raw string
+ // Col 2 — "Opened": parse ISO timestamp, convert to local time, fall back to raw string
{
const QDateTime dt = QDateTime::fromString(p.opened_at, Qt::ISODate).toLocalTime();
- ensure_item(positions_table_, i, 1)
+ ensure_item(positions_table_, i, 2)
->setText(dt.isValid() ? dt.toString("yyyy-MM-dd HH:mm") : p.opened_at);
}
- ensure_item(positions_table_, i, 2)->setText(p.side);
- ensure_item(positions_table_, i, 3)->setText(QString::number(p.quantity, 'f', 0));
- ensure_item(positions_table_, i, 4)->setText(QString::number(p.entry_price, 'f', 2));
- ensure_item(positions_table_, i, 5)->setText(QString::number(p.current_price, 'f', 2));
+ ensure_item(positions_table_, i, 3)->setText(p.side.toUpper());
+ ensure_item(positions_table_, i, 4)->setText(QString::number(p.quantity, 'f', 0));
+ ensure_item(positions_table_, i, 5)->setText(QString::number(p.entry_price, 'f', 2));
+ ensure_item(positions_table_, i, 6)->setText(QString::number(p.current_price, 'f', 2));
- // Col 6 — P&L
- auto* pnl_item = ensure_item(positions_table_, i, 6);
+ // Col 7 — P&L
+ auto* pnl_item = ensure_item(positions_table_, i, 7);
pnl_item->setText(QString::number(p.unrealized_pnl, 'f', 2));
- pnl_item->setForeground(p.unrealized_pnl >= 0 ? QColor(fincept::ui::colors::POSITIVE())
- : QColor(fincept::ui::colors::NEGATIVE()));
+ pnl_item->setForeground(p.unrealized_pnl >= 0 ? pos_color : neg_color);
- // Col 7 — P&L %
- // Use notional as the divisor so both entry_price == 0 and quantity == 0
- // are safely handled by a single guard (avoids divide-by-zero).
+ // Col 8 — P&L %. Use notional as the divisor so both entry_price == 0 and
+ // quantity == 0 are handled by a single guard (avoids divide-by-zero).
const double notional = p.entry_price * p.quantity;
- const double pct = notional != 0.0
- ? (p.unrealized_pnl / notional) * 100.0
- : 0.0;
- auto* pct_item = ensure_item(positions_table_, i, 7);
+ const double pct = notional != 0.0 ? (p.unrealized_pnl / notional) * 100.0 : 0.0;
+ auto* pct_item = ensure_item(positions_table_, i, 8);
pct_item->setText(QString::number(pct, 'f', 2) + "%");
- pct_item->setForeground(
- pct >= 0 ? QColor(fincept::ui::colors::POSITIVE())
- : QColor(fincept::ui::colors::NEGATIVE()));
+ pct_item->setForeground(pct >= 0 ? pos_color : neg_color);
+
+ // Col 9 — CONVERT to CNC (carry overnight). Only intraday (MIS) positions
+ // can be converted to delivery; NRML/CNC show nothing.
+ if (trading::product_is_intraday(p.product)) {
+ auto* btn = new QPushButton(tr("→ CNC"));
+ btn->setObjectName("eqTableBtn");
+ btn->setFixedHeight(18);
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setToolTip(tr("Convert to CNC delivery (carry overnight, locks full cash)"));
+ btn->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(37,99,235,0.15);color:%1;"
+ "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
+ "QPushButton#eqTableBtn:hover{background:rgba(37,99,235,0.30);}")
+ .arg(fincept::ui::colors::INFO(), fincept::ui::colors::BORDER_MED()));
+ const QString pid = p.id;
+ const QString sym = p.symbol;
+ connect(btn, &QPushButton::clicked, this,
+ [this, pid, sym]() { emit convert_position_requested(pid, sym, QStringLiteral("CNC")); });
+ positions_table_->setCellWidget(i, 9, btn);
+ } else {
+ positions_table_->setCellWidget(i, 9, nullptr);
+ }
}
+ update_positions_summary();
}
void EquityBottomPanel::set_paper_orders(const QVector<trading::PtOrder>& orders) {
@@ -486,84 +764,195 @@ void EquityBottomPanel::set_paper_orders(const QVector<trading::PtOrder>& orders
const auto& o = orders[i];
ensure_item(orders_table_, i, 0)->setText(o.id.left(8));
ensure_item(orders_table_, i, 1)->setText(o.symbol);
- ensure_item(orders_table_, i, 2)->setText(o.side.toUpper());
- ensure_item(orders_table_, i, 3)->setText(o.order_type.toUpper());
- ensure_item(orders_table_, i, 4)->setText(QString::number(o.quantity, 'f', 0));
- ensure_item(orders_table_, i, 5)->setText(o.price ? QString::number(*o.price, 'f', 2) : "MKT");
- ensure_item(orders_table_, i, 6)->setText(o.status.toUpper());
- ensure_item(orders_table_, i, 7)->setText(o.created_at);
- ensure_item(orders_table_, i, 8)->setText("");
+ ensure_item(orders_table_, i, 2)->setText(o.product.isEmpty() ? QStringLiteral("MIS") : o.product.toUpper());
+ ensure_item(orders_table_, i, 3)->setText(o.side.toUpper());
+ ensure_item(orders_table_, i, 4)->setText(o.order_type.toUpper());
+ ensure_item(orders_table_, i, 5)->setText(QString::number(o.quantity, 'f', 0));
+ ensure_item(orders_table_, i, 6)->setText(o.price ? QString::number(*o.price, 'f', 2) : tr("MKT"));
+
+ auto* status_item = ensure_item(orders_table_, i, 7);
+ status_item->setText(o.status.toUpper());
+ status_item->setForeground(order_status_color(o.status));
+
+ const QDateTime dt = QDateTime::fromString(o.created_at, Qt::ISODate).toLocalTime();
+ ensure_item(orders_table_, i, 8)->setText(dt.isValid() ? dt.toString("HH:mm:ss") : o.created_at);
+ // Paper orders are filled synchronously / by the matcher; no inline edit.
+ orders_table_->setCellWidget(i, 9, nullptr);
+ ensure_item(orders_table_, i, 9)->setText("");
}
}
-void EquityBottomPanel::set_paper_trades(const QVector<trading::PtTrade>& trades) {
- // Append trade rows below orders in the orders table (separated by a visual break)
- // We use a dedicated approach: show last 20 trades after orders
- const int base = orders_table_->rowCount();
- if (trades.isEmpty())
- return;
+void EquityBottomPanel::set_funds_view(const EquityFundsView& v) {
+ const QString sym = v.currency;
+ const QString pos = fincept::ui::colors::POSITIVE();
+ const QString neg = fincept::ui::colors::NEGATIVE();
+ const QString pri = fincept::ui::colors::TEXT_PRIMARY();
- // Add a separator row
- orders_table_->setRowCount(base + 1 + trades.size());
- auto* sep_item = ensure_item(orders_table_, base, 0);
- sep_item->setText(tr("--- RECENT TRADES ---"));
- sep_item->setForeground(QColor(fincept::ui::colors::AMBER()));
- for (int c = 1; c < 8; ++c)
- ensure_item(orders_table_, base, c)->setText("");
-
- for (int i = 0; i < trades.size(); ++i) {
- const auto& t = trades[i];
- const int row = base + 1 + i;
- ensure_item(orders_table_, row, 0)->setText(t.id.left(8));
- ensure_item(orders_table_, row, 1)->setText(t.symbol);
- ensure_item(orders_table_, row, 2)->setText(t.side.toUpper());
- ensure_item(orders_table_, row, 3)->setText("TRADE");
- ensure_item(orders_table_, row, 4)->setText(QString::number(t.quantity, 'f', 0));
- ensure_item(orders_table_, row, 5)->setText(QString::number(t.price, 'f', 2));
-
- auto* pnl_item = ensure_item(orders_table_, row, 6);
- pnl_item->setText(QString::number(t.pnl, 'f', 2));
- pnl_item->setForeground(t.pnl >= 0 ? QColor(fincept::ui::colors::POSITIVE())
- : QColor(fincept::ui::colors::NEGATIVE()));
-
- ensure_item(orders_table_, row, 7)->setText(t.timestamp);
- }
+ auto set_plain = [&](int idx, const QString& text) {
+ if (!fund_card_val_[idx])
+ return;
+ fund_card_val_[idx]->setText(text);
+ fund_card_val_[idx]->setStyleSheet(QString("color:%1;font-size:15px;font-weight:700;").arg(pri));
+ };
+ auto set_pnl = [&](int idx, double val) {
+ if (!fund_card_val_[idx])
+ return;
+ fund_card_val_[idx]->setText(fmt_money(val, sym, true));
+ fund_card_val_[idx]->setStyleSheet(
+ QString("color:%1;font-size:15px;font-weight:700;").arg(val >= 0 ? pos : neg));
+ };
+
+ set_plain(FC_Available, fmt_money(v.available, sym));
+ set_plain(FC_UsedMargin, fmt_money(v.used_margin, sym));
+ set_plain(FC_TotalEquity, fmt_money(v.total_equity, sym));
+ set_pnl(FC_RealizedPnl, v.realized_pnl);
+ set_pnl(FC_UnrealizedPnl, v.unrealized_pnl);
+ set_plain(FC_HoldingsValue, fmt_money(v.holdings_value, sym));
+ set_plain(FC_OpeningBalance, fmt_money(v.opening_balance, sym));
+ set_plain(FC_MarginUtil, QString::number(v.margin_util_pct, 'f', 1) + "%");
+ set_plain(FC_Collateral, fmt_money(v.collateral, sym));
+}
+
+void EquityBottomPanel::set_stats_view(const EquityStatsView& v) {
+ const QString sym = v.currency;
+ const QString pos = fincept::ui::colors::POSITIVE();
+ const QString neg = fincept::ui::colors::NEGATIVE();
+ const QString pri = fincept::ui::colors::TEXT_PRIMARY();
+
+ auto set_card = [&](int idx, const QString& text, const QString& color) {
+ if (!stat_card_val_[idx])
+ return;
+ stat_card_val_[idx]->setText(text);
+ stat_card_val_[idx]->setStyleSheet(QString("color:%1;font-size:15px;font-weight:700;").arg(color));
+ };
+ auto pnl_color = [&](double x) { return x >= 0 ? pos : neg; };
+
+ set_card(SC_NetPnl, fmt_money(v.net_pnl, sym, true), pnl_color(v.net_pnl));
+ set_card(SC_TodayPnl, fmt_money(v.today_pnl, sym, true), pnl_color(v.today_pnl));
+ set_card(SC_ReturnPct,
+ QString("%1%2%").arg(v.return_pct >= 0 ? "+" : "").arg(QString::number(v.return_pct, 'f', 2)),
+ pnl_color(v.return_pct));
+ set_card(SC_WinRate,
+ QString("%1% (%2/%3)")
+ .arg(QString::number(v.win_rate * 100, 'f', 1))
+ .arg(v.winning_trades)
+ .arg(v.winning_trades + v.losing_trades),
+ pri);
+ set_card(SC_ProfitFactor, v.profit_factor > 0 ? QString::number(v.profit_factor, 'f', 2) : QStringLiteral("--"),
+ pri);
+ set_card(SC_TotalTrades, QString::number(v.total_trades), pri);
+ set_card(SC_AvgWin, fmt_money(v.avg_win, sym, true), pos);
+ set_card(SC_AvgLoss, fmt_money(v.avg_loss, sym, true), neg);
+ set_card(SC_Turnover, fmt_money(v.turnover, sym), pri);
+ set_card(SC_LargestWin, fmt_money(v.largest_win, sym, true), pos);
+ set_card(SC_LargestLoss, fmt_money(v.largest_loss, sym, true), neg);
+ set_card(SC_TotalFees, fmt_money(v.total_fees, sym), pri);
}
-void EquityBottomPanel::set_paper_stats(const trading::PtStats& stats) {
- stat_values_[0]->setText(QString::number(stats.total_pnl, 'f', 2));
- stat_values_[0]->setStyleSheet(
- QString("color: %1;")
- .arg(stats.total_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
- stat_values_[1]->setText(QString("%1%").arg(stats.win_rate * 100, 0, 'f', 1));
- stat_values_[2]->setText(QString::number(stats.total_trades));
- stat_values_[3]->setText(QString::number(stats.largest_win, 'f', 2));
- stat_values_[3]->setStyleSheet(QString("color: %1;").arg(fincept::ui::colors::POSITIVE()));
- stat_values_[4]->setText(QString::number(stats.largest_loss, 'f', 2));
- stat_values_[4]->setStyleSheet(QString("color: %1;").arg(fincept::ui::colors::NEGATIVE()));
+void EquityBottomPanel::set_orders_date(const QDate& day) {
+ if (!orders_date_edit_)
+ return;
+ suppress_orders_date_signal_ = true;
+ orders_date_edit_->setDate(day);
+ suppress_orders_date_signal_ = false;
}
void EquityBottomPanel::set_positions(const QVector<trading::BrokerPosition>& positions) {
last_positions_ = positions; // keep row-aligned for live-quote patching
+ const QColor pos_color(fincept::ui::colors::POSITIVE());
+ const QColor neg_color(fincept::ui::colors::NEGATIVE());
positions_table_->setRowCount(positions.size());
for (int i = 0; i < positions.size(); ++i) {
const auto& p = positions[i];
ensure_item(positions_table_, i, 0)->setText(p.symbol);
- ensure_item(positions_table_, i, 1)->setText(p.exchange.isEmpty() ? "--" : p.exchange);
- ensure_item(positions_table_, i, 2)->setText(p.side.toUpper());
- ensure_item(positions_table_, i, 3)->setText(QString::number(p.quantity, 'f', 0));
- ensure_item(positions_table_, i, 4)->setText(QString::number(p.avg_price, 'f', 2));
- ensure_item(positions_table_, i, 5)->setText(QString::number(p.ltp, 'f', 2));
-
- auto* pnl_item = ensure_item(positions_table_, i, 6);
+ ensure_item(positions_table_, i, 1)->setText(p.product_type.isEmpty() ? "--" : p.product_type.toUpper());
+ ensure_item(positions_table_, i, 2)->setText(p.exchange.isEmpty() ? "--" : p.exchange);
+ ensure_item(positions_table_, i, 3)->setText(p.side.toUpper());
+ ensure_item(positions_table_, i, 4)->setText(QString::number(p.quantity, 'f', 0));
+ ensure_item(positions_table_, i, 5)->setText(QString::number(p.avg_price, 'f', 2));
+ ensure_item(positions_table_, i, 6)->setText(QString::number(p.ltp, 'f', 2));
+
+ auto* pnl_item = ensure_item(positions_table_, i, 7);
pnl_item->setText(QString::number(p.pnl, 'f', 2));
- pnl_item->setForeground(p.pnl >= 0 ? QColor(fincept::ui::colors::POSITIVE())
- : QColor(fincept::ui::colors::NEGATIVE()));
+ pnl_item->setForeground(p.pnl >= 0 ? pos_color : neg_color);
- auto* pct_item = ensure_item(positions_table_, i, 7);
+ auto* pct_item = ensure_item(positions_table_, i, 8);
pct_item->setText(QString("%1%").arg(p.pnl_pct, 0, 'f', 2));
- pct_item->setForeground(p.pnl_pct >= 0 ? QColor(fincept::ui::colors::POSITIVE())
- : QColor(fincept::ui::colors::NEGATIVE()));
+ pct_item->setForeground(p.pnl_pct >= 0 ? pos_color : neg_color);
+
+ positions_table_->setCellWidget(i, 9, nullptr); // no convert action in live mode
+ }
+ update_positions_summary();
+}
+
+void EquityBottomPanel::update_holding_quote(const QString& symbol, double ltp) {
+ // Find this symbol's holding (one per symbol) and re-mark it to the live price.
+ trading::BrokerHolding* h = nullptr;
+ for (auto& it : last_holdings_)
+ if (it.symbol == symbol) {
+ h = &it;
+ break;
+ }
+ if (!h)
+ return;
+ h->ltp = ltp;
+ h->current_value = h->quantity * ltp;
+ h->pnl = h->current_value - h->invested_value;
+ h->pnl_pct = h->invested_value > 0.0 ? (h->pnl / h->invested_value) * 100.0 : 0.0;
+
+ const QColor pos_color(fincept::ui::colors::POSITIVE());
+ const QColor neg_color(fincept::ui::colors::NEGATIVE());
+
+ // Patch the row in place. Sorting may reorder rows, so match on the symbol cell
+ // rather than assuming index alignment. Disable sorting during the writes.
+ const bool was_sorting = holdings_table_->isSortingEnabled();
+ holdings_table_->setSortingEnabled(false);
+ for (int r = 0; r < holdings_table_->rowCount(); ++r) {
+ auto* sym_item = holdings_table_->item(r, 0);
+ if (!sym_item || sym_item->text() != symbol)
+ continue;
+ auto set_num = [&](int col, double v) {
+ auto* item = ensure_item(holdings_table_, r, col);
+ item->setData(Qt::DisplayRole, QString::number(v, 'f', 2));
+ item->setData(Qt::EditRole, v);
+ };
+ set_num(3, ltp); // LTP
+ set_num(5, h->current_value); // Current
+ auto* pnl_item = ensure_item(holdings_table_, r, 6);
+ pnl_item->setData(Qt::DisplayRole, QString::number(h->pnl, 'f', 2));
+ pnl_item->setData(Qt::EditRole, h->pnl);
+ pnl_item->setForeground(h->pnl >= 0 ? pos_color : neg_color);
+ auto* pct_item = ensure_item(holdings_table_, r, 7);
+ pct_item->setData(Qt::DisplayRole, QString("%1%").arg(h->pnl_pct, 0, 'f', 2));
+ pct_item->setData(Qt::EditRole, h->pnl_pct);
+ pct_item->setForeground(h->pnl_pct >= 0 ? pos_color : neg_color);
+ break; // one row per symbol
+ }
+ holdings_table_->setSortingEnabled(was_sorting);
+
+ // Refresh the summary strip (CURRENT / TOTAL P&L / RETURN %); invested is fixed.
+ double total_invested = 0.0, total_current = 0.0, total_pnl = 0.0;
+ for (const auto& it : last_holdings_) {
+ total_invested += it.invested_value;
+ total_current += it.current_value;
+ total_pnl += it.pnl;
+ }
+ const double total_pct = total_invested > 0.0 ? (total_pnl / total_invested) * 100.0 : 0.0;
+ if (holdings_current_label_)
+ holdings_current_label_->setText(QString::number(total_current, 'f', 2));
+ if (holdings_pnl_label_) {
+ holdings_pnl_label_->setText(
+ QString("%1%2").arg(total_pnl >= 0 ? "+" : "").arg(QString::number(total_pnl, 'f', 2)));
+ holdings_pnl_label_->setStyleSheet(
+ QString("color:%1;font-size:13px;font-weight:700;")
+ .arg(total_pnl >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
+ }
+ if (holdings_pnl_pct_label_) {
+ holdings_pnl_pct_label_->setText(
+ QString("%1%2%").arg(total_pct >= 0 ? "+" : "").arg(QString::number(total_pct, 'f', 2)));
+ holdings_pnl_pct_label_->setStyleSheet(
+ QString("color:%1;font-size:13px;font-weight:700;")
+ .arg(total_pct >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE()));
}
}
@@ -572,15 +961,19 @@ void EquityBottomPanel::update_quote(const QString& symbol, const trading::Broke
if (ltp <= 0.0 || symbol.isEmpty())
return; // ignore empty / zero-price ticks — keep the last good values
+ // Holdings (CNC) live the same quote stream as positions — patch them too.
+ update_holding_quote(symbol, ltp);
+
const QColor pos_color(fincept::ui::colors::POSITIVE());
const QColor neg_color(fincept::ui::colors::NEGATIVE());
+ // Columns shift by +1 vs the pre-Product layout: LTP=6, P&L=7, P&L%=8.
auto paint = [&](int row, double pnl, double pnl_pct) {
- ensure_item(positions_table_, row, 5)->setText(QString::number(ltp, 'f', 2));
- auto* pnl_item = ensure_item(positions_table_, row, 6);
+ ensure_item(positions_table_, row, 6)->setText(QString::number(ltp, 'f', 2));
+ auto* pnl_item = ensure_item(positions_table_, row, 7);
pnl_item->setText(QString::number(pnl, 'f', 2));
pnl_item->setForeground(pnl >= 0 ? pos_color : neg_color);
- auto* pct_item = ensure_item(positions_table_, row, 7);
+ auto* pct_item = ensure_item(positions_table_, row, 8);
pct_item->setText(QString("%1%").arg(pnl_pct, 0, 'f', 2));
pct_item->setForeground(pnl_pct >= 0 ? pos_color : neg_color);
};
@@ -601,6 +994,7 @@ void EquityBottomPanel::update_quote(const QString& symbol, const trading::Broke
const double pct = notional != 0.0 ? (p.unrealized_pnl / notional) * 100.0 : 0.0;
paint(i, p.unrealized_pnl, pct);
}
+ update_positions_summary();
return;
}
@@ -620,6 +1014,7 @@ void EquityBottomPanel::update_quote(const QString& symbol, const trading::Broke
p.pnl_pct = notional > 0.0 ? (p.pnl / notional) * 100.0 : 0.0;
paint(i, p.pnl, p.pnl_pct);
}
+ update_positions_summary();
}
void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& holdings) {
@@ -702,12 +1097,15 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
const auto& o = orders[i];
ensure_item(orders_table_, i, 0)->setText(o.order_id.left(12));
ensure_item(orders_table_, i, 1)->setText(o.symbol);
- ensure_item(orders_table_, i, 2)->setText(o.side.toUpper());
- ensure_item(orders_table_, i, 3)->setText(o.order_type.toUpper());
- ensure_item(orders_table_, i, 4)->setText(QString::number(o.quantity, 'f', 0));
- ensure_item(orders_table_, i, 5)->setText(QString::number(o.price, 'f', 2));
- ensure_item(orders_table_, i, 6)->setText(o.status.toUpper());
- ensure_item(orders_table_, i, 7)->setText(o.timestamp);
+ ensure_item(orders_table_, i, 2)->setText(o.product_type.isEmpty() ? "--" : o.product_type.toUpper());
+ ensure_item(orders_table_, i, 3)->setText(o.side.toUpper());
+ ensure_item(orders_table_, i, 4)->setText(o.order_type.toUpper());
+ ensure_item(orders_table_, i, 5)->setText(QString::number(o.quantity, 'f', 0));
+ ensure_item(orders_table_, i, 6)->setText(QString::number(o.price, 'f', 2));
+ auto* status_item = ensure_item(orders_table_, i, 7);
+ status_item->setText(o.status.toUpper());
+ status_item->setForeground(order_status_color(o.status));
+ ensure_item(orders_table_, i, 8)->setText(o.timestamp);
// Action column — MODIFY button for open/pending orders
const bool modifiable = (o.status == "new" || o.status == "partially_filled" || o.status == "accepted" ||
@@ -780,20 +1178,13 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
dlg->exec();
dlg->deleteLater();
});
- orders_table_->setCellWidget(i, 8, btn);
+ orders_table_->setCellWidget(i, 9, btn);
} else {
- orders_table_->setCellWidget(i, 8, nullptr);
+ orders_table_->setCellWidget(i, 9, nullptr);
}
}
}
-void EquityBottomPanel::set_funds(const trading::BrokerFunds& funds) {
- available_label_->setText(QString::number(funds.available_balance, 'f', 2));
- used_margin_label_->setText(QString::number(funds.used_margin, 'f', 2));
- total_label_->setText(QString::number(funds.total_balance, 'f', 2));
- collateral_label_->setText(QString::number(funds.collateral, 'f', 2));
-}
-
// ── Auctions Tab ────────────────────────────────────────────────────────────
void EquityBottomPanel::setup_auctions_tab() {
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
index e1d09b31c..1c58e4c53 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
@@ -5,6 +5,7 @@
#include "trading/BrokerInterface.h"
#include "trading/TradingTypes.h"
+#include <QDate>
#include <QEvent>
#include <QLabel>
#include <QList>
@@ -14,6 +15,8 @@
#include <QVector>
#include <QWidget>
+class QDateEdit;
+
namespace fincept::screens::equity {
class EquityBottomPanel : public QWidget {
@@ -24,8 +27,6 @@ class EquityBottomPanel : public QWidget {
// Paper mode data
void set_paper_positions(const QVector<trading::PtPosition>& positions);
void set_paper_orders(const QVector<trading::PtOrder>& orders);
- void set_paper_trades(const QVector<trading::PtTrade>& trades);
- void set_paper_stats(const trading::PtStats& stats);
// Live broker data
void set_positions(const QVector<trading::BrokerPosition>& positions);
@@ -38,7 +39,12 @@ class EquityBottomPanel : public QWidget {
void update_quote(const QString& symbol, const trading::BrokerQuote& quote);
void set_orders(const QVector<trading::BrokerOrderInfo>& orders);
- void set_funds(const trading::BrokerFunds& funds);
+ // Funds + Stats render from view-models so the panel is source-agnostic; the
+ // screen builds them from the paper engine (paper) or BrokerFunds (live).
+ void set_funds_view(const EquityFundsView& view);
+ void set_stats_view(const EquityStatsView& view);
+ // Set the orders date-picker without emitting orders_day_changed (programmatic).
+ void set_orders_date(const QDate& day);
void set_calendar(const QVector<trading::MarketCalendarDay>& days);
void set_clock(const trading::MarketClock& clock);
void set_auctions(const QVector<trading::BrokerAuction>& auctions);
@@ -50,6 +56,14 @@ class EquityBottomPanel : public QWidget {
void set_account_id(const QString& account_id);
+ // Currency symbol (₹/$/…) used to format the positions action-bar P&L totals.
+ void set_currency(const QString& sym);
+
+ // Show/hide the US-market-only tabs (Time & Sales, Auctions, Calendar). These
+ // carry tape/condition/auction data that only US brokers (Alpaca etc.) provide,
+ // so they're hidden for Indian and other non-US brokers.
+ void set_us_market_tabs_visible(bool visible);
+
// Collapse the sheet down to just its tab-bar header (and back).
void toggle_collapsed();
bool is_collapsed() const { return collapsed_; }
@@ -60,6 +74,15 @@ class EquityBottomPanel : public QWidget {
void import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
void cancel_all_orders_requested(const QString& account_id);
void close_all_positions_requested(const QString& account_id);
+ // Paper: convert an open position's product in place (MIS -> CNC), identified
+ // by its paper position id.
+ void convert_position_requested(const QString& position_id, const QString& symbol, const QString& new_product);
+ // Orders tab date-selector changed — request that IST day's order book.
+ void orders_day_changed(const QDate& day);
+ // Square off the subset of open positions by P&L sign (+1 winners, -1 losers).
+ void square_off_group_requested(const QString& account_id, int sign);
+ // Right-click Buy(add)/Sell(reduce) on a position or holding row.
+ void trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy);
protected:
void changeEvent(QEvent* event) override;
@@ -76,6 +99,15 @@ class EquityBottomPanel : public QWidget {
void setup_time_sales_tab();
void setup_auctions_tab();
+ // Recompute the positions action-bar summary (net P&L + winners/losers chips)
+ // from the current backing vectors. Called on every (re)load and quote patch.
+ void update_positions_summary();
+
+ // Live-quote patch for the Holdings table (CNC delivery): updates LTP / current
+ // value / P&L for the symbol's row and the summary strip, in place — same per
+ // tick refresh as the Positions table so Holdings tracks in real time.
+ void update_holding_quote(const QString& symbol, double ltp);
+
static QTableWidgetItem* ensure_item(QTableWidget* table, int row, int col);
QTabWidget* tabs_ = nullptr;
@@ -101,6 +133,15 @@ class EquityBottomPanel : public QWidget {
// quotes can patch LTP / P&L / P&L% in place (no full rebuild, no flicker).
QVector<trading::BrokerPosition> last_positions_; // live mode
QVector<trading::PtPosition> last_paper_positions_; // paper mode
+
+ // Positions action-bar summary: net P&L + winners/losers chips, each with a
+ // group square-off button. Updated by update_positions_summary().
+ QLabel* positions_total_pnl_label_ = nullptr;
+ QLabel* positions_win_label_ = nullptr;
+ QLabel* positions_loss_label_ = nullptr;
+ class QPushButton* win_squareoff_btn_ = nullptr;
+ class QPushButton* loss_squareoff_btn_ = nullptr;
+ QString currency_sym_ = QStringLiteral("₹"); // for action-bar P&L formatting
QTableWidget* holdings_table_ = nullptr;
QLabel* holdings_invested_label_ = nullptr;
QLabel* holdings_current_label_ = nullptr;
@@ -116,6 +157,8 @@ class EquityBottomPanel : public QWidget {
class QPushButton* holdings_import_btn_ = nullptr;
QVector<trading::BrokerHolding> last_holdings_;
QTableWidget* orders_table_ = nullptr;
+ QDateEdit* orders_date_edit_ = nullptr; // per-day order book selector
+ bool suppress_orders_date_signal_ = false; // guard during programmatic set
QTableWidget* calendar_table_ = nullptr;
QTableWidget* time_sales_table_ = nullptr;
QString time_sales_symbol_; // track last symbol to detect change
@@ -126,20 +169,15 @@ class EquityBottomPanel : public QWidget {
QLabel* clock_status_label_ = nullptr;
QLabel* clock_next_label_ = nullptr;
- // Funds labels
- QLabel* available_label_ = nullptr;
- QLabel* used_margin_label_ = nullptr;
- QLabel* total_label_ = nullptr;
- QLabel* collateral_label_ = nullptr;
- // Funds row caption labels (cached for retranslateUi)
- QLabel* available_caption_ = nullptr;
- QLabel* used_margin_caption_ = nullptr;
- QLabel* total_caption_ = nullptr;
- QLabel* collateral_caption_ = nullptr;
-
- // Stats labels
- QLabel* stat_values_[5] = {};
- QLabel* stat_captions_[5] = {};
+ // Funds tab — card grid. Index order is documented by FundCard in the .cpp.
+ static constexpr int kFundCards = 9;
+ QLabel* fund_card_val_[kFundCards] = {};
+ QLabel* fund_card_cap_[kFundCards] = {};
+
+ // Stats tab — card grid. Index order is documented by StatCard in the .cpp.
+ static constexpr int kStatCards = 12;
+ QLabel* stat_card_val_[kStatCards] = {};
+ QLabel* stat_card_cap_[kStatCards] = {};
// Bulk action buttons
class QPushButton* cancel_all_btn_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 56f466ff1..fe71fad51 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -14,6 +14,7 @@
#include "core/symbol/SymbolContext.h"
#include "core/symbol/SymbolDragSource.h"
+#include <QAbstractItemView>
#include <QApplication>
#include <QMouseEvent>
#include "screens/equity_trading/AccountManagementDialog.h"
@@ -24,6 +25,8 @@
#include "screens/equity_trading/EquityOrderEntry.h"
#include "screens/equity_trading/EquityTickerBar.h"
#include "screens/equity_trading/EquityWatchlist.h"
+#include "screens/common/feeds/FeedPanel.h"
+#include "services/feeds/FeedMonitor.h"
#include "services/portfolio/PortfolioService.h"
#include "storage/repositories/SettingsRepository.h"
#include "trading/AccountManager.h"
@@ -117,25 +120,30 @@ EquityTradingScreen::~EquityTradingScreen() {
void EquityTradingScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
- // Restore persisted session state on first show
+ // Always make sure a configured broker is loaded. Re-checked on every show so a
+ // broker configured after the tab first opened is picked up automatically,
+ // instead of stranding the user on "NO ACCOUNT" while a broker exists in the DB.
+ ensure_account_loaded();
+
+ // Restore the rest of the persisted session state on first show.
if (!initialized_) {
const auto s = ScreenStateManager::instance().load_direct("equity_trading");
if (!s.isEmpty()) {
- const QString acct = s.value("focused_account_id").toString();
const QString sym = s.value("selected_symbol", selected_symbol_).toString();
- if (!acct.isEmpty() && acct != focused_account_id_ && AccountManager::instance().has_account(acct))
- on_account_changed(acct);
- if (sym != selected_symbol_)
+ if (!sym.isEmpty() && 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);
+ // Restore the feed column (visibility + width).
+ if (s.value("feeds_visible").toBool()) {
+ feeds_btn_->setChecked(true); // toggled() shows the panel
+ const int w = s.value("feeds_width").toInt();
+ if (w > 50 && main_splitter_) {
+ auto sizes = main_splitter_->sizes();
+ if (sizes.size() == 4) {
+ sizes[3] = w;
+ main_splitter_->setSizes(sizes);
+ }
+ }
+ }
}
}
@@ -146,6 +154,12 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
// Hub subscriptions for streaming data (D4)
hub_subscribe_streaming();
+ // Catch up intraday auto-square for paper portfolios (e.g. the app was closed
+ // at 15:30, so yesterday's MIS positions never squared). Refresh picks up the
+ // resulting state; it no-ops for live accounts.
+ trading::pt_settle_intraday_all();
+ refresh_paper_panels();
+
// UI-local timers
if (clock_timer_)
clock_timer_->start();
@@ -157,6 +171,8 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
initialized_ = true;
}
+ fincept::feeds::FeedMonitor::instance().resume_all();
+
LOG_INFO(TAG, "Screen visible — data streams resumed");
}
@@ -169,10 +185,14 @@ void EquityTradingScreen::hideEvent(QHideEvent* event) {
if (market_clock_timer_)
market_clock_timer_->stop();
+ fincept::feeds::FeedMonitor::instance().pause_all();
+
ScreenStateManager::instance().save_direct("equity_trading", {
{"focused_account_id", focused_account_id_},
{"selected_symbol", selected_symbol_},
{"selected_exchange", selected_exchange_},
+ {"feeds_visible", feed_panel_ != nullptr && feed_panel_->isVisible()},
+ {"feeds_width", main_splitter_ != nullptr ? main_splitter_->sizes().value(3) : 0},
});
LOG_INFO(TAG, "Screen hidden — data streams paused, hub unsubscribed");
}
@@ -245,6 +265,21 @@ void EquityTradingScreen::setup_ui() {
// Choosing a suggestion (click / Enter in the popup) activates that symbol.
connect(symbol_completer_, qOverload<const QString&>(&QCompleter::activated), this,
[this](const QString& choice) { apply_symbol_input(choice); });
+ // A single mouse-click on a suggestion must select it. QCompleter::activated is
+ // unreliable on click for a model rebuilt every keystroke, so wire the popup's
+ // clicked() directly (and give the dropdown a clean dark style).
+ if (auto* popup = symbol_completer_->popup()) {
+ popup->setObjectName("eqSymbolPopup");
+ popup->setStyleSheet(
+ QString("QAbstractItemView{background:%1;color:%2;border:1px solid %3;outline:0;padding:2px;"
+ "font-size:11px;}"
+ "QAbstractItemView::item{padding:4px 8px;border-radius:2px;}"
+ "QAbstractItemView::item:selected,QAbstractItemView::item:hover{background:%4;color:%2;}")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(),
+ fincept::ui::colors::BORDER_MED(), fincept::ui::colors::BG_HOVER()));
+ connect(popup, &QAbstractItemView::clicked, this,
+ [this](const QModelIndex& idx) { apply_symbol_input(idx.data(Qt::DisplayRole).toString()); });
+ }
connect(symbol_input_, &QLineEdit::returnPressed, this,
[this]() { apply_symbol_input(symbol_input_->text()); });
cmd_layout->addWidget(symbol_input_);
@@ -285,10 +320,19 @@ void EquityTradingScreen::setup_ui() {
mode_btn_->setCursor(Qt::PointingHandCursor);
cmd_layout->addWidget(mode_btn_);
+ // FEEDS — toggles the far-right feed monitor column.
+ feeds_btn_ = new QPushButton(tr("FEEDS"));
+ feeds_btn_->setObjectName("eqApiBtn");
+ feeds_btn_->setFixedHeight(22);
+ feeds_btn_->setCheckable(true);
+ feeds_btn_->setCursor(Qt::PointingHandCursor);
+ cmd_layout->addWidget(feeds_btn_);
+
main_layout->addWidget(cmd_bar);
// ── MAIN 3-PANEL SPLITTER ─────────────────────────────────────────────────
- auto* main_splitter = new QSplitter(Qt::Horizontal);
+ main_splitter_ = new QSplitter(Qt::Horizontal);
+ auto* main_splitter = main_splitter_;
main_splitter->setObjectName("eqMainSplitter");
main_splitter->setHandleWidth(1);
@@ -338,15 +382,32 @@ void EquityTradingScreen::setup_ui() {
main_splitter->addWidget(right_splitter);
- main_splitter->setSizes({265, 555, 290});
+ // FAR RIGHT: collapsible feed monitor column (hidden by default; toggled via the
+ // FEEDS command-bar button). Reusable FeedPanel — see screens/common/feeds.
+ feed_panel_ = new fincept::feeds::FeedPanel;
+ feed_panel_->setVisible(false);
+ main_splitter->addWidget(feed_panel_);
+
+ main_splitter->setSizes({265, 555, 290, 0});
main_splitter->setStretchFactor(0, 0);
main_splitter->setStretchFactor(1, 1);
main_splitter->setStretchFactor(2, 0);
+ main_splitter->setStretchFactor(3, 0);
main_layout->addWidget(main_splitter, 1);
// ── Signal Connections ────────────────────────────────────────────────────
connect(mode_btn_, &QPushButton::clicked, this, &EquityTradingScreen::on_mode_toggled);
+ connect(feeds_btn_, &QPushButton::toggled, this, [this](bool on) {
+ feed_panel_->setVisible(on);
+ if (on) {
+ auto sizes = main_splitter_->sizes();
+ if (sizes.size() == 4 && sizes[3] < 50) {
+ sizes[3] = 300;
+ main_splitter_->setSizes(sizes);
+ }
+ }
+ });
connect(accounts_btn_, &QPushButton::clicked, this, &EquityTradingScreen::on_accounts_clicked);
connect(watchlist_, &EquityWatchlist::symbol_selected, this, &EquityTradingScreen::on_symbol_selected);
connect(watchlist_, &EquityWatchlist::symbol_added, this, &EquityTradingScreen::on_watchlist_symbol_added);
@@ -370,6 +431,13 @@ void EquityTradingScreen::setup_ui() {
connect(bottom_panel_, &EquityBottomPanel::close_all_positions_requested, this,
[this](const QString&) { on_close_all_positions(); });
connect(bottom_panel_, &EquityBottomPanel::import_holdings_requested, this, &EquityTradingScreen::on_import_holdings_requested);
+ connect(bottom_panel_, &EquityBottomPanel::convert_position_requested, this,
+ &EquityTradingScreen::on_convert_position);
+ connect(bottom_panel_, &EquityBottomPanel::orders_day_changed, this, &EquityTradingScreen::on_orders_day_changed);
+ connect(bottom_panel_, &EquityBottomPanel::square_off_group_requested, this,
+ &EquityTradingScreen::on_square_off_group);
+ connect(bottom_panel_, &EquityBottomPanel::trade_symbol_requested, this,
+ &EquityTradingScreen::on_trade_symbol_requested);
connect(chart_, &EquityChartPanel::timeframe_changed, this, [this](const QString& tf) {
auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
if (stream)
@@ -396,18 +464,20 @@ void EquityTradingScreen::setup_timers() {
market_clock_timer_ = new QTimer(this);
connect(market_clock_timer_, &QTimer::timeout, this, [this]() {
auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
- if (stream)
- stream->fetch_clock();
+ if (stream && focused_is_us_market_)
+ stream->fetch_clock(); // US-only market clock (Alpaca calendar tab)
+ // Paper intraday auto-square at 15:30 IST. Cheap no-op until the cutoff;
+ // refreshes the panels only when something was actually squared off.
+ if (trading::pt_settle_intraday_all() > 0)
+ refresh_paper_panels();
});
market_clock_timer_->setInterval(60000);
- // Deferred init — auto-select first account if none focused
+ // Deferred init — auto-select the configured broker if none is focused yet.
+ // Routes through the single credential-aware resolver so it can't pick an
+ // unconfigured (no-credentials) broker that merely sorts first in the map.
QTimer::singleShot(100, this, [this]() {
- if (focused_account_id_.isEmpty()) {
- auto accounts = AccountManager::instance().active_accounts();
- if (!accounts.isEmpty())
- on_account_changed(accounts.first().account_id);
- }
+ ensure_account_loaded();
update_account_menu();
update_connection_status();
});
@@ -533,6 +603,54 @@ void EquityTradingScreen::connect_data_stream_signals() {
// Init
// ============================================================================
+void EquityTradingScreen::ensure_account_loaded() {
+ auto& am = AccountManager::instance();
+
+ // Respect the current focus when it's a live session, or — once the user has
+ // started interacting (post-init) — any valid account, so manual broker switches
+ // are never undone. The smart auto-pick only happens at startup / when stranded.
+ const bool focus_valid = !focused_account_id_.isEmpty() && am.has_account(focused_account_id_);
+ if (focus_valid) {
+ const bool live = am.get_account(focused_account_id_).state == ConnectionState::Connected;
+ if (live || initialized_)
+ return;
+ }
+
+ const QString saved =
+ ScreenStateManager::instance().load_direct("equity_trading").value("focused_account_id").toString();
+
+ // Rank every account so the *connected* broker wins over one whose token is
+ // expired or that was merely added. Tiers (×2 so the saved tie-breaker can only
+ // reorder within a tier, never across):
+ // Connected (live session) → 4 ← what the user means by "configured"
+ // Connecting (token, unknown expiry) → 3
+ // has credentials (api_key) but dead → 1
+ // added, no credentials → 0
+ auto score = [&am](const BrokerAccount& a) -> int {
+ switch (a.state) {
+ case ConnectionState::Connected: return 4;
+ case ConnectionState::Connecting: return 3;
+ default: break; // TokenExpired / Error / Disconnected
+ }
+ return am.load_credentials(a.account_id).api_key.isEmpty() ? 0 : 1;
+ };
+
+ QString best;
+ int best_rank = -1;
+ for (const auto& a : am.list_accounts()) {
+ const int rank = score(a) * 2 + (a.account_id == saved ? 1 : 0);
+ if (rank > best_rank) {
+ best_rank = rank;
+ best = a.account_id;
+ }
+ }
+
+ // on_account_changed() configures the UI and (when credentials exist) loads the
+ // instrument master + starts the data stream; it is a no-op for a focused match.
+ if (!best.isEmpty() && best != focused_account_id_)
+ on_account_changed(best);
+}
+
void EquityTradingScreen::init_focused_account() {
if (focused_account_id_.isEmpty())
return;
@@ -702,9 +820,10 @@ void EquityTradingScreen::restore_state(const QVariantMap& state) {
const QString sym = state.value("symbol", "RELIANCE").toString();
if (!sym.isEmpty() && sym != selected_symbol_)
on_symbol_selected(sym);
- const QString acct = state.value("account_id").toString();
- if (!acct.isEmpty() && acct != focused_account_id_)
- on_account_changed(acct);
+ // Account selection goes through the single connection-aware resolver (which
+ // reads the saved account itself) rather than forcing state["account_id"] — that
+ // direct path used to override the resolver and load an expired/unconfigured broker.
+ ensure_account_loaded();
// Honour the restored list even when the account didn't change (idempotent).
if (!wl.isEmpty() && !focused_account_id_.isEmpty())
load_watchlists();
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index bf5ca3781..50d85ed77 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -9,6 +9,7 @@
#include "trading/BrokerAccount.h"
#include "trading/TradingTypes.h"
+#include <QDate>
#include <QEvent>
#include <QHash>
#include <QHideEvent>
@@ -24,6 +25,11 @@
class QCompleter;
class QStringListModel;
+class QSplitter;
+
+namespace fincept::feeds {
+class FeedPanel;
+}
namespace fincept::screens::equity {
class EquityTickerBar;
@@ -76,6 +82,14 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void on_strategy_submitted(const trading::BasketOrderRequest& basket); // options strategy → basket
void on_ob_price_clicked(double price);
void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
+ // Paper: convert a position's product in place (MIS -> CNC) then refresh.
+ void on_convert_position(const QString& position_id, const QString& symbol, const QString& new_product);
+ // Orders tab date-selector changed — show that IST day's paper order book.
+ void on_orders_day_changed(const QDate& day);
+ // Square off the subset of open positions by P&L sign (+1 winners, -1 losers).
+ void on_square_off_group(const QString& account_id, int sign);
+ // Right-click Buy/Sell on a position or holding → open an order ticket.
+ void on_trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy);
// EXIT clicked on the chart's position card → confirm + square off the symbol.
void on_chart_exit_position(const QString& symbol, const QString& exchange,
const QString& product_type, const QString& side, double qty);
@@ -114,6 +128,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void retranslateUi();
void connect_data_stream_signals();
void init_focused_account();
+ // Ensure a configured broker is focused (saved → active → any configured).
+ // Called on every show so a broker configured later is picked up automatically.
+ void ensure_account_loaded();
void switch_symbol(const QString& symbol);
// Parse a (possibly "SYMBOL · EXCH · Broker") command-bar entry and activate it.
void apply_symbol_input(const QString& raw);
@@ -130,6 +147,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void on_chart_sell_requested(double price);
void on_chart_add_to_watchlist();
void open_chart_order_ticket(bool is_buy, double price);
+ // Generalized order ticket for an arbitrary symbol/product (right-click trade
+ // from the positions/holdings tables). Routes through on_order_submitted().
+ void open_order_ticket_for(const QString& symbol, const QString& exchange, const QString& product, bool is_buy);
// 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();
@@ -168,7 +188,12 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
QLineEdit* symbol_input_ = nullptr;
QCompleter* symbol_completer_ = nullptr; // dynamic instrument-search popup
QStringListModel* symbol_completer_model_ = nullptr; // suggestions, refreshed per keystroke
+ // Friendly picker label → canonical symbol, rebuilt each keystroke. Lets the
+ // popup show clean F&O names (e.g. "NIFTY 7 Jul 26 18250 CE") while still
+ // resolving the real symbol (NIFTY07JUL2618250CE) on select.
+ QHash<QString, QString> symbol_suggestion_map_;
QPushButton* mode_btn_ = nullptr;
+ QPushButton* feeds_btn_ = nullptr; // toggles the far-right feed monitor column
QPushButton* accounts_btn_ = nullptr; // opens AccountManagementDialog
QLabel* exchange_label_ = nullptr;
QLabel* clock_label_ = nullptr;
@@ -181,6 +206,8 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
equity::EquityOrderEntry* order_entry_ = nullptr;
equity::EquityOrderBook* orderbook_ = nullptr;
equity::EquityBottomPanel* bottom_panel_ = nullptr;
+ fincept::feeds::FeedPanel* feed_panel_ = nullptr; // collapsible far-right feed column
+ QSplitter* main_splitter_ = nullptr; // kept to toggle the feed column width
// ── Timers (only UI-local timers remain; data timers are in AccountDataStream) ──
QTimer* clock_timer_ = nullptr;
@@ -197,6 +224,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
// 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;
+ // True when the focused broker is a US-market broker (region == "US"). Gates the
+ // US-only data fetches (time&sales / calendar / clock) and bottom-panel tabs.
+ bool focused_is_us_market_ = 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
@@ -210,6 +240,9 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
QStringList watchlist_symbols_;
QString active_watchlist_id_; // current WatchlistRepository list id
+ // Paper order book day shown in the Orders tab (default today; date selector
+ // moves it to view a past IST session). Open positions/holdings stay current.
+ QDate orders_view_day_ = QDate::currentDate();
QStringList position_symbols_; // symbols with open positions (transient, for live pricing)
QVector<trading::BrokerPosition> live_positions_; // cached live positions for focused account
double current_price_ = 0.0; // last known LTP for selected symbol
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 36c6278f9..ee0d5c3d0 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -29,6 +29,7 @@
#include "trading/DataStreamManager.h"
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
+#include "trading/instruments/InstrumentNormalize.h"
#include "trading/instruments/InstrumentService.h"
#include "ui/theme/StyleSheets.h"
#include "ui/theme/Theme.h"
@@ -100,6 +101,11 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
order_entry_->configure_for_broker(prof);
order_entry_->set_broker_id(account.broker_id);
watchlist_->set_broker_id(account.broker_id);
+
+ // Time & Sales / Auctions / Calendar are US-broker-only market data —
+ // show those tabs and run their fetches only for US brokers (Alpaca etc.).
+ focused_is_us_market_ = (prof.region == QLatin1String("US"));
+ bottom_panel_->set_us_market_tabs_visible(focused_is_us_market_);
}
// Update mode button to reflect this account's trading mode
@@ -147,12 +153,18 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
- stream->fetch_time_sales(selected_symbol_);
- stream->fetch_calendar();
- stream->fetch_clock();
+ // US-only market data — skip for Indian/other brokers (no tape/calendar).
+ if (focused_is_us_market_) {
+ stream->fetch_time_sales(selected_symbol_);
+ stream->fetch_calendar();
+ stream->fetch_clock();
+ }
}
}
+ // Each account's order book opens on today's session.
+ orders_view_day_ = QDate::currentDate();
+
// Load paper portfolio orders into matcher
if (!account.paper_portfolio_id.isEmpty() && account.trading_mode == "paper") {
auto pending = pt_get_orders(account.paper_portfolio_id, "pending");
@@ -160,7 +172,7 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
if (o.order_type != "market")
OrderMatcher::instance().add_order(o);
}
- // Refresh paper data immediately (positions/orders/trades/stats/funds).
+ // Refresh paper data immediately (positions/holdings/orders/funds/stats).
refresh_paper_panels();
}
@@ -203,7 +215,7 @@ void EquityTradingScreen::switch_symbol(const QString& symbol) {
stream->fetch_orderbook(symbol);
auto account = AccountManager::instance().get_account(focused_account_id_);
- if (account.trading_mode == "live") {
+ if (account.trading_mode == "live" && focused_is_us_market_) {
stream->fetch_time_sales(symbol);
}
}
@@ -239,10 +251,17 @@ void EquityTradingScreen::on_symbol_search_changed(const QString& text) {
const auto results = InstrumentService::instance().search_all(query, "", ids, 24);
QStringList suggestions;
suggestions.reserve(results.size());
+ symbol_suggestion_map_.clear();
for (const auto& inst : results) {
- auto* b = BrokerRegistry::instance().get(inst.broker_id);
- const QString broker_name = b ? b->profile().display_name : inst.broker_id;
- suggestions.append(QString("%1 · %2 · %3").arg(inst.symbol, inst.exchange, broker_name));
+ // Show a clean human label (e.g. "NIFTY 7 Jul 26 18250 CE · NFO") instead
+ // of the raw canonical symbol, and remember the real symbol for selection.
+ const QString friendly =
+ norm::display_name(inst.name, inst.instrument_type, inst.expiry, inst.strike, inst.symbol);
+ const QString label = QStringLiteral("%1 · %2").arg(friendly, inst.exchange);
+ if (symbol_suggestion_map_.contains(label))
+ continue; // collapse identical labels surfaced by multiple brokers
+ symbol_suggestion_map_.insert(label, inst.symbol);
+ suggestions.append(label);
}
symbol_completer_model_->setStringList(suggestions);
// Re-evaluate the popup against the just-updated model; otherwise the
@@ -253,11 +272,15 @@ void EquityTradingScreen::on_symbol_search_changed(const QString& text) {
}
void EquityTradingScreen::apply_symbol_input(const QString& raw) {
- // A chosen suggestion is "SYMBOL · EXCH · Broker" — keep only the leading
- // symbol token. Also tolerate the legacy "EXCHANGE:SYMBOL" form and bare input.
- QString sym = raw.trimmed().section(QStringLiteral(" · "), 0, 0).trimmed().toUpper();
- if (sym.contains(':'))
- sym = sym.section(':', 1);
+ const QString trimmed = raw.trimmed();
+ // A picked suggestion maps its friendly label back to the real symbol.
+ QString sym = symbol_suggestion_map_.value(trimmed);
+ if (sym.isEmpty()) {
+ // Typed text or legacy "SYMBOL · EXCH" / "EXCHANGE:SYMBOL" forms.
+ sym = trimmed.section(QStringLiteral(" · "), 0, 0).trimmed().toUpper();
+ if (sym.contains(':'))
+ sym = sym.section(':', 1);
+ }
if (sym.isEmpty())
return;
on_symbol_selected(sym);
@@ -316,13 +339,10 @@ void EquityTradingScreen::on_accounts_clicked() {
connect(dlg, &AccountManagementDialog::account_removed, this, [this](const QString& account_id) {
DataStreamManager::instance().stop_stream(account_id);
update_account_menu();
- // If removed the focused account, switch to next available
+ // If removed the focused account, switch to the next configured broker.
if (account_id == focused_account_id_) {
- auto accounts = AccountManager::instance().active_accounts();
- if (!accounts.isEmpty())
- on_account_changed(accounts.first().account_id);
- else
- focused_account_id_.clear();
+ focused_account_id_.clear();
+ ensure_account_loaded(); // credential-aware next pick
}
update_connection_status();
});
@@ -401,8 +421,14 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
return;
}
+ // Forward the exchange + broker product (MIS/CNC/NRML) so the engine
+ // applies per-product leverage, tags the position, and routes CNC to the
+ // Holdings tab. Without this the product was silently dropped (everything
+ // looked like blank-product CNC) and MIS could never be told apart.
+ const QString product = product_to_broker_str(order.product_type);
try {
- auto pt_order = pt_place_order(portfolio_id, order.symbol, side, type, order.quantity, price_opt, stop_opt);
+ auto pt_order = pt_place_order(portfolio_id, order.symbol, side, type, order.quantity, price_opt,
+ stop_opt, /*reduce_only=*/false, order.exchange, product);
if (order.order_type == OrderType::Market) {
double fill_price = current_price_ > 0 ? current_price_ : (order.price > 0 ? order.price : 0.0);
@@ -422,19 +448,8 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
return;
}
- // Refresh paper portfolio
- try {
- auto portfolio = pt_get_portfolio(portfolio_id);
- auto positions = pt_get_positions(portfolio_id);
- auto orders_list = pt_get_orders(portfolio_id);
- auto trades = pt_get_trades(portfolio_id, 50);
- auto stats = pt_get_stats(portfolio_id);
- order_entry_->set_balance(portfolio.balance);
- bottom_panel_->set_paper_positions(positions);
- bottom_panel_->set_paper_orders(orders_list);
- bottom_panel_->set_paper_trades(trades);
- bottom_panel_->set_paper_stats(stats);
- } catch (...) {}
+ // Refresh paper portfolio (positions/holdings/orders/funds/stats).
+ refresh_paper_panels();
} else {
// Route to live broker via account-aware UnifiedTrading
// Safety: capture account_id by value at click time (immutable per order lifecycle)
@@ -571,20 +586,7 @@ void EquityTradingScreen::on_cancel_order(const QString& order_id) {
LOG_ERROR(TAG, QString("Paper cancel failed: %1 order_id=%2").arg(e.what(), order_id));
}
// Refresh paper data
- if (!account.paper_portfolio_id.isEmpty()) {
- try {
- auto portfolio = pt_get_portfolio(account.paper_portfolio_id);
- auto positions = pt_get_positions(account.paper_portfolio_id);
- auto orders = pt_get_orders(account.paper_portfolio_id);
- auto trades = pt_get_trades(account.paper_portfolio_id, 50);
- auto stats = pt_get_stats(account.paper_portfolio_id);
- order_entry_->set_balance(portfolio.balance);
- bottom_panel_->set_paper_positions(positions);
- bottom_panel_->set_paper_orders(orders);
- bottom_panel_->set_paper_trades(trades);
- bottom_panel_->set_paper_stats(stats);
- } catch (...) {}
- }
+ refresh_paper_panels();
} else {
const QString acct_id = focused_account_id_;
QPointer<EquityTradingScreen> self = this;
@@ -658,34 +660,88 @@ void EquityTradingScreen::refresh_paper_panels() {
// 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);
- auto orders = pt_get_orders(account.paper_portfolio_id);
- auto trades = pt_get_trades(account.paper_portfolio_id, 50);
- auto stats = pt_get_stats(account.paper_portfolio_id);
- order_entry_->set_balance(portfolio.balance);
- bottom_panel_->set_paper_positions(positions);
- bottom_panel_->set_paper_orders(orders);
- bottom_panel_->set_paper_trades(trades);
- bottom_panel_->set_paper_stats(stats);
- // Paper Funds tab: live set_funds is gated off in paper, so surface a
- // broker-equivalent funds view computed from the paper portfolio.
- // equity = free cash + open P&L; used margin = notional / leverage.
- double unrealized = 0.0, used_margin = 0.0;
+ const auto portfolio = pt_get_portfolio(account.paper_portfolio_id);
+ const auto positions = pt_get_positions(account.paper_portfolio_id);
+ const auto stats = pt_get_stats(account.paper_portfolio_id);
+ const QString sym = currency_symbol(portfolio.currency.isEmpty() ? QStringLiteral("INR") : portfolio.currency);
+
+ // Split exposure: CNC/delivery -> Holdings tab, MIS/NRML -> Positions tab.
+ QVector<trading::PtPosition> intraday;
+ QVector<trading::BrokerHolding> holdings;
+ double used_margin = 0.0, mis_unrealized = 0.0;
+ double holdings_value = 0.0, holdings_unreal = 0.0;
+ QStringList pos_syms;
for (const auto& p : positions) {
- unrealized += p.unrealized_pnl;
- const double lev = p.leverage > 0.0 ? p.leverage : 1.0;
- used_margin += (qAbs(p.quantity) * p.current_price) / lev;
+ pos_syms << p.symbol;
+ if (product_is_delivery(p.product)) {
+ trading::BrokerHolding h;
+ h.symbol = p.symbol;
+ h.quantity = p.quantity;
+ h.avg_price = p.entry_price;
+ h.ltp = p.current_price > 0.0 ? p.current_price : p.entry_price;
+ h.invested_value = p.entry_price * p.quantity;
+ h.current_value = h.ltp * p.quantity;
+ h.pnl = h.current_value - h.invested_value;
+ h.pnl_pct = h.invested_value > 0.0 ? (h.pnl / h.invested_value) * 100.0 : 0.0;
+ holdings.push_back(h);
+ holdings_value += h.current_value;
+ holdings_unreal += h.pnl;
+ } else {
+ intraday.push_back(p);
+ used_margin += p.held_margin;
+ mis_unrealized += p.unrealized_pnl;
+ }
}
- trading::BrokerFunds funds;
- funds.available_balance = portfolio.balance; // free cash
- funds.used_margin = used_margin; // locked in open positions
- funds.total_balance = portfolio.balance + unrealized; // equity
- bottom_panel_->set_funds(funds);
+ const double unrealized = mis_unrealized + holdings_unreal;
+
+ order_entry_->set_balance(portfolio.balance);
+ bottom_panel_->set_currency(sym); // before positions so the P&L summary formats in ₹
+ bottom_panel_->set_paper_positions(intraday);
+ bottom_panel_->set_holdings(holdings);
+
+ // Order book: the day shown by the date selector (default today, so each
+ // session starts empty). Keep the picker in sync with the viewed day.
+ bottom_panel_->set_orders_date(orders_view_day_);
+ bottom_panel_->set_paper_orders(pt_get_orders_for_day(account.paper_portfolio_id, orders_view_day_));
+
+ // ── Funds card view ──
+ EquityFundsView fv;
+ fv.is_paper = true;
+ fv.currency = sym;
+ fv.available = portfolio.balance;
+ fv.used_margin = used_margin;
+ fv.holdings_value = holdings_value;
+ fv.unrealized_pnl = unrealized;
+ fv.total_equity = portfolio.balance + used_margin + holdings_value + mis_unrealized;
+ fv.opening_balance = portfolio.initial_balance;
+ fv.realized_pnl = stats.today_pnl; // booked today
+ fv.collateral = 0.0;
+ const double margin_denom = used_margin + portfolio.balance;
+ fv.margin_util_pct = margin_denom > 0.0 ? (used_margin / margin_denom) * 100.0 : 0.0;
+ bottom_panel_->set_funds_view(fv);
+
+ // ── Stats card view ──
+ EquityStatsView sv;
+ sv.currency = sym;
+ sv.realized_pnl = stats.total_pnl; // all-time realized
+ sv.unrealized_pnl = unrealized;
+ sv.net_pnl = stats.total_pnl + unrealized;
+ sv.today_pnl = stats.today_pnl;
+ sv.return_pct = portfolio.initial_balance > 0.0 ? (sv.net_pnl / portfolio.initial_balance) * 100.0 : 0.0;
+ sv.win_rate = stats.win_rate;
+ sv.total_trades = stats.total_trades;
+ sv.winning_trades = stats.winning_trades;
+ sv.losing_trades = stats.losing_trades;
+ sv.profit_factor = stats.profit_factor;
+ sv.avg_win = stats.avg_win;
+ sv.avg_loss = stats.avg_loss;
+ sv.largest_win = stats.largest_win;
+ sv.largest_loss = stats.largest_loss;
+ sv.total_fees = stats.total_fees;
+ sv.turnover = stats.turnover;
+ bottom_panel_->set_stats_view(sv);
+
// Held symbols get live WebSocket prices even if not in the active list.
- QStringList pos_syms;
- for (const auto& p : positions)
- pos_syms << p.symbol;
update_position_symbols(pos_syms);
update_chart_position(); // refresh the on-chart position card
} catch (...) {
@@ -693,6 +749,155 @@ void EquityTradingScreen::refresh_paper_panels() {
}
}
+void EquityTradingScreen::on_convert_position(const QString& position_id, const QString& symbol,
+ const QString& new_product) {
+ if (focused_account_id_.isEmpty() || position_id.isEmpty())
+ return;
+ auto account = AccountManager::instance().get_account(focused_account_id_);
+ if (account.trading_mode != "paper" || account.paper_portfolio_id.isEmpty()) {
+ order_entry_->show_order_status(tr("Product conversion is available for paper accounts"), false);
+ return;
+ }
+ const auto reply = QMessageBox::question(
+ this, tr("Convert to %1").arg(new_product),
+ tr("Convert %1 to %2 (delivery)?\n\nThis locks the full position value as cash and carries it overnight "
+ "instead of auto-squaring at 15:30.")
+ .arg(symbol, new_product),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+ try {
+ pt_convert_position_product(position_id, new_product);
+ order_entry_->show_order_status(tr("%1 converted to %2").arg(symbol, new_product), true);
+ } catch (const std::exception& e) {
+ order_entry_->show_order_status(tr("Convert failed: %1").arg(e.what()), false);
+ }
+ refresh_paper_panels();
+}
+
+void EquityTradingScreen::on_orders_day_changed(const QDate& day) {
+ orders_view_day_ = day;
+ auto account = AccountManager::instance().get_account(focused_account_id_);
+ if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty())
+ bottom_panel_->set_paper_orders(pt_get_orders_for_day(account.paper_portfolio_id, day));
+}
+
+void EquityTradingScreen::on_square_off_group(const QString& account_id, int sign) {
+ if (account_id.isEmpty() || sign == 0)
+ return;
+ auto account = AccountManager::instance().get_account(account_id);
+
+ // Collect the matching positions (the panel already confirmed via dialog).
+ struct Target {
+ QString symbol;
+ QString exchange;
+ QString product;
+ };
+ QVector<Target> targets;
+ if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty()) {
+ for (const auto& p : pt_get_positions(account.paper_portfolio_id)) {
+ if (product_is_delivery(p.product))
+ continue; // CNC lives in Holdings — not squared by the positions buttons
+ if ((sign > 0 && p.unrealized_pnl > 0.0) || (sign < 0 && p.unrealized_pnl < 0.0))
+ targets.push_back({p.symbol, QString(), p.product});
+ }
+ } else {
+ for (const auto& p : live_positions_) {
+ if ((sign > 0 && p.pnl > 0.0) || (sign < 0 && p.pnl < 0.0))
+ targets.push_back({p.symbol, p.exchange, p.product_type});
+ }
+ }
+ if (targets.isEmpty()) {
+ order_entry_->show_order_status(
+ tr("No %1 positions to square off").arg(sign > 0 ? tr("winning") : tr("losing")), false);
+ return;
+ }
+
+ // Close each in a single background worker (sequential) to avoid a thread storm.
+ const QString acct_id = account_id;
+ QPointer<EquityTradingScreen> self = this;
+ (void)QtConcurrent::run([self, acct_id, targets]() {
+ if (!self)
+ return;
+ for (const auto& t : targets)
+ UnifiedTrading::instance().close_position(acct_id, t.symbol, t.exchange, t.product);
+ QMetaObject::invokeMethod(
+ self,
+ [self]() {
+ if (self)
+ self->refresh_paper_panels();
+ },
+ Qt::QueuedConnection);
+ });
+}
+
+void EquityTradingScreen::on_trade_symbol_requested(const QString& symbol, const QString& product, bool is_buy) {
+ // Exchange isn't carried on the row; default to the screen's current exchange.
+ open_order_ticket_for(symbol, QString(), product, is_buy);
+}
+
+void EquityTradingScreen::open_order_ticket_for(const QString& symbol, const QString& exchange,
+ const QString& product, bool is_buy) {
+ if (focused_account_id_.isEmpty()) {
+ order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
+ return;
+ }
+ const QString exch = exchange.isEmpty() ? selected_exchange_ : exchange;
+ const double ref_price = (symbol == selected_symbol_ && current_price_ > 0.0) ? current_price_ : 0.0;
+
+ QDialog dlg(this);
+ dlg.setWindowTitle(is_buy ? tr("Buy %1").arg(symbol) : tr("Sell %1").arg(symbol));
+ auto* form = new QFormLayout(&dlg);
+
+ auto* hdr = new QLabel(
+ QStringLiteral("%1 %2 · %3 · %4").arg(is_buy ? tr("BUY") : tr("SELL"), symbol, exch, product.toUpper()), &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);
+ 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(ref_price > 0.0 ? ref_price : 0.01);
+ form->addRow(tr("Limit price"), px_spin);
+
+ 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 = symbol;
+ order.exchange = exch;
+ 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 = product_from_broker_str(product);
+ order.validity = QStringLiteral("DAY");
+ on_order_submitted(order);
+}
+
void EquityTradingScreen::on_chart_exit_position(const QString& symbol, const QString& exchange,
const QString& product_type, const QString& side,
double qty) {
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
index 3ba54868c..1c9ba3504 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
@@ -111,12 +111,28 @@ void EquityTradingScreen::hub_subscribe_streaming() {
});
// ── Balance / Funds ──
+ // Resolve the broker's currency symbol once (₹/$/…) for the funds cards.
+ const QString ccy_sym = [&]() {
+ if (auto* b = BrokerRegistry::instance().get(bid))
+ return currency_symbol(b->profile().currency);
+ return QStringLiteral("$");
+ }();
+ bottom_panel_->set_currency(ccy_sym); // so the positions P&L summary formats correctly
hub.subscribe(this, broker_topic(bid, aid, QStringLiteral("balance")),
- [this](const QVariant& v) {
+ [this, ccy_sym](const QVariant& v) {
if (!v.canConvert<BrokerFunds>())
return;
const auto funds = v.value<BrokerFunds>();
- bottom_panel_->set_funds(funds);
+ EquityFundsView fv;
+ fv.is_paper = false;
+ fv.currency = ccy_sym;
+ fv.available = funds.available_balance;
+ fv.used_margin = funds.used_margin;
+ fv.total_equity = funds.total_balance;
+ fv.collateral = funds.collateral;
+ const double denom = funds.used_margin + funds.available_balance;
+ fv.margin_util_pct = denom > 0.0 ? (funds.used_margin / denom) * 100.0 : 0.0;
+ bottom_panel_->set_funds_view(fv);
order_entry_->set_balance(funds.available_balance);
});
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityTypes.h b/fincept-qt/src/screens/equity_trading/EquityTypes.h
index 2b927f771..c92bc4912 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTypes.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTypes.h
@@ -138,4 +138,45 @@ inline QString currency_symbol(const QString& currency) {
return "$";
}
+// \u2500\u2500 Funds / Stats view-models \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
+// The bottom-panel Funds and Stats tabs render from these view-models, so the
+// panel is decoupled from the data source: live mode fills them from BrokerFunds
+// (the subset it knows), paper mode fills the full set from the paper engine.
+
+struct EquityFundsView {
+ QString currency = QStringLiteral("\u20B9"); // symbol, e.g. \u20B9 / $
+ bool is_paper = false;
+
+ double available = 0.0; // free cash / available margin
+ double used_margin = 0.0; // locked by open intraday positions + pending orders
+ double total_equity = 0.0; // net worth = available + used + holdings + open P&L
+ double opening_balance = 0.0; // initial / start-of-day balance
+ double holdings_value = 0.0; // current value of CNC delivery holdings
+ double realized_pnl = 0.0; // realized P&L (today)
+ double unrealized_pnl = 0.0; // open positions + holdings mark-to-market
+ double collateral = 0.0; // pledged collateral (live brokers)
+ double margin_util_pct = 0.0; // used / (used + available) * 100
+};
+
+struct EquityStatsView {
+ QString currency = QStringLiteral("\u20B9");
+
+ double net_pnl = 0.0; // realized + unrealized
+ double today_pnl = 0.0; // realized today
+ double realized_pnl = 0.0;
+ double unrealized_pnl = 0.0;
+ double return_pct = 0.0; // net_pnl / opening_balance * 100
+ double win_rate = 0.0; // 0..1
+ long long total_trades = 0;
+ long long winning_trades = 0;
+ long long losing_trades = 0;
+ double profit_factor = 0.0;
+ double avg_win = 0.0;
+ double avg_loss = 0.0;
+ double largest_win = 0.0;
+ double largest_loss = 0.0;
+ double total_fees = 0.0;
+ double turnover = 0.0;
+};
+
} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
index c80a5d87b..44b82245d 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
@@ -4,6 +4,7 @@
#include "screens/equity_trading/EquityTypes.h"
#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
+#include "trading/instruments/InstrumentNormalize.h"
#include "trading/instruments/InstrumentService.h"
#include "ui/theme/Theme.h"
@@ -37,12 +38,6 @@ QStringList connected_broker_ids(const QString& active) {
return ids;
}
-// Human-readable broker name for the suggestion tag.
-QString broker_display(const QString& broker_id) {
- auto* b = trading::BrokerRegistry::instance().get(broker_id);
- return b ? b->profile().display_name : broker_id;
-}
-
// True if at least one of the connected brokers has its instrument catalog loaded.
bool any_loaded(const QStringList& ids) {
for (const QString& id : ids)
@@ -78,7 +73,7 @@ EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
wl_menu_btn_ = new QToolButton;
wl_menu_btn_->setObjectName("eqWatchlistMenuBtn");
- wl_menu_btn_->setText(QStringLiteral("⋯"));
+ wl_menu_btn_->setText(QStringLiteral("+"));
wl_menu_btn_->setCursor(Qt::PointingHandCursor);
wl_menu_btn_->setAutoRaise(true);
wl_menu_btn_->setToolTip(tr("New / Rename / Delete watchlist"));
@@ -152,16 +147,37 @@ EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
// 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).
+ // Resolve a picked label back to the real symbol: friendly-name map first
+ // (clean F&O label), else the legacy "SYMBOL · EXCH" / "EXCH:SYMBOL" parse.
+ auto resolve = [this](const QString& choice) -> QString {
+ QString sym = add_suggestion_map_.value(choice);
+ if (sym.isEmpty()) {
+ sym = choice.section(QStringLiteral(" · "), 0, 0).trimmed().toUpper();
+ if (sym.contains(':'))
+ sym = sym.section(':', 1);
+ }
+ return sym;
+ };
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();
- });
+ [this, resolve](const QString& choice) {
+ const QString sym = resolve(choice);
+ if (sym.isEmpty())
+ return;
+ add_symbol(sym);
+ add_edit_->clear();
+ });
+ // A single mouse-click on a suggestion must add it — QCompleter::activated is
+ // unreliable on click for a per-keystroke model, so wire the popup's clicked()
+ // directly. add_symbol() dedups, so the two paths can never double-add.
+ if (auto* popup = completer_->popup()) {
+ connect(popup, &QAbstractItemView::clicked, this, [this, resolve](const QModelIndex& idx) {
+ const QString sym = resolve(idx.data(Qt::DisplayRole).toString());
+ if (sym.isEmpty())
+ return;
+ add_symbol(sym);
+ add_edit_->clear();
+ });
+ }
add_btn_ = new QPushButton("+");
add_btn_->setObjectName("eqWatchlistAddBtn");
@@ -450,15 +466,18 @@ void EquityWatchlist::add_symbol(const QString& symbol) {
}
void EquityWatchlist::on_add_symbol_entered() {
- const QString raw = add_edit_->text().trimmed().toUpper();
+ const QString raw = add_edit_->text().trimmed();
if (raw.isEmpty())
return;
- // The completer suggestion is "SYMBOL · EXCH · Broker" — keep only the
- // leading symbol token. Also tolerate the legacy "EXCHANGE:SYMBOL" form.
- QString sym = raw.section(QStringLiteral(" · "), 0, 0).trimmed();
- if (sym.contains(':'))
- sym = sym.section(':', 1);
+ // A picked friendly label resolves to the real symbol via the map; otherwise
+ // treat the text as typed input (legacy "SYMBOL · EXCH" / "EXCH:SYMBOL").
+ QString sym = add_suggestion_map_.value(raw);
+ if (sym.isEmpty()) {
+ sym = raw.toUpper().section(QStringLiteral(" · "), 0, 0).trimmed();
+ if (sym.contains(':'))
+ sym = sym.section(':', 1);
+ }
// Validate against every connected broker (not just the focused one) so a
// symbol that only one connected broker carries is still accepted.
@@ -495,9 +514,16 @@ void EquityWatchlist::on_add_text_changed(const QString& text) {
auto results = trading::InstrumentService::instance().search_all(query, "", ids, 24);
QStringList suggestions;
suggestions.reserve(results.size());
+ add_suggestion_map_.clear();
for (const auto& inst : results) {
- suggestions.append(
- QString("%1 · %2 · %3").arg(inst.symbol, inst.exchange, broker_display(inst.broker_id)));
+ // Clean F&O label instead of the raw symbol; remember the real symbol.
+ const QString friendly =
+ trading::norm::display_name(inst.name, inst.instrument_type, inst.expiry, inst.strike, inst.symbol);
+ const QString label = QStringLiteral("%1 · %2").arg(friendly, inst.exchange);
+ if (add_suggestion_map_.contains(label))
+ continue; // collapse identical labels across brokers
+ add_suggestion_map_.insert(label, inst.symbol);
+ suggestions.append(label);
}
completer_model_->setStringList(suggestions);
// Force the popup to refresh against the just-updated model (otherwise the
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.h b/fincept-qt/src/screens/equity_trading/EquityWatchlist.h
index 11b59c966..0d4b37d1a 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.h
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.h
@@ -6,6 +6,7 @@
#include <QComboBox>
#include <QCompleter>
#include <QEvent>
+#include <QHash>
#include <QLabel>
#include <QLineEdit>
#include <QMutex>
@@ -76,6 +77,8 @@ class EquityWatchlist : public QWidget {
QPushButton* add_btn_ = nullptr;
QStringListModel* completer_model_ = nullptr;
QCompleter* completer_ = nullptr;
+ // Friendly picker label → canonical symbol (F&O clean names in the add box).
+ QHash<QString, QString> add_suggestion_map_;
QLabel* title_label_ = nullptr;
QLabel* count_label_ = nullptr;
QTableWidget* table_ = nullptr;
diff --git a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
index d336215f9..a1ca12805 100644
--- a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.cpp
@@ -5,6 +5,7 @@
#include "ui/theme/Theme.h"
#include "ui/widgets/WorldMapWidget.h"
+#include <QComboBox>
#include <QDesktopServices>
#include <QGridLayout>
#include <QHBoxLayout>
@@ -34,9 +35,77 @@ void ConflictMonitorPanel::build_ui() {
left_splitter->setStyleSheet(QString("QSplitter::handle { background:%1; }").arg(ui::colors::BORDER_DIM()));
// ── World Map ───────────────────────────────────────────────────────────
- map_widget_ = new fincept::ui::WorldMapWidget(left_splitter);
+ // Wrap the map in a container with a slim toolbar carrying the BASEMAP
+ // selector, then add the container (not the bare map) to the splitter.
+ auto* map_container = new QWidget(left_splitter);
+ auto* mc_vl = new QVBoxLayout(map_container);
+ mc_vl->setContentsMargins(0, 0, 0, 0);
+ mc_vl->setSpacing(0);
+
+ auto* map_toolbar = new QWidget(map_container);
+ map_toolbar->setObjectName("gpMapToolbar");
+ map_toolbar->setFixedHeight(32);
+ map_toolbar->setStyleSheet(QString("#gpMapToolbar { background:%1; border-bottom:1px solid %2; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_MED()));
+ auto* mt_hl = new QHBoxLayout(map_toolbar);
+ mt_hl->setContentsMargins(10, 0, 10, 0);
+ mt_hl->setSpacing(8);
+
+ auto* map_accent = new QLabel(map_toolbar);
+ map_accent->setFixedSize(3, 12);
+ map_accent->setStyleSheet(QString("background:%1; border-radius:1px;").arg(ui::colors::AMBER()));
+ mt_hl->addWidget(map_accent);
+
+ auto* map_title = new QLabel(tr("CONFLICT MAP"), map_toolbar);
+ map_title->setStyleSheet(QString("color:%1; font-size:11px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::AMBER())
+ .arg(ui::fonts::DATA_FAMILY));
+ mt_hl->addWidget(map_title);
+ mt_hl->addStretch();
+
+ auto* basemap_cap = new QLabel(tr("BASEMAP"), map_toolbar);
+ basemap_cap->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_TERTIARY())
+ .arg(ui::fonts::DATA_FAMILY));
+ mt_hl->addWidget(basemap_cap);
+
+ map_type_combo_ = new QComboBox(map_toolbar);
+ map_type_combo_->setCursor(Qt::PointingHandCursor);
+ map_type_combo_->setFixedWidth(132);
+ map_type_combo_->setStyleSheet(
+ QString("QComboBox { background:%1; color:%2; border:1px solid %3; border-radius:2px;"
+ "font-family:%6; font-size:%7px; font-weight:700; padding:3px 8px; }"
+ "QComboBox:hover, QComboBox:focus { border-color:%4; }"
+ "QComboBox::drop-down { border:none; width:16px; }"
+ "QComboBox::down-arrow { image:none; width:0; height:0;"
+ "border-left:3px solid transparent; border-right:3px solid transparent;"
+ "border-top:4px solid %4; margin-right:6px; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2; border:1px solid %3;"
+ "selection-background-color:%5; selection-color:%4; outline:0;"
+ "font-family:%6; font-size:%7px; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(),
+ ui::colors::AMBER(), ui::colors::BG_HOVER())
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::fonts::SMALL));
+ mt_hl->addWidget(map_type_combo_);
+
+ mc_vl->addWidget(map_toolbar);
+
+ map_widget_ = new fincept::ui::WorldMapWidget(map_container);
map_widget_->setMinimumHeight(280);
- left_splitter->addWidget(map_widget_);
+ mc_vl->addWidget(map_widget_, 1);
+
+ left_splitter->addWidget(map_container);
+
+ // Default geopolitics to the DARK political basemap (index 1) — preserves
+ // the screen's prior look; the selector lets the user pick satellite, etc.
+ map_type_combo_->addItems(fincept::ui::WorldMapWidget::basemap_labels());
+ map_type_combo_->setCurrentIndex(1); // 1 = DARK in basemap_labels()
+ map_widget_->set_basemap(1);
+ connect(map_type_combo_, &QComboBox::currentIndexChanged, this, [this](int idx) {
+ if (map_widget_)
+ map_widget_->set_basemap(idx);
+ });
// Map pin click → select the matching row in the events table. The row's
// currentCellChanged handler (wired below) then fills the detail panel,
diff --git a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.h b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.h
index 586c8c242..3ea7eaa9d 100644
--- a/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.h
+++ b/fincept-qt/src/screens/geopolitics/ConflictMonitorPanel.h
@@ -2,6 +2,7 @@
#pragma once
#include "services/geopolitics/GeopoliticsTypes.h"
+#include <QComboBox>
#include <QEvent>
#include <QLabel>
#include <QPushButton>
@@ -44,6 +45,7 @@ class ConflictMonitorPanel : public QWidget {
// Map
fincept::ui::WorldMapWidget* map_widget_ = nullptr;
+ QComboBox* map_type_combo_ = nullptr; // basemap selector in the map toolbar
QTableWidget* events_table_ = nullptr;
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp
index 47189d245..2513affa8 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp
@@ -42,17 +42,10 @@ MaritimeScreen::MaritimeScreen(QWidget* parent) : QWidget(parent) {
refresh_timer_ = new QTimer(this);
refresh_timer_->setInterval(5 * 60 * 1000); // 5 min
- // Auto-refresh re-issues whichever mode produced the most recent set: a
- // bbox load if the user had typed one, otherwise the global sample. This
- // avoids a no-op refresh after a first-show global view (the bbox
- // spinners stay at zero in that case).
- connect(refresh_timer_, &QTimer::timeout, this, [this]() {
- const bool valid_bbox = area_min_lat_ && area_max_lat_ && area_min_lng_ && area_max_lng_
- && area_max_lat_->value() > area_min_lat_->value()
- && area_max_lng_->value() > area_min_lng_->value();
- if (valid_bbox) on_load_vessels();
- else load_global_sample();
- });
+ // Auto-refresh is opt-in (the AUTO toggle in the map toolbar), so it never
+ // silently burns API credits. The timer and the manual button share
+ // do_refresh().
+ connect(refresh_timer_, &QTimer::timeout, this, &MaritimeScreen::do_refresh);
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { apply_theme(); });
@@ -62,7 +55,9 @@ MaritimeScreen::MaritimeScreen(QWidget* parent) : QWidget(parent) {
void MaritimeScreen::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
- refresh_timer_->start();
+ // Only resume auto-refresh if the user had it enabled (off by default).
+ if (auto_refresh_btn_ && auto_refresh_btn_->isChecked())
+ refresh_timer_->start();
if (first_show_) {
first_show_ = false;
// Default first-show action: globally-spread sample so the map looks
@@ -120,28 +115,28 @@ void MaritimeScreen::apply_theme() {
brand_label_->setStyleSheet(
QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:2px;")
.arg(ui::colors::AMBER())
- .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA)
.arg(ui::fonts::DATA_FAMILY));
if (classified_label_)
- classified_label_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2; letter-spacing:1px;")
- .arg(ui::colors::TEXT_TERTIARY())
+ classified_label_->setStyleSheet(QString("color:%1; font-size:11px; font-family:%2; letter-spacing:1px;")
+ .arg(ui::colors::TEXT_SECONDARY())
.arg(ui::fonts::DATA_FAMILY));
if (credits_label_)
credits_label_->setStyleSheet(
- QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
- "padding:3px 10px; background:%3; border:1px solid %4; border-radius:2px;")
- .arg(ui::colors::TEXT_TERTIARY())
+ QString("color:%1; font-size:11px; font-weight:700; font-family:%2;"
+ "padding:4px 10px; background:%3; border:1px solid %4; border-radius:2px;")
+ .arg(ui::colors::TEXT_SECONDARY())
.arg(ui::fonts::DATA_FAMILY)
.arg(ui::colors::BG_SURFACE())
.arg(ui::colors::BORDER_MED()));
if (vessel_count_label_)
vessel_count_label_->setStyleSheet(
- QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
- "padding:3px 10px; background:%3; border:1px solid %4; border-radius:2px;")
- .arg(ui::colors::INFO())
+ QString("color:%1; font-size:11px; font-weight:700; font-family:%2;"
+ "padding:4px 10px; background:%3; border:1px solid %4; border-radius:2px;")
+ .arg(ui::colors::AMBER())
.arg(ui::fonts::DATA_FAMILY)
.arg(ui::colors::BG_SURFACE())
.arg(ui::colors::BORDER_MED()));
@@ -166,17 +161,39 @@ void MaritimeScreen::apply_theme() {
if (status_label_)
set_status(tr("READY"), ui::colors::POSITIVE);
+ // Both cards scope their border to the container objectName so the border
+ // doesn't cascade onto every child label (which made each row look boxed).
if (route_detail_)
route_detail_->setStyleSheet(
- QString("background:%1; border:1px solid %2; border-left:3px solid %2; border-radius:2px;")
+ QString("#mtRouteCard { background:%1; border:1px solid %2; border-left:3px solid %2;"
+ " border-radius:2px; }")
.arg(C(ui::colors::BG_SURFACE), C(ui::colors::AMBER)));
if (search_result_card_)
- search_result_card_->setStyleSheet(QString("background:%1; border:1px solid %2; border-radius:2px;")
- .arg(C(ui::colors::BG_SURFACE), C(ui::colors::INFO)));
+ search_result_card_->setStyleSheet(
+ QString("#mtSearchCard { background:%1; border:1px solid %2; border-left:3px solid %2;"
+ " border-radius:2px; }")
+ .arg(C(ui::colors::BG_SURFACE), C(ui::colors::AMBER)));
if (imo_edit_)
imo_edit_->setStyleSheet(input_ss());
+
+ if (basemap_cap_)
+ basemap_cap_->setStyleSheet(tiny_label_ss());
+ if (map_type_combo_)
+ map_type_combo_->setStyleSheet(combo_ss());
+}
+
+void MaritimeScreen::do_refresh() {
+ // Re-issue whichever mode produced the most recent set: a bbox load if the
+ // user had typed/selected one, otherwise the global sample.
+ const bool valid_bbox = area_min_lat_ && area_max_lat_ && area_min_lng_ && area_max_lng_
+ && area_max_lat_->value() > area_min_lat_->value()
+ && area_max_lng_->value() > area_min_lng_->value();
+ if (valid_bbox)
+ on_load_vessels();
+ else
+ load_global_sample();
}
void MaritimeScreen::changeEvent(QEvent* event) {
@@ -201,16 +218,19 @@ void MaritimeScreen::retranslateUi() {
if (sq_btn_) sq_btn_->setText(tr("◻ SQUARE"));
if (ci_btn_) ci_btn_->setText(tr("◯ CIRCLE"));
if (clr_btn_) clr_btn_->setText(tr("✕ CLEAR"));
- if (intel_title_) intel_title_->setText(tr("INTELLIGENCE"));
- if (stat_vessels_cap_) stat_vessels_cap_->setText(tr("TOTAL IN AREA"));
- if (stat_displayed_cap_) stat_displayed_cap_->setText(tr("DISPLAYED"));
+ if (intel_title_) intel_title_->setText(tr("FLEET INTELLIGENCE"));
+ if (stat_vessels_cap_) stat_vessels_cap_->setText(tr("LOADED"));
+ if (stat_displayed_cap_) stat_displayed_cap_->setText(tr("IN REGION"));
+ if (stat_moving_cap_) stat_moving_cap_->setText(tr("MOVING"));
+ if (stat_speed_cap_) stat_speed_cap_->setText(tr("AVG SPEED"));
if (stat_routes_cap_) stat_routes_cap_->setText(tr("ROUTES"));
- if (stat_ports_cap_) stat_ports_cap_->setText(tr("PORTS"));
+ if (stat_ports_cap_) stat_ports_cap_->setText(tr("DEST PORTS"));
if (routes_title_) routes_title_->setText(tr("TRADE CORRIDORS"));
if (routes_table_) routes_table_->setHorizontalHeaderLabels({tr("Route"), tr("Vessels"), tr("Status")});
// Center
- if (center_title_) center_title_->setText(tr("VESSEL TRACKING"));
+ if (center_title_) center_title_->setText(tr("LIVE VESSEL MAP"));
+ if (basemap_cap_) basemap_cap_->setText(tr("BASEMAP"));
if (vessels_table_)
vessels_table_->setHorizontalHeaderLabels(
{tr("Name"), tr("IMO"), tr("Lat"), tr("Lng"), tr("Speed (kn)"), tr("Angle"),
@@ -247,8 +267,8 @@ void MaritimeScreen::retranslateUi() {
// Status bar
if (sb_source_cap_) sb_source_cap_->setText(tr("SOURCE:"));
if (sb_records_cap_) sb_records_cap_->setText(tr("RECORDS:"));
- if (sb_refresh_cap_) sb_refresh_cap_->setText(tr("REFRESH:"));
- if (sb_refresh_val_) sb_refresh_val_->setText(tr("5 MIN"));
+ if (sb_refresh_cap_) sb_refresh_cap_->setText(tr("UPDATED:"));
+ // sb_refresh_val_ holds the live last-update clock — don't reset it here.
// status_label_ reflects the last operation; re-apply the idle READY label.
if (status_label_) set_status(tr("READY"), ui::colors::POSITIVE);
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.h b/fincept-qt/src/screens/maritime/MaritimeScreen.h
index fe8e436fe..d42ef58bb 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen.h
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.h
@@ -6,14 +6,18 @@
#include "services/maritime/MaritimeTypes.h"
#include "ui/theme/Theme.h"
+#include <QComboBox>
+#include <QCompleter>
#include <QDoubleSpinBox>
#include <QEvent>
+#include <QHash>
#include <QHideEvent>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QShowEvent>
+#include <QStringListModel>
#include <QTableWidget>
#include <QTimer>
#include <QVBoxLayout>
@@ -71,10 +75,13 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {
void connect_service();
void rebuild_routes_from_vessels(const QVector<services::maritime::VesselData>& vessels);
void populate_routes_table();
- void update_intelligence(int vessel_count);
+ void update_intelligence(int region_total, int loaded);
void update_credits(int remaining);
void update_map(const QVector<services::maritime::VesselData>& vessels);
void apply_theme();
+ /// Re-issue the most recent load (bbox if one is set, else global sample).
+ /// Shared by the manual refresh button and the auto-refresh timer.
+ void do_refresh();
void set_status(const QString& text, const ui::ColorToken& color);
/// Issue a world-bbox search and flag the result for spatial downsampling
/// so the map fans out instead of clustering on whatever bbox the user
@@ -106,14 +113,18 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {
QWidget* right_panel_ = nullptr;
QWidget* status_bar_ = nullptr;
- // Left panel
- QLabel* stat_vessels_ = nullptr;
- QLabel* stat_displayed_ = nullptr;
+ // Left panel — fleet stats (all computed from the loaded vessel set).
+ QLabel* stat_vessels_ = nullptr; // LOADED — vessels rendered on the map
+ QLabel* stat_displayed_ = nullptr; // IN REGION — server-reported area total
+ QLabel* stat_moving_ = nullptr; // MOVING — speed > 0.5 kn
+ QLabel* stat_speed_ = nullptr; // AVG SPEED — mean speed of moving vessels
QLabel* stat_routes_ = nullptr;
QLabel* stat_ports_ = nullptr;
// Center
fincept::ui::WorldMapWidget* map_widget_ = nullptr;
+ QPushButton* refresh_btn_ = nullptr; // manual refresh
+ QPushButton* auto_refresh_btn_ = nullptr; // AUTO-refresh toggle (off by default)
fincept::ui::LoadingOverlay* map_loader_ = nullptr;
QTableWidget* vessels_table_ = nullptr;
QTableWidget* routes_table_ = nullptr;
@@ -136,6 +147,10 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {
QTableWidget* place_table_ = nullptr;
QLabel* place_status_ = nullptr;
QVector<services::maritime::GeoPlace> place_results_;
+ // Live typeahead: debounced geocoder search feeds a completer popup.
+ QCompleter* place_completer_ = nullptr;
+ QStringListModel* place_completer_model_ = nullptr;
+ QTimer* place_debounce_ = nullptr;
// Right panel - area search (raw lat/long). Kept behind an "Advanced"
// expander; place search / map-draw are the primary inputs now.
@@ -150,6 +165,13 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {
QTableWidget* ports_table_ = nullptr;
QLabel* ports_status_ = nullptr;
QVector<services::maritime::PortRecord> port_results_;
+ QCompleter* ports_completer_ = nullptr;
+ QStringListModel* ports_completer_model_ = nullptr;
+ QTimer* ports_debounce_ = nullptr;
+ // Voyage endpoint port resolution: maps the expected PortsCatalog context
+ // ("name:<port>") to the pin label to plot when its results arrive, so
+ // these lookups don't leak into the user-facing ports table.
+ QHash<QString, QString> voyage_port_ctx_;
// Route detail
QWidget* route_detail_ = nullptr;
@@ -186,10 +208,14 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {
QLabel* routes_title_ = nullptr;
QLabel* stat_vessels_cap_ = nullptr;
QLabel* stat_displayed_cap_ = nullptr;
+ QLabel* stat_moving_cap_ = nullptr;
+ QLabel* stat_speed_cap_ = nullptr;
QLabel* stat_routes_cap_ = nullptr;
QLabel* stat_ports_cap_ = nullptr;
// Center.
QLabel* center_title_ = nullptr;
+ QLabel* basemap_cap_ = nullptr; // "BASEMAP" caption in the map toolbar
+ QComboBox* map_type_combo_ = nullptr; // basemap selector
// Right panel buttons + titles + field captions.
QLabel* search_title_ = nullptr;
QLabel* imo_cap_ = nullptr;
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp
index ec18740b0..ce120e104 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp
@@ -30,6 +30,7 @@
#include <QSet>
#include <QSplitter>
#include <QTabWidget>
+#include <QTime>
namespace fincept::screens {
@@ -52,7 +53,7 @@ void MaritimeScreen::load_global_sample() {
// a geographically diverse pool to spread across — the API returns busy
// lanes first, so a tight server cap would cluster. ~22x less than 45k.
params.limit = 2000;
- set_status(tr("LOADING GLOBAL..."), ui::colors::WARNING);
+ set_status(tr("LOADING GLOBAL..."), ui::colors::AMBER);
pending_global_sample_ = true;
filter_to_shapes_ = false; // global view is never shape-filtered
show_map_loading(tr("LOADING GLOBAL VESSELS"));
@@ -69,7 +70,7 @@ void MaritimeScreen::on_load_vessels() {
void MaritimeScreen::run_area_search(double min_lat, double max_lat, double min_lng, double max_lng,
bool filter_to_shapes) {
if (max_lat <= min_lat || max_lng <= min_lng) {
- set_status(tr("INVALID BBOX"), ui::colors::WARNING);
+ set_status(tr("INVALID BBOX"), ui::colors::AMBER);
return;
}
// Filter the next result to drawn shapes only when this search was driven
@@ -90,7 +91,7 @@ void MaritimeScreen::run_area_search(double min_lat, double max_lat, double min_
// Cap the working set like the global view does — a large place bbox
// (e.g. an ocean) can still match thousands of vessels.
params.limit = 2000;
- set_status(tr("SEARCHING..."), ui::colors::WARNING);
+ set_status(tr("SEARCHING..."), ui::colors::AMBER);
pending_global_sample_ = false;
show_map_loading(tr("SEARCHING AREA"));
MaritimeService::instance().search_vessels_by_area(params);
@@ -116,6 +117,17 @@ void MaritimeScreen::on_places_found(QVector<services::maritime::GeoPlace> place
place_table_->setSortingEnabled(true);
place_table_->resizeColumnsToContents();
+ // Feed the typeahead completer and pop it open while the user is typing.
+ if (place_completer_model_) {
+ QStringList names;
+ names.reserve(places.size());
+ for (const auto& p : places)
+ names << p.display_name;
+ place_completer_model_->setStringList(names);
+ if (!names.isEmpty() && place_query_edit_ && place_query_edit_->hasFocus())
+ place_completer_->complete();
+ }
+
if (place_status_) {
if (places.isEmpty())
place_status_->setText(tr("No places found."));
@@ -158,13 +170,18 @@ void MaritimeScreen::on_search_vessel() {
return;
search_result_card_->setVisible(false);
search_result_label_->setVisible(false);
- set_status(tr("TRACKING..."), ui::colors::WARNING);
+ set_status(tr("TRACKING..."), ui::colors::AMBER);
show_map_loading(tr("TRACKING VESSEL"));
MaritimeService::instance().get_vessel_position(imo);
}
void MaritimeScreen::on_vessels_loaded(VesselsPage page) {
hide_map_loading();
+ // Server-reported total for the searched area, captured before any
+ // downsampling/shape-filter overwrites page.total_count. This drives the
+ // "IN REGION" stat — kept distinct from the LOADED count so the two never
+ // get conflated (the old UI showed this 5.2K figure as the vessel count).
+ const int region_total = page.total_count;
// Spread mode — globally-sampled fetch was triggered. Bin the returned
// vessels into a 10x10 lat/lng grid and pick up to 2 per cell so the
// map gets coverage instead of a dense regional cluster (the API tends
@@ -173,7 +190,7 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {
pending_global_sample_ = false;
constexpr int kBins = 10;
constexpr int kPerCell = 2;
- constexpr int kTargetCount = 100;
+ constexpr int kTargetCount = 200;
QHash<int, QVector<int>> by_cell; // cell index → vessel indices
for (int i = 0; i < page.vessels.size(); ++i) {
const auto& v = page.vessels[i];
@@ -218,8 +235,8 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {
// Render limit — area-search can still return a large set for a tight
// user bbox. Pin/render the top (newest-first) batch to keep the UI
- // responsive; full count still shown in the status badge.
- static constexpr int kRenderLimit = 100;
+ // responsive; the server's region total is shown separately (IN REGION).
+ static constexpr int kRenderLimit = 200;
const int render_n = qMin(page.vessels.size(), kRenderLimit);
vessels_table_->setSortingEnabled(false);
@@ -229,7 +246,7 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {
const auto& v = page.vessels[i];
auto* name_item = new QTableWidgetItem(v.name);
- name_item->setForeground(QBrush(QColor(ui::colors::INFO.get())));
+ name_item->setForeground(QBrush(QColor(ui::colors::TEXT_PRIMARY.get())));
vessels_table_->setItem(i, 0, name_item);
vessels_table_->setItem(i, 1, new QTableWidgetItem(v.imo));
@@ -270,14 +287,21 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {
}
}
- update_intelligence(page.total_count);
update_credits(page.remaining_credits);
- update_map(page.vessels.mid(0, kRenderLimit));
+ // Routes first so the ROUTES stat reflects this load (not the previous one).
rebuild_routes_from_vessels(page.vessels);
populate_routes_table();
+ // update_map populates rendered_vessels_ + the moving/speed/ports stats;
+ // run it before update_intelligence so LOADED = actual pins on the map.
+ update_map(page.vessels.mid(0, kRenderLimit));
+ update_intelligence(region_total, rendered_vessels_.size());
+
+ // Real "UPDATED:" clock in the status bar — every successful load stamps it.
+ if (sb_refresh_val_)
+ sb_refresh_val_->setText(QTime::currentTime().toString(QStringLiteral("HH:mm:ss")));
if (page.vessels.size() > kRenderLimit)
- set_status(tr("READY (showing %1 of %2)").arg(render_n).arg(page.vessels.size()), ui::colors::WARNING);
+ set_status(tr("READY (showing %1 of %2)").arg(render_n).arg(page.vessels.size()), ui::colors::AMBER);
else
set_status(tr("READY"), ui::colors::POSITIVE);
}
@@ -292,6 +316,21 @@ void MaritimeScreen::on_vessel_found(VesselData vessel) {
sr_speed_->setText(tr("Speed: %1 kn").arg(vessel.speed, 0, 'f', 1));
sr_from_->setText(tr("From: %1").arg(vessel.from_port.isEmpty() ? QStringLiteral("—") : vessel.from_port));
sr_to_->setText(tr("To: %1").arg(vessel.to_port.isEmpty() ? QStringLiteral("—") : vessel.to_port));
+
+ // Focus the map on the tracked vessel: drop a single amber pin and zoom in
+ // on its current position so TRACK actually takes the user there.
+ if (map_widget_ && (vessel.latitude != 0.0 || vessel.longitude != 0.0)) {
+ fincept::ui::MapPin pin;
+ pin.latitude = vessel.latitude;
+ pin.longitude = vessel.longitude;
+ pin.label = QString("%1 (%2)").arg(vessel.name, vessel.imo);
+ pin.color = QColor(ui::colors::AMBER.get());
+ pin.radius = 8.0;
+ pin.id = -1;
+ rendered_vessels_.clear(); // single-vessel focus; no fleet to click
+ map_widget_->set_pins({pin}); // also clears any old voyage path
+ map_widget_->fly_to(vessel.latitude, vessel.longitude);
+ }
set_status(tr("READY"), ui::colors::POSITIVE);
}
@@ -308,7 +347,25 @@ void MaritimeScreen::on_error(const QString& context, const QString& message) {
}
void MaritimeScreen::on_ports_found(QVector<services::maritime::PortRecord> ports, QString context) {
- Q_UNUSED(context);
+ // Voyage origin/destination lookup → plot a labeled port pin instead of
+ // populating the user-facing ports table.
+ if (voyage_port_ctx_.contains(context)) {
+ const QString label = voyage_port_ctx_.take(context);
+ if (!ports.isEmpty() && map_widget_) {
+ const auto& p = ports.first(); // best match for the searched name
+ fincept::ui::MapPin pin;
+ pin.latitude = p.latitude;
+ pin.longitude = p.longitude;
+ pin.label = p.country.isEmpty() ? label : QString("%1 — %2").arg(label, p.country);
+ // White marker — distinct from the green vessels and the amber trail.
+ pin.color = QColor(ui::colors::TEXT_PRIMARY.get());
+ pin.radius = 9.0;
+ pin.id = -1;
+ map_widget_->add_pin(pin);
+ }
+ return;
+ }
+
port_results_ = ports;
if (!ports_table_) return;
@@ -328,6 +385,16 @@ void MaritimeScreen::on_ports_found(QVector<services::maritime::PortRecord> port
ports_table_->setSortingEnabled(true);
ports_table_->resizeColumnsToContents();
+ if (ports_completer_model_) {
+ QStringList names;
+ names.reserve(ports.size());
+ for (const auto& p : ports)
+ names << p.name;
+ ports_completer_model_->setStringList(names);
+ if (!names.isEmpty() && ports_query_edit_ && ports_query_edit_->hasFocus())
+ ports_completer_->complete();
+ }
+
if (ports_status_) {
if (ports.isEmpty())
ports_status_->setText(tr("No ports found."));
@@ -354,9 +421,9 @@ void MaritimeScreen::on_health_loaded(QJsonObject payload) {
const QString label = module.isEmpty() ? tr("FINCEPT MARINE API") : module.toUpper();
const QString color = status == QStringLiteral("healthy")
? ui::colors::POSITIVE()
- : ui::colors::WARNING();
+ : ui::colors::AMBER();
source_value_->setText(label);
- source_value_->setStyleSheet(QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
+ source_value_->setStyleSheet(QString("color:%1; font-size:10px; font-weight:700; font-family:%2;")
.arg(color)
.arg(ui::fonts::DATA_FAMILY));
}
@@ -384,18 +451,19 @@ void MaritimeScreen::on_route_selected(int row) {
rd_vessels_->setText(tr("Active Vessels: %1").arg(r.vessels));
}
-void MaritimeScreen::update_intelligence(int vessel_count) {
+void MaritimeScreen::update_intelligence(int region_total, int loaded) {
auto fmt = [](int n) -> QString {
if (n >= 1'000'000) return QString::number(n / 1'000'000.0, 'f', 1) + "M";
if (n >= 1'000) return QString::number(n / 1'000.0, 'f', 1) + "K";
return QString::number(n);
};
- const QString count_str = fmt(vessel_count);
- vessel_count_label_->setText(tr("%1 VESSELS").arg(count_str));
+ // Headline badge + LOADED stat = vessels actually on the map (truthful).
+ vessel_count_label_->setText(tr("%1 VESSELS").arg(fmt(loaded)));
if (stat_vessels_)
- stat_vessels_->setText(count_str);
+ stat_vessels_->setText(fmt(loaded));
+ // IN REGION = server-reported total for the searched area (real, just bigger).
if (stat_displayed_)
- stat_displayed_->setText(QString::number(qMin(vessel_count, 100)));
+ stat_displayed_->setText(region_total > 0 ? fmt(region_total) : QStringLiteral("—"));
if (stat_routes_)
stat_routes_->setText(QString::number(routes_.size()));
}
@@ -404,7 +472,7 @@ void MaritimeScreen::update_credits(int remaining) {
if (!credits_label_ || remaining < 0)
return;
const QString c = remaining < 20 ? ui::colors::NEGATIVE()
- : remaining < 100 ? ui::colors::WARNING()
+ : remaining < 100 ? ui::colors::AMBER()
: ui::colors::POSITIVE();
QColor cc(c);
auto rgb = QString("%1,%2,%3").arg(cc.red()).arg(cc.green()).arg(cc.blue());
@@ -423,6 +491,9 @@ void MaritimeScreen::update_map(const QVector<VesselData>& vessels) {
QVector<fincept::ui::MapPin> pins;
pins.reserve(vessels.size());
QSet<QString> port_seen;
+ int moving = 0;
+ double speed_sum = 0.0;
+ int speed_n = 0;
for (const auto& v : vessels) {
if (v.latitude == 0.0 && v.longitude == 0.0)
continue;
@@ -432,13 +503,25 @@ void MaritimeScreen::update_map(const QVector<VesselData>& vessels) {
const int id = rendered_vessels_.size();
rendered_vessels_.append(v);
pins.append({v.latitude, v.longitude, QString("%1 (%2)").arg(v.name, v.imo),
- ui::colors::POSITIVE, 4.0, id});
- // Track unique destination ports for the PORTS stat.
+ ui::colors::POSITIVE, 5.5, id});
+ // Track unique destination ports for the DEST PORTS stat.
if (!v.to_port.isEmpty())
port_seen.insert(v.to_port);
+ // Fleet motion stats — under-way vessels report speed > ~0.5 kn.
+ if (v.speed > 0.5) {
+ ++moving;
+ speed_sum += v.speed;
+ ++speed_n;
+ }
}
if (stat_ports_)
stat_ports_->setText(QString::number(port_seen.size()));
+ if (stat_moving_)
+ stat_moving_->setText(QString::number(moving));
+ if (stat_speed_)
+ stat_speed_->setText(speed_n > 0
+ ? QString("%1 kn").arg(speed_sum / speed_n, 0, 'f', 1)
+ : QStringLiteral("—"));
map_widget_->set_pins(pins);
map_widget_->fit_to_pins();
}
@@ -472,7 +555,7 @@ void MaritimeScreen::on_vessel_history(VesselHistoryPage page) {
update_credits(page.remaining_credits);
const auto& history = page.history;
if (history.isEmpty()) {
- set_status(tr("NO HISTORY"), ui::colors::WARNING);
+ set_status(tr("NO HISTORY"), ui::colors::AMBER);
return;
}
@@ -505,15 +588,41 @@ void MaritimeScreen::on_vessel_history(VesselHistoryPage page) {
ui::colors::POSITIVE, 8.0});
}
- map_widget_->set_pins(pins);
+ // Connect the trail dots with a polyline so the voyage reads as a route,
+ // not a scatter of points.
+ QVector<QPointF> track;
+ track.reserve(history.size());
+ for (const auto& h : history) {
+ if (h.latitude == 0.0 && h.longitude == 0.0)
+ continue;
+ track.append(QPointF(h.latitude, h.longitude));
+ }
+
+ map_widget_->set_pins(pins); // clears any previous track
+ map_widget_->set_track_path(track); // draw the connecting line
map_widget_->fit_to_pins();
+ // Resolve + plot the voyage's origin / destination ports from the latest
+ // leg's from/to names (async; routed by the name: context in on_ports_found
+ // so these never leak into the user-facing ports table).
+ voyage_port_ctx_.clear();
+ const QString from_p = current.from_port.trimmed();
+ const QString to_p = current.to_port.trimmed();
+ if (!from_p.isEmpty()) {
+ voyage_port_ctx_.insert(QStringLiteral("name:") + from_p.toLower(), tr("ORIGIN: %1").arg(from_p));
+ PortsCatalog::instance().search_by_name(from_p, 5);
+ }
+ if (!to_p.isEmpty() && to_p.compare(from_p, Qt::CaseInsensitive) != 0) {
+ voyage_port_ctx_.insert(QStringLiteral("name:") + to_p.toLower(), tr("DEST: %1").arg(to_p));
+ PortsCatalog::instance().search_by_name(to_p, 5);
+ }
+
vessels_table_->setSortingEnabled(false);
vessels_table_->setRowCount(history.size());
for (int i = 0; i < history.size(); ++i) {
const auto& v = history[i];
auto* name_item = new QTableWidgetItem(v.name);
- name_item->setForeground(QBrush(QColor(ui::colors::WARNING.get())));
+ name_item->setForeground(QBrush(QColor(ui::colors::AMBER.get())));
vessels_table_->setItem(i, 0, name_item);
vessels_table_->setItem(i, 1, new QTableWidgetItem(v.imo));
auto* lat = new QTableWidgetItem(QString::number(v.latitude, 'f', 4));
@@ -536,7 +645,7 @@ void MaritimeScreen::on_vessel_history(VesselHistoryPage page) {
vessels_table_->resizeColumnsToContents();
const int reported = page.total_records > 0 ? page.total_records : total;
- set_status(tr("HISTORY: %1 (%2 positions)").arg(vessel_name).arg(reported), ui::colors::WARNING);
+ set_status(tr("HISTORY: %1 (%2 positions)").arg(vessel_name).arg(reported), ui::colors::AMBER);
LOG_INFO("Maritime", QString("Vessel history [%1]: %2 / %3 positions").arg(vessel_name).arg(total).arg(reported));
}
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp
index 14d536529..9de6a499b 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp
@@ -66,23 +66,23 @@ void MaritimeScreen::build_ui() {
// ── Top Bar ──────────────────────────────────────────────────────────────────
QWidget* MaritimeScreen::build_top_bar() {
auto* bar = new QWidget(this);
- bar->setFixedHeight(44);
+ bar->setFixedHeight(46);
auto* hl = new QHBoxLayout(bar);
- hl->setContentsMargins(12, 0, 12, 0);
- hl->setSpacing(12);
+ hl->setContentsMargins(14, 0, 14, 0);
+ hl->setSpacing(10);
+
+ // Leading amber accent bar.
+ auto* accent = new QLabel(bar);
+ accent->setFixedSize(4, 18);
+ accent->setStyleSheet(QString("background:%1; border-radius:2px;").arg(C(ui::colors::AMBER)));
+ hl->addWidget(accent);
brand_label_ = new QLabel(tr("FINCEPT MARITIME INTELLIGENCE"), bar);
hl->addWidget(brand_label_);
- classified_label_ = new QLabel(tr("VESSEL TRACKING // FINCEPT MARINE API"), bar);
- hl->addWidget(classified_label_);
-
hl->addStretch(1);
- credits_label_ = new QLabel(tr("CREDITS: —"), bar);
- hl->addWidget(credits_label_);
-
vessel_count_label_ = new QLabel(tr("— VESSELS"), bar);
hl->addWidget(vessel_count_label_);
@@ -116,9 +116,7 @@ QWidget* MaritimeScreen::build_left_panel() {
// each finalized shape triggers on_shapes_changed which loads the union
// bbox and filters returned vessels to those inside any drawn shape.
draw_title_ = new QLabel(tr("DRAW AREA ON MAP"), panel);
- draw_title_->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::colors::AMBER())
- .arg(ui::fonts::DATA_FAMILY));
+ draw_title_->setStyleSheet(section_label_ss());
vl->addWidget(draw_title_);
auto* draw_row = new QHBoxLayout;
@@ -163,10 +161,8 @@ QWidget* MaritimeScreen::build_left_panel() {
}
});
- intel_title_ = new QLabel(tr("INTELLIGENCE"), panel);
- intel_title_->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::colors::AMBER())
- .arg(ui::fonts::DATA_FAMILY));
+ intel_title_ = new QLabel(tr("FLEET INTELLIGENCE"), panel);
+ intel_title_->setStyleSheet(section_label_ss());
vl->addWidget(intel_title_);
auto* grid = new QGridLayout;
@@ -178,17 +174,19 @@ QWidget* MaritimeScreen::build_left_panel() {
auto make_stat = [&](const QString& label, const QString& obj_key, const QString& value,
const ui::ColorToken& val_color, QLabel** cap_out, QLabel** val_out) {
auto* box = new QWidget(panel);
- box->setStyleSheet(QString("background:%1; border:1px solid %2; border-radius:2px;")
- .arg(C(ui::colors::BG_BASE), C(ui::colors::BORDER_DIM)));
+ box->setObjectName(QStringLiteral("mtStatBox"));
+ // Scope to the box so the border doesn't cascade onto the child labels.
+ box->setStyleSheet(QString("#mtStatBox { background:%1; border:1px solid %2; border-radius:2px; }")
+ .arg(C(ui::colors::BG_BASE), C(ui::colors::BORDER_MED)));
auto* bvl = new QVBoxLayout(box);
- bvl->setContentsMargins(8, 6, 8, 6);
- bvl->setSpacing(2);
+ bvl->setContentsMargins(10, 8, 10, 8);
+ bvl->setSpacing(3);
auto* lbl = new QLabel(label, box);
- lbl->setStyleSheet(QString("color:%1; font-size:7px; font-family:%2;")
- .arg(ui::colors::TEXT_TERTIARY())
+ lbl->setStyleSheet(QString("color:%1; font-size:10px; font-weight:700; font-family:%2; letter-spacing:0.5px;")
+ .arg(ui::colors::TEXT_SECONDARY())
.arg(ui::fonts::DATA_FAMILY));
auto* val = new QLabel(value, box);
- val->setStyleSheet(QString("color:%1; font-size:12px; font-weight:700; font-family:%2;")
+ val->setStyleSheet(QString("color:%1; font-size:18px; font-weight:700; font-family:%2;")
.arg(C(val_color))
.arg(ui::fonts::DATA_FAMILY));
val->setObjectName(obj_key);
@@ -199,25 +197,29 @@ QWidget* MaritimeScreen::build_left_panel() {
return box;
};
- // All stats start at "—" and are populated from the loaded vessel set.
- // No hardcoded trade-volume, route count, or satellite numbers — the API
- // does not expose those, so we don't fabricate them.
- grid->addWidget(make_stat(tr("TOTAL IN AREA"), QStringLiteral("stat_vessels"), "—",
- ui::colors::INFO, &stat_vessels_cap_, &stat_vessels_), 0, 0);
- grid->addWidget(make_stat(tr("DISPLAYED"), QStringLiteral("stat_displayed"), "—",
- ui::colors::POSITIVE, &stat_displayed_cap_, &stat_displayed_), 0, 1);
+ // All stats start at "—" and are computed from the loaded vessel set only.
+ // No hardcoded trade-volume / satellite figures — the API doesn't expose
+ // those, so we don't fabricate them. LOADED = vessels actually on the map;
+ // IN REGION = the server's reported total for the searched area (these
+ // differ, so they're labelled distinctly to avoid the "200 vs 5.2K" confusion).
+ grid->addWidget(make_stat(tr("LOADED"), QStringLiteral("stat_vessels"), "—",
+ ui::colors::AMBER, &stat_vessels_cap_, &stat_vessels_), 0, 0);
+ grid->addWidget(make_stat(tr("IN REGION"), QStringLiteral("stat_displayed"), "—",
+ ui::colors::TEXT_PRIMARY, &stat_displayed_cap_, &stat_displayed_), 0, 1);
+ grid->addWidget(make_stat(tr("MOVING"), QStringLiteral("stat_moving"), "—",
+ ui::colors::POSITIVE, &stat_moving_cap_, &stat_moving_), 1, 0);
+ grid->addWidget(make_stat(tr("AVG SPEED"), QStringLiteral("stat_speed"), "—",
+ ui::colors::TEXT_PRIMARY, &stat_speed_cap_, &stat_speed_), 1, 1);
grid->addWidget(make_stat(tr("ROUTES"), QStringLiteral("stat_routes"), "—",
- ui::colors::INFO, &stat_routes_cap_, &stat_routes_), 1, 0);
- grid->addWidget(make_stat(tr("PORTS"), QStringLiteral("stat_ports"), "—",
- ui::colors::WARNING, &stat_ports_cap_, &stat_ports_), 1, 1);
+ ui::colors::TEXT_PRIMARY, &stat_routes_cap_, &stat_routes_), 2, 0);
+ grid->addWidget(make_stat(tr("DEST PORTS"), QStringLiteral("stat_ports"), "—",
+ ui::colors::TEXT_PRIMARY, &stat_ports_cap_, &stat_ports_), 2, 1);
vl->addLayout(grid);
vl->addSpacing(8);
routes_title_ = new QLabel(tr("TRADE CORRIDORS"), panel);
- routes_title_->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(ui::colors::AMBER())
- .arg(ui::fonts::DATA_FAMILY));
+ routes_title_->setStyleSheet(section_label_ss());
vl->addWidget(routes_title_);
routes_table_ = new QTableWidget(panel);
@@ -242,19 +244,65 @@ QWidget* MaritimeScreen::build_center_panel() {
vl->setContentsMargins(0, 0, 0, 0);
vl->setSpacing(0);
+ // ── Map toolbar ─────────────────────────────────────────────────────────
+ // Command-bar styled header above the map: accent + title on the left, a
+ // BASEMAP selector on the right. The combo is populated once the map widget
+ // exists (below) so its current basemap drives the initial selection.
auto* header = new QWidget(panel);
+ header->setObjectName("mtMapToolbar");
header->setFixedHeight(36);
- header->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(C(ui::colors::BG_RAISED), C(ui::colors::BORDER_DIM)));
+ // Flat, even background matching the panels (no lighter "raised" strip) with
+ // a single hairline rule separating it from the map. WA_StyledBackground
+ // guarantees the whole rect fills uniformly.
+ header->setAttribute(Qt::WA_StyledBackground, true);
+ header->setStyleSheet(QString("#mtMapToolbar { background:%1; border-bottom:1px solid %2; }")
+ .arg(C(ui::colors::BG_BASE), C(ui::colors::BORDER_DIM)));
auto* hhl = new QHBoxLayout(header);
- hhl->setContentsMargins(16, 0, 16, 0);
- center_title_ = new QLabel(tr("VESSEL TRACKING"), header);
+ hhl->setContentsMargins(12, 0, 12, 0);
+ hhl->setSpacing(8);
+
+ auto* accent = new QLabel(header);
+ accent->setFixedSize(3, 14);
+ accent->setStyleSheet(QString("background:%1; border-radius:1px;").arg(C(ui::colors::AMBER)));
+ hhl->addWidget(accent);
+
+ center_title_ = new QLabel(tr("LIVE VESSEL MAP"), header);
center_title_->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; letter-spacing:1px;")
.arg(ui::colors::AMBER())
.arg(ui::fonts::TINY)
.arg(ui::fonts::DATA_FAMILY));
hhl->addWidget(center_title_);
hhl->addStretch();
+
+ // Manual refresh + visible AUTO-refresh toggle (off by default so it never
+ // silently burns API credits — the user opts in).
+ refresh_btn_ = new QPushButton(tr("⟳ REFRESH"), header);
+ refresh_btn_->setCursor(Qt::PointingHandCursor);
+ refresh_btn_->setStyleSheet(toolbar_btn_ss());
+ connect(refresh_btn_, &QPushButton::clicked, this, [this]() { do_refresh(); });
+ hhl->addWidget(refresh_btn_);
+
+ auto_refresh_btn_ = new QPushButton(tr("AUTO ⟳ OFF"), header);
+ auto_refresh_btn_->setCursor(Qt::PointingHandCursor);
+ auto_refresh_btn_->setCheckable(true);
+ auto_refresh_btn_->setStyleSheet(toolbar_btn_ss());
+ connect(auto_refresh_btn_, &QPushButton::toggled, this, [this](bool on) {
+ auto_refresh_btn_->setText(on ? tr("AUTO ⟳ 5m") : tr("AUTO ⟳ OFF"));
+ if (on) refresh_timer_->start();
+ else refresh_timer_->stop();
+ });
+ hhl->addWidget(auto_refresh_btn_);
+
+ basemap_cap_ = new QLabel(tr("BASEMAP"), header);
+ basemap_cap_->setStyleSheet(tiny_label_ss());
+ hhl->addWidget(basemap_cap_);
+
+ map_type_combo_ = new QComboBox(header);
+ map_type_combo_->setCursor(Qt::PointingHandCursor);
+ map_type_combo_->setFixedWidth(132);
+ map_type_combo_->setStyleSheet(combo_ss());
+ hhl->addWidget(map_type_combo_);
+
vl->addWidget(header);
auto* splitter = new QSplitter(Qt::Vertical, panel);
@@ -268,6 +316,17 @@ QWidget* MaritimeScreen::build_center_panel() {
// events while visible so the user can't pan a half-loaded map.
map_loader_ = new fincept::ui::LoadingOverlay(map_widget_);
+ // Populate + wire the basemap selector now that the map exists. The map
+ // defaults to SATELLITE; switching is instant and preserves camera/pins.
+ if (map_type_combo_) {
+ map_type_combo_->addItems(fincept::ui::WorldMapWidget::basemap_labels());
+ map_type_combo_->setCurrentIndex(map_widget_->current_basemap_index());
+ connect(map_type_combo_, &QComboBox::currentIndexChanged, this, [this](int idx) {
+ if (map_widget_)
+ map_widget_->set_basemap(idx);
+ });
+ }
+
// Drawn-shape changes → load vessels for the union bbox and filter to
// those inside the shapes.
connect(map_widget_, &fincept::ui::WorldMapWidget::shapes_changed, this,
@@ -373,7 +432,7 @@ QWidget* MaritimeScreen::build_right_panel() {
auto imo = imo_edit_->text().trimmed();
if (imo.isEmpty())
return;
- set_status(tr("LOADING HISTORY..."), ui::colors::WARNING);
+ set_status(tr("LOADING HISTORY..."), ui::colors::AMBER);
show_map_loading(tr("LOADING HISTORY"));
MaritimeService::instance().get_vessel_history(imo);
});
@@ -381,14 +440,15 @@ QWidget* MaritimeScreen::build_right_panel() {
// Search result card
search_result_card_ = new QWidget(content);
+ search_result_card_->setObjectName(QStringLiteral("mtSearchCard"));
search_result_card_->setVisible(false);
auto* srvl = new QVBoxLayout(search_result_card_);
srvl->setContentsMargins(10, 10, 10, 10);
srvl->setSpacing(4);
sr_name_ = new QLabel(search_result_card_);
- sr_name_->setStyleSheet(QString("color:%1; font-size:11px; font-weight:700; font-family:%2;")
- .arg(ui::colors::INFO())
+ sr_name_->setStyleSheet(QString("color:%1; font-size:13px; font-weight:700; font-family:%2;")
+ .arg(ui::colors::AMBER())
.arg(ui::fonts::DATA_FAMILY));
srvl->addWidget(sr_name_);
sr_imo_ = new QLabel(search_result_card_);
@@ -439,6 +499,45 @@ QWidget* MaritimeScreen::build_right_panel() {
services::maritime::GeocodingService::instance().search(q);
};
connect(place_query_edit_, &QLineEdit::returnPressed, this, run_place_search);
+
+ // Live typeahead: a completer popup fed by debounced geocoder results.
+ place_completer_model_ = new QStringListModel(this);
+ place_completer_ = new QCompleter(place_completer_model_, this);
+ place_completer_->setCaseSensitivity(Qt::CaseInsensitive);
+ place_completer_->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
+ place_completer_->setMaxVisibleItems(8);
+ place_query_edit_->setCompleter(place_completer_);
+ if (auto* popup = place_completer_->popup()) {
+ popup->setStyleSheet(QString("background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; outline:0;"
+ "selection-background-color:%6; selection-color:%7;")
+ .arg(C(ui::colors::BG_RAISED), C(ui::colors::TEXT_PRIMARY),
+ C(ui::colors::BORDER_MED), F(ui::fonts::DATA_FAMILY))
+ .arg(ui::fonts::SMALL)
+ .arg(C(ui::colors::BG_HOVER), C(ui::colors::AMBER)));
+ }
+ // Picking a suggestion loads vessels for that place's bbox.
+ connect(place_completer_, QOverload<const QString&>::of(&QCompleter::activated), this,
+ [this](const QString& text) {
+ for (const auto& p : place_results_) {
+ if (p.display_name == text) {
+ run_area_search(p.min_lat, p.max_lat, p.min_lng, p.max_lng);
+ return;
+ }
+ }
+ });
+ place_debounce_ = new QTimer(this);
+ place_debounce_->setSingleShot(true);
+ place_debounce_->setInterval(350);
+ connect(place_debounce_, &QTimer::timeout, this, [this]() {
+ const QString q = place_query_edit_->text().trimmed();
+ if (q.size() < 3) return;
+ if (place_status_) place_status_->setText(tr("Searching…"));
+ services::maritime::GeocodingService::instance().search(q);
+ });
+ // textEdited (not textChanged) so programmatic fills don't trigger searches.
+ connect(place_query_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { place_debounce_->start(); });
vl->addWidget(place_query_edit_);
place_btn_ = new QPushButton(tr("SEARCH PLACES"), content);
@@ -550,6 +649,53 @@ QWidget* MaritimeScreen::build_right_panel() {
PortsCatalog::instance().search_by_name(q);
};
connect(ports_query_edit_, &QLineEdit::returnPressed, this, run_name_search);
+
+ // Live typeahead for ports — same pattern as place search.
+ ports_completer_model_ = new QStringListModel(this);
+ ports_completer_ = new QCompleter(ports_completer_model_, this);
+ ports_completer_->setCaseSensitivity(Qt::CaseInsensitive);
+ ports_completer_->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
+ ports_completer_->setMaxVisibleItems(8);
+ ports_query_edit_->setCompleter(ports_completer_);
+ if (auto* popup = ports_completer_->popup()) {
+ popup->setStyleSheet(QString("background:%1; color:%2; border:1px solid %3;"
+ "font-family:%4; font-size:%5px; outline:0;"
+ "selection-background-color:%6; selection-color:%7;")
+ .arg(C(ui::colors::BG_RAISED), C(ui::colors::TEXT_PRIMARY),
+ C(ui::colors::BORDER_MED), F(ui::fonts::DATA_FAMILY))
+ .arg(ui::fonts::SMALL)
+ .arg(C(ui::colors::BG_HOVER), C(ui::colors::AMBER)));
+ }
+ // Picking a port suggestion plots it on the map (amber pin) and flies there.
+ connect(ports_completer_, QOverload<const QString&>::of(&QCompleter::activated), this,
+ [this](const QString& text) {
+ if (!map_widget_) return;
+ for (const auto& p : port_results_) {
+ if (p.name == text) {
+ fincept::ui::MapPin pin;
+ pin.latitude = p.latitude;
+ pin.longitude = p.longitude;
+ pin.label = QString("%1 (%2)").arg(p.name, p.locode.isEmpty() ? p.country : p.locode);
+ pin.color = QColor(ui::colors::AMBER.get());
+ pin.radius = 6.0;
+ pin.id = -1;
+ map_widget_->add_pin(pin);
+ map_widget_->fly_to(p.latitude, p.longitude);
+ return;
+ }
+ }
+ });
+ ports_debounce_ = new QTimer(this);
+ ports_debounce_->setSingleShot(true);
+ ports_debounce_->setInterval(350);
+ connect(ports_debounce_, &QTimer::timeout, this, [this]() {
+ const QString q = ports_query_edit_->text().trimmed();
+ if (q.size() < 3) return;
+ if (ports_status_) ports_status_->setText(tr("Searching…"));
+ PortsCatalog::instance().search_by_name(q);
+ });
+ connect(ports_query_edit_, &QLineEdit::textEdited, this,
+ [this](const QString&) { ports_debounce_->start(); });
vl->addWidget(ports_query_edit_);
ports_btn_ = new QPushButton(tr("SEARCH PORTS"), content);
@@ -592,7 +738,7 @@ QWidget* MaritimeScreen::build_right_panel() {
ports_table_->horizontalHeader()->setStretchLastSection(true);
ports_table_->setMinimumHeight(160);
ports_table_->setStyleSheet(table_ss());
- // Click → drop a CYAN pin on the existing world map to distinguish from
+ // Click → drop an AMBER pin on the existing world map to distinguish from
// the green vessel pins, then re-fit the camera.
connect(ports_table_, &QTableWidget::currentCellChanged, this,
[this](int row, int, int, int) {
@@ -604,7 +750,7 @@ QWidget* MaritimeScreen::build_right_panel() {
pin.latitude = p.latitude;
pin.longitude = p.longitude;
pin.label = QString("%1 (%2)").arg(p.name, p.locode.isEmpty() ? p.country : p.locode);
- pin.color = QColor(ui::colors::CYAN.get());
+ pin.color = QColor(ui::colors::AMBER.get());
pin.radius = 6.0;
pin.id = -1;
map_widget_->add_pin(pin);
@@ -615,6 +761,7 @@ QWidget* MaritimeScreen::build_right_panel() {
// ── Route Detail ───────────────────────────────────────────────────────
vl->addSpacing(8);
route_detail_ = new QWidget(content);
+ route_detail_->setObjectName(QStringLiteral("mtRouteCard"));
route_detail_->setVisible(false);
auto* rdvl = new QVBoxLayout(route_detail_);
rdvl->setContentsMargins(10, 10, 10, 10);
@@ -627,8 +774,8 @@ QWidget* MaritimeScreen::build_right_panel() {
rdvl->addWidget(rd_title_);
rd_name_ = new QLabel(route_detail_);
- rd_name_->setStyleSheet(QString("color:%1; font-size:11px; font-weight:700; font-family:%2;")
- .arg(ui::colors::INFO())
+ rd_name_->setStyleSheet(QString("color:%1; font-size:13px; font-weight:700; font-family:%2;")
+ .arg(ui::colors::AMBER())
.arg(ui::fonts::DATA_FAMILY));
rdvl->addWidget(rd_name_);
rd_value_ = new QLabel(route_detail_);
@@ -647,9 +794,9 @@ QWidget* MaritimeScreen::build_right_panel() {
not_found_label_ = new QLabel(content);
not_found_label_->setVisible(false);
not_found_label_->setWordWrap(true);
- not_found_label_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;"
+ not_found_label_->setStyleSheet(QString("color:%1; font-size:11px; font-family:%2;"
"padding:6px; border:1px solid %3; background:%4; border-radius:2px;")
- .arg(ui::colors::WARNING())
+ .arg(ui::colors::AMBER())
.arg(ui::fonts::DATA_FAMILY)
.arg(ui::colors::BORDER_MED())
.arg(ui::colors::BG_SURFACE()));
@@ -668,9 +815,9 @@ QWidget* MaritimeScreen::build_right_panel() {
classified_footer_ = new QLabel(tr("CLASSIFIED — AUTHORIZED PERSONNEL ONLY"), content);
classified_footer_->setWordWrap(true);
classified_footer_->setAlignment(Qt::AlignCenter);
- classified_footer_->setStyleSheet(QString("color:%1; font-size:8px; font-family:%2; font-weight:700;"
+ classified_footer_->setStyleSheet(QString("color:%1; font-size:10px; font-family:%2; font-weight:700;"
"padding:8px; border:1px solid %3; background:%4; border-radius:2px;")
- .arg(ui::colors::WARNING())
+ .arg(ui::colors::TEXT_TERTIARY())
.arg(ui::fonts::DATA_FAMILY)
.arg(ui::colors::BORDER_MED())
.arg(ui::colors::BG_SURFACE()));
@@ -688,15 +835,15 @@ QWidget* MaritimeScreen::build_right_panel() {
// ── Status Bar ───────────────────────────────────────────────────────────────
QWidget* MaritimeScreen::build_status_bar() {
auto* bar = new QWidget(this);
- bar->setFixedHeight(24);
+ bar->setFixedHeight(26);
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(12, 0, 12, 0);
hl->setSpacing(16);
auto s =
- QString("color:%1; font-size:8px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY()).arg(ui::fonts::DATA_FAMILY);
- auto sv = QString("color:%1; font-size:8px; font-weight:700; font-family:%2;")
+ QString("color:%1; font-size:10px; font-family:%2;").arg(ui::colors::TEXT_TERTIARY()).arg(ui::fonts::DATA_FAMILY);
+ auto sv = QString("color:%1; font-size:10px; font-weight:700; font-family:%2;")
.arg(ui::colors::TEXT_PRIMARY())
.arg(ui::fonts::DATA_FAMILY);
@@ -714,9 +861,11 @@ QWidget* MaritimeScreen::build_status_bar() {
hl->addWidget(sb_records_cap_);
hl->addWidget(records_value_);
- sb_refresh_cap_ = new QLabel(tr("REFRESH:"), bar);
+ // Real last-update clock (set on each successful load) — replaces the old
+ // hardcoded "5 MIN" refresh label.
+ sb_refresh_cap_ = new QLabel(tr("UPDATED:"), bar);
sb_refresh_cap_->setStyleSheet(s);
- sb_refresh_val_ = new QLabel(tr("5 MIN"), bar);
+ sb_refresh_val_ = new QLabel(QStringLiteral("—"), bar);
sb_refresh_val_->setStyleSheet(sv);
hl->addWidget(sb_refresh_cap_);
hl->addWidget(sb_refresh_val_);
@@ -735,7 +884,7 @@ void MaritimeScreen::populate_routes_table() {
for (int i = 0; i < routes_.size(); ++i) {
const auto& r = routes_[i];
auto* name_item = new QTableWidgetItem(r.name);
- name_item->setForeground(QBrush(QColor(ui::colors::INFO.get())));
+ name_item->setForeground(QBrush(QColor(ui::colors::AMBER.get())));
routes_table_->setItem(i, 0, name_item);
// The API doesn't expose trade-volume in $ — repurpose the middle
// column for the live vessel count derived from the loaded set.
diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_internal.h b/fincept-qt/src/screens/maritime/MaritimeScreen_internal.h
index 72408f107..29cd05393 100644
--- a/fincept-qt/src/screens/maritime/MaritimeScreen_internal.h
+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_internal.h
@@ -22,18 +22,40 @@ inline QString F(const fincept::ui::fonts::FontFamilyToken& t) {
}
inline QString table_ss() {
+ // Equity-grade terminal table: hairline gridlines, header bottom-rule only,
+ // amber selection, monospace data. Matches the look of the trading screens.
return QString("QTableWidget { background:%1; color:%2; gridline-color:%3;"
- "font-family:%4; font-size:%5px; border:none; }"
- "QTableWidget::item { padding:4px 6px; }"
- "QTableWidget::item:selected { background:%6; }"
- "QTableWidget::item:alternate { background:%7; }"
- "QHeaderView::section { background:%8; color:%9; font-weight:700;"
- "padding:6px 8px; border:1px solid %3; font-family:%4; font-size:%5px; }")
+ "font-family:%4; font-size:%5px; border:none; outline:none; }"
+ "QTableWidget::item { padding:3px 8px; border:none; }"
+ "QTableWidget::item:selected { background:%6; color:%7; }"
+ "QTableWidget::item:alternate { background:%8; }"
+ "QHeaderView::section { background:%9; color:%10; font-weight:700;"
+ "padding:5px 8px; border:none; border-bottom:1px solid %11;"
+ "font-family:%4; font-size:%5px; letter-spacing:0.5px; }")
.arg(C(fincept::ui::colors::BG_BASE), C(fincept::ui::colors::TEXT_PRIMARY),
- C(fincept::ui::colors::BORDER_DIM), F(fincept::ui::fonts::DATA_FAMILY))
+ C(fincept::ui::colors::BG_RAISED), F(fincept::ui::fonts::DATA_FAMILY))
.arg(fincept::ui::fonts::SMALL)
- .arg(C(fincept::ui::colors::BG_HOVER), C(fincept::ui::colors::ROW_ALT),
- C(fincept::ui::colors::BG_RAISED), C(fincept::ui::colors::TEXT_SECONDARY));
+ .arg(C(fincept::ui::colors::BG_HOVER), C(fincept::ui::colors::AMBER),
+ C(fincept::ui::colors::ROW_ALT), C(fincept::ui::colors::BG_RAISED),
+ C(fincept::ui::colors::TEXT_SECONDARY), C(fincept::ui::colors::BORDER_MED));
+}
+
+inline QString combo_ss() {
+ return QString("QComboBox { background:%1; color:%2; border:1px solid %3; border-radius:2px;"
+ "font-family:%4; font-size:%5px; font-weight:700; padding:3px 8px; }"
+ "QComboBox:hover { border-color:%6; }"
+ "QComboBox:focus { border-color:%6; }"
+ "QComboBox::drop-down { border:none; width:16px; }"
+ "QComboBox::down-arrow { image:none; width:0; height:0;"
+ "border-left:3px solid transparent; border-right:3px solid transparent;"
+ "border-top:4px solid %6; margin-right:6px; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2; border:1px solid %3;"
+ "selection-background-color:%7; selection-color:%6; outline:0;"
+ "font-family:%4; font-size:%5px; }")
+ .arg(C(fincept::ui::colors::BG_RAISED), C(fincept::ui::colors::TEXT_PRIMARY),
+ C(fincept::ui::colors::BORDER_MED), F(fincept::ui::fonts::DATA_FAMILY))
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(C(fincept::ui::colors::AMBER), C(fincept::ui::colors::BG_HOVER));
}
inline QString input_ss() {
@@ -56,28 +78,43 @@ inline QString btn_primary_ss() {
}
inline QString btn_outline_ss() {
+ // Neutral grey outline that lights up amber on hover/checked — no yellow.
return QString("QPushButton { background:transparent; color:%1; font-family:%2; font-size:%3px;"
- "font-weight:700; border:1px solid %1; padding:6px; border-radius:2px; }"
- "QPushButton:hover { background:%4; }")
- .arg(C(fincept::ui::colors::WARNING), F(fincept::ui::fonts::DATA_FAMILY))
+ "font-weight:700; border:1px solid %4; padding:7px; border-radius:2px; }"
+ "QPushButton:hover { background:%5; color:%6; border-color:%6; }"
+ "QPushButton:checked { background:%5; color:%6; border-color:%6; }")
+ .arg(C(fincept::ui::colors::TEXT_SECONDARY), F(fincept::ui::fonts::DATA_FAMILY))
.arg(fincept::ui::fonts::SMALL)
- .arg(C(fincept::ui::colors::BG_HOVER));
+ .arg(C(fincept::ui::colors::BORDER_BRIGHT), C(fincept::ui::colors::BG_HOVER),
+ C(fincept::ui::colors::AMBER));
+}
+
+inline QString toolbar_btn_ss() {
+ // Borderless map-toolbar button so the strip reads as one flat surface
+ // (no patchy bordered boxes). Amber text on hover / when active.
+ return QString("QPushButton { background:transparent; color:%1; border:none;"
+ "font-family:%2; font-size:%3px; font-weight:700; padding:3px 8px; }"
+ "QPushButton:hover { color:%4; }"
+ "QPushButton:checked { color:%4; }")
+ .arg(C(fincept::ui::colors::TEXT_SECONDARY), F(fincept::ui::fonts::DATA_FAMILY))
+ .arg(fincept::ui::fonts::SMALL)
+ .arg(C(fincept::ui::colors::AMBER));
}
inline QString section_label_ss() {
- return QString("color:%1; font-size:9px; font-weight:700; font-family:%2;"
+ return QString("color:%1; font-size:12px; font-weight:700; font-family:%2;"
"letter-spacing:1px; padding-bottom:4px; border-bottom:1px solid %3;")
.arg(C(fincept::ui::colors::AMBER), F(fincept::ui::fonts::DATA_FAMILY),
C(fincept::ui::colors::BORDER_DIM));
}
inline QString tiny_label_ss() {
- return QString("color:%1; font-size:8px; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(C(fincept::ui::colors::TEXT_TERTIARY), F(fincept::ui::fonts::DATA_FAMILY));
+ return QString("color:%1; font-size:10px; font-weight:700; font-family:%2; letter-spacing:1px;")
+ .arg(C(fincept::ui::colors::TEXT_SECONDARY), F(fincept::ui::fonts::DATA_FAMILY));
}
inline QString detail_text_ss() {
- return QString("color:%1; font-size:9px; font-family:%2;")
+ return QString("color:%1; font-size:12px; font-family:%2;")
.arg(C(fincept::ui::colors::TEXT_SECONDARY), F(fincept::ui::fonts::DATA_FAMILY));
}
diff --git a/fincept-qt/src/screens/settings/LlmConfigSection.cpp b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
index 7a9dd2278..c2e782b18 100644
--- a/fincept-qt/src/screens/settings/LlmConfigSection.cpp
+++ b/fincept-qt/src/screens/settings/LlmConfigSection.cpp
@@ -35,7 +35,7 @@ static constexpr const char* TAG = "LlmConfigSection";
const QStringList LlmConfigSection::KNOWN_PROVIDERS = {"openai", "anthropic", "gemini", "groq", "deepseek",
"openrouter", "minimax", "kimi", "ollama", "xai", "fincept",
- "astraflow", "astraflow_cn"};
+ "astraflow", "astraflow_cn", "aihubmix"};
QString LlmConfigSection::default_base_url(const QString& provider) {
const QString p = provider.toLower();
@@ -65,6 +65,8 @@ QString LlmConfigSection::default_base_url(const QString& provider) {
return "https://api-us-ca.umodelverse.ai/v1"; // Astraflow global endpoint (UCloud)
if (p == "astraflow_cn")
return "https://api.modelverse.cn/v1"; // Astraflow China endpoint (UCloud)
+ if (p == "aihubmix")
+ return "https://aihubmix.com/v1"; // AIHubMix — OpenAI-compatible aggregator (500+ models)
return {};
}
@@ -115,6 +117,15 @@ QStringList LlmConfigSection::fallback_models(const QString& provider) {
"gemini-2.5-flash", "gemini-2.5-pro",
"deepseek-chat", "deepseek-reasoner",
"llama-3.3-70b-versatile", "qwen-turbo", "qwen-plus"};
+ if (p == "aihubmix")
+ // AIHubMix — OpenAI-compatible aggregator routing 500+ models (OpenAI, Claude,
+ // Gemini, DeepSeek, Qwen, ...) through one /v1/chat/completions endpoint. Models
+ // keep their upstream ids. Starter list only; full list via the Fetch button.
+ return {"gpt-4o", "gpt-4o-mini", "gpt-4.1", "o3-mini",
+ "claude-sonnet-4-5-20250514", "claude-3-5-sonnet-20241022",
+ "gemini-2.5-flash", "gemini-2.5-pro",
+ "deepseek-chat", "deepseek-reasoner",
+ "qwen-max", "qwen-plus", "grok-4"};
return {};
}
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
index 2f9f94996..16bf37fdf 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
@@ -211,6 +211,7 @@ inline QVector<IndicatorDef> algo_indicators() {
// Volume
{"OBV", "On Balance Volume", "volume", {}, {"value"}},
{"CMF", "Chaikin Money Flow", "volume", {{"period", 1, 100, 20, 1, 0}}, {"value"}},
+ {"VOL_WIN_CHG", "Volume Window Δ%", "volume", {{"window", 2, 200, 10, 1, 0}}, {"value"}},
};
}
diff --git a/fincept-qt/src/services/feeds/FeedMonitor.cpp b/fincept-qt/src/services/feeds/FeedMonitor.cpp
new file mode 100644
index 000000000..f89bde45b
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedMonitor.cpp
@@ -0,0 +1,263 @@
+#include "services/feeds/FeedMonitor.h"
+
+#include "services/feeds/FeedParseUtil.h"
+#include "services/feeds/FeedScraper.h"
+#include "storage/repositories/FeedItemRepository.h"
+#include "storage/repositories/FeedSubscriptionRepository.h"
+
+#include <QDateTime>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QTimer>
+#include <QUrl>
+
+#include <algorithm>
+
+namespace fincept::feeds {
+
+namespace {
+
+const char* kBrowserUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/120.0 Safari/537.36";
+constexpr int kTransferTimeoutMs = 15000;
+
+QNetworkRequest build_request(const FeedSubscription& sub) {
+ QNetworkRequest req{QUrl(sub.url)};
+ req.setHeader(QNetworkRequest::UserAgentHeader, kBrowserUA);
+ req.setRawHeader("Accept", "application/rss+xml, application/xml, text/xml, application/json, text/csv, */*");
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
+ req.setTransferTimeout(kTransferTimeoutMs);
+ for (auto it = sub.headers.begin(); it != sub.headers.end(); ++it)
+ req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());
+ return req;
+}
+
+} // namespace
+
+FeedMonitor& FeedMonitor::instance() {
+ static FeedMonitor s;
+ return s;
+}
+
+FeedMonitor::FeedMonitor() : QObject(nullptr) {
+ qRegisterMetaType<fincept::feeds::FeedItem>("fincept::feeds::FeedItem");
+ qRegisterMetaType<QVector<fincept::feeds::FeedItem>>("QVector<fincept::feeds::FeedItem>");
+ qRegisterMetaType<fincept::feeds::FeedStatus>("fincept::feeds::FeedStatus");
+ nam_ = new QNetworkAccessManager(this);
+}
+
+void FeedMonitor::ensure_loaded() {
+ if (loaded_)
+ return;
+ loaded_ = true;
+ const auto res = FeedSubscriptionRepository::instance().list_all();
+ if (res.is_ok()) {
+ for (const auto& sub : res.value()) {
+ Entry e;
+ e.sub = sub;
+ // Seed the in-memory cache from stored history so cached items show
+ // immediately (and survive a feed being down on first fetch).
+ if (sub.persist) {
+ const auto cached = FeedItemRepository::instance().recent(sub.id, kMaxItems);
+ if (cached.is_ok())
+ e.items = cached.value();
+ }
+ feeds_.insert(sub.id, e);
+ if (sub.enabled)
+ arm_timer(sub);
+ }
+ }
+}
+
+QVector<FeedSubscription> FeedMonitor::subscriptions() const {
+ QVector<FeedSubscription> out;
+ out.reserve(feeds_.size());
+ for (const auto& e : feeds_)
+ out.append(e.sub);
+ std::sort(out.begin(), out.end(),
+ [](const FeedSubscription& a, const FeedSubscription& b) { return a.sort_order < b.sort_order; });
+ return out;
+}
+
+QVector<FeedItem> FeedMonitor::cached_items(const QString& id) const {
+ auto it = feeds_.find(id);
+ return it != feeds_.end() ? it->items : QVector<FeedItem>{};
+}
+
+FeedStatus FeedMonitor::status(const QString& id) const {
+ auto it = feeds_.find(id);
+ return it != feeds_.end() ? it->status : FeedStatus::Idle;
+}
+
+void FeedMonitor::arm_timer(const FeedSubscription& sub) {
+ Entry& e = feeds_[sub.id];
+ e.sub = sub;
+ if (!e.timer) {
+ e.timer = new QTimer(this);
+ const QString id = sub.id;
+ connect(e.timer, &QTimer::timeout, this, [this, id]() {
+ auto it = feeds_.find(id);
+ if (it != feeds_.end())
+ fetch(it->sub);
+ });
+ }
+ e.timer->setInterval(std::max(kMinRefreshSec, sub.refresh_sec) * 1000);
+ if (!paused_) {
+ e.timer->start();
+ fetch(sub); // immediate first fetch
+ }
+}
+
+void FeedMonitor::disarm_timer(const QString& id) {
+ auto it = feeds_.find(id);
+ if (it != feeds_.end() && it->timer)
+ it->timer->stop();
+}
+
+void FeedMonitor::fetch(const FeedSubscription& sub) {
+ feeds_[sub.id].status = FeedStatus::Fetching;
+ emit feed_status(sub.id, FeedStatus::Fetching, QStringLiteral("Fetching…"));
+
+ auto* reply = nam_->get(build_request(sub));
+ const QString id = sub.id;
+ connect(reply, &QNetworkReply::finished, this, [this, reply, id]() {
+ reply->deleteLater();
+ auto it = feeds_.find(id);
+ if (it == feeds_.end())
+ return;
+ const FeedSubscription fsub = it->sub;
+ if (reply->error() != QNetworkReply::NoError) {
+ it->status = FeedStatus::Error;
+ emit feed_status(id, FeedStatus::Error, reply->errorString());
+ return;
+ }
+ const QByteArray data = reply->readAll();
+ if (looks_like_html(data)) {
+ it->status = FeedStatus::Error;
+ emit feed_status(id, FeedStatus::Error, QStringLiteral("Access denied / not a feed"));
+ return;
+ }
+ QVector<FeedItem> parsed = FeedScraper::parse(data, fsub);
+ if (parsed.isEmpty()) {
+ it->status = FeedStatus::Error;
+ emit feed_status(id, FeedStatus::Error, QStringLiteral("No items parsed"));
+ return;
+ }
+ // Merge newest-first, dedup by id, cap.
+ QVector<FeedItem> merged = parsed;
+ for (const auto& old : it->items)
+ if (std::none_of(merged.begin(), merged.end(),
+ [&](const FeedItem& x) { return x.id == old.id; }))
+ merged.append(old);
+ std::stable_sort(merged.begin(), merged.end(),
+ [](const FeedItem& a, const FeedItem& b) { return a.sort_ts > b.sort_ts; });
+ if (merged.size() > kMaxItems)
+ merged.resize(kMaxItems);
+ it->items = merged;
+ it->status = FeedStatus::Ok;
+ // Persist newly-seen items for offline cache + history (capped per feed).
+ if (fsub.persist) {
+ const qint64 now_ts = QDateTime::currentSecsSinceEpoch();
+ FeedItemRepository::instance().upsert(id, parsed, now_ts);
+ FeedItemRepository::instance().prune(id, kMaxHistory);
+ }
+ emit feed_updated(id, merged);
+ emit feed_status(id, FeedStatus::Ok, QStringLiteral("Updated"));
+ });
+}
+
+void FeedMonitor::add_or_update(const FeedSubscription& sub) {
+ FeedSubscriptionRepository::instance().upsert(sub);
+ if (sub.enabled) {
+ arm_timer(sub);
+ } else {
+ feeds_[sub.id].sub = sub;
+ disarm_timer(sub.id);
+ }
+ emit subscriptions_changed();
+}
+
+void FeedMonitor::remove(const QString& id) {
+ FeedSubscriptionRepository::instance().remove(id);
+ FeedItemRepository::instance().clear(id); // drop stored history too
+ disarm_timer(id);
+ feeds_.remove(id);
+ emit subscriptions_changed();
+}
+
+void FeedMonitor::set_enabled(const QString& id, bool enabled) {
+ auto it = feeds_.find(id);
+ if (it == feeds_.end())
+ return;
+ it->sub.enabled = enabled;
+ FeedSubscriptionRepository::instance().set_enabled(id, enabled);
+ if (enabled)
+ arm_timer(it->sub);
+ else
+ disarm_timer(id);
+ emit subscriptions_changed();
+}
+
+void FeedMonitor::refresh_now(const QString& id) {
+ auto it = feeds_.find(id);
+ if (it != feeds_.end())
+ fetch(it->sub);
+}
+
+void FeedMonitor::pause_all() {
+ paused_ = true;
+ for (auto& e : feeds_)
+ if (e.timer)
+ e.timer->stop();
+}
+
+void FeedMonitor::resume_all() {
+ if (!paused_)
+ return;
+ paused_ = false;
+ for (auto& e : feeds_)
+ if (e.sub.enabled && e.timer)
+ e.timer->start();
+}
+
+void FeedMonitor::fetch_once(const FeedSubscription& sub, PreviewCb cb) {
+ auto* reply = nam_->get(build_request(sub));
+ connect(reply, &QNetworkReply::finished, this, [reply, sub, cb]() {
+ reply->deleteLater();
+ if (reply->error() != QNetworkReply::NoError) {
+ cb(false, reply->errorString(), {});
+ return;
+ }
+ const QByteArray data = reply->readAll();
+ if (looks_like_html(data)) {
+ cb(false, QStringLiteral("Access denied / not a feed"), {});
+ return;
+ }
+ const QVector<FeedItem> items = FeedScraper::parse(data, sub);
+ cb(!items.isEmpty(),
+ items.isEmpty() ? QStringLiteral("No items parsed") : QString("%1 items").arg(items.size()), items);
+ });
+}
+
+void FeedMonitor::discover(const FeedSubscription& sub, DiscoverCb cb) {
+ auto* reply = nam_->get(build_request(sub));
+ connect(reply, &QNetworkReply::finished, this, [reply, sub, cb]() {
+ reply->deleteLater();
+ if (reply->error() != QNetworkReply::NoError) {
+ cb(false, reply->errorString(), {});
+ return;
+ }
+ const QByteArray data = reply->readAll();
+ if (looks_like_html(data)) {
+ cb(false, QStringLiteral("Access denied / not a feed"), {});
+ return;
+ }
+ const DiscoveredSchema schema = FeedScraper::discover(data, sub);
+ cb(schema.ok, schema.ok ? QString("%1 tags found").arg(schema.fields.size())
+ : QStringLiteral("Couldn't read the feed structure"),
+ schema);
+ });
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedMonitor.h b/fincept-qt/src/services/feeds/FeedMonitor.h
new file mode 100644
index 000000000..12c6f5cee
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedMonitor.h
@@ -0,0 +1,74 @@
+#pragma once
+#include "services/feeds/FeedScraper.h"
+#include "services/feeds/FeedTypes.h"
+
+#include <QHash>
+#include <QObject>
+#include <QVector>
+
+#include <functional>
+
+class QNetworkAccessManager;
+class QTimer;
+
+namespace fincept::feeds {
+
+/// App-lifetime singleton. Owns subscriptions + one QTimer per enabled feed,
+/// fetches via a raw QNetworkAccessManager (HttpClient is JSON-only and cannot be
+/// used for RSS/XML), parses via FeedScraper, caches latest items, and emits
+/// per-feed updates consumed by any number of FeedViews (docked or floating).
+class FeedMonitor : public QObject {
+ Q_OBJECT
+ public:
+ static FeedMonitor& instance();
+
+ void ensure_loaded(); // load subscriptions from repo (idempotent)
+ QVector<FeedSubscription> subscriptions() const;
+ QVector<FeedItem> cached_items(const QString& feed_id) const;
+ FeedStatus status(const QString& feed_id) const;
+
+ // CRUD — persist + re-arm timers + emit subscriptions_changed().
+ void add_or_update(const FeedSubscription& sub);
+ void remove(const QString& feed_id);
+ void set_enabled(const QString& feed_id, bool enabled);
+
+ void refresh_now(const QString& feed_id);
+ void pause_all();
+ void resume_all();
+
+ // One-shot fetch for the config dialog Test/Preview (not persisted).
+ using PreviewCb = std::function<void(bool ok, QString msg, QVector<FeedItem>)>;
+ void fetch_once(const FeedSubscription& sub, PreviewCb cb);
+
+ // One-shot fetch + structure probe for the manual-mapping UI (not persisted).
+ using DiscoverCb = std::function<void(bool ok, QString msg, DiscoveredSchema)>;
+ void discover(const FeedSubscription& sub, DiscoverCb cb);
+
+ signals:
+ void feed_updated(const QString& feed_id, const QVector<fincept::feeds::FeedItem>& items);
+ void feed_status(const QString& feed_id, fincept::feeds::FeedStatus status, const QString& msg);
+ void subscriptions_changed();
+
+ private:
+ FeedMonitor();
+ void arm_timer(const FeedSubscription& sub);
+ void disarm_timer(const QString& feed_id);
+ void fetch(const FeedSubscription& sub);
+
+ struct Entry {
+ FeedSubscription sub;
+ QTimer* timer = nullptr;
+ QVector<FeedItem> items;
+ FeedStatus status = FeedStatus::Idle;
+ };
+ QNetworkAccessManager* nam_ = nullptr;
+ QHash<QString, Entry> feeds_;
+ bool loaded_ = false;
+ bool paused_ = false;
+
+ static constexpr int kMinRefreshSec = 15;
+ static constexpr int kMaxItems = 200; // in-memory cache cap (live display)
+ static constexpr int kMaxHistory = 2000; // persisted-history cap per feed
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedParseUtil.cpp b/fincept-qt/src/services/feeds/FeedParseUtil.cpp
new file mode 100644
index 000000000..e3b2a29f4
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedParseUtil.cpp
@@ -0,0 +1,189 @@
+#include "services/feeds/FeedParseUtil.h"
+
+#include <QDate>
+#include <QDateTime>
+#include <QHash>
+#include <QLocale>
+#include <QRegularExpression>
+#include <QTime>
+
+namespace fincept::feeds {
+
+QString strip_html(const QString& in, int max_chars) {
+ QString s = in;
+ static const QRegularExpression tag("<[^>]*>");
+ s.remove(tag);
+ s.replace("&amp;", "&")
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&quot;", "\"")
+ .replace("&#39;", "'")
+ .replace("&nbsp;", " ");
+ static const QRegularExpression ws("\\s+");
+ s = s.replace(ws, " ").trimmed();
+ if (max_chars > 0 && s.size() > max_chars)
+ s = s.left(max_chars).trimmed() + QStringLiteral("…");
+ return s;
+}
+
+namespace {
+
+// Common timezone abbreviations -> fixed UTC offset (RFC822 style).
+const QHash<QString, QString>& zone_offsets() {
+ static const QHash<QString, QString> z = {
+ {"GMT", "+0000"}, {"UTC", "+0000"}, {"UT", "+0000"}, {"Z", "+0000"}, {"EST", "-0500"},
+ {"EDT", "-0400"}, {"CST", "-0600"}, {"CDT", "-0500"}, {"MST", "-0700"}, {"MDT", "-0600"},
+ {"PST", "-0800"}, {"PDT", "-0700"}, {"IST", "+0530"}, {"CET", "+0100"}, {"CEST", "+0200"},
+ {"BST", "+0100"}, {"JST", "+0900"}, {"AEST", "+1000"}, {"AEDT", "+1100"},{"SGT", "+0800"},
+ {"HKT", "+0800"}, {"NZST", "+1200"},
+ };
+ return z;
+}
+
+// Explicit formats tried with the C locale, so text month/day names parse
+// regardless of the user's system locale.
+const QStringList& fallback_formats() {
+ static const QStringList f = {
+ "ddd, dd MMM yyyy HH:mm:ss", "ddd, d MMM yyyy HH:mm:ss", "dd MMM yyyy HH:mm:ss",
+ "d MMM yyyy HH:mm:ss", "ddd, dd MMM yyyy HH:mm", "dd MMM yyyy HH:mm",
+ // Text-month with dash / slash / dot separators (e.g. "05-Jun-2026 14:35:36").
+ "dd-MMM-yyyy HH:mm:ss", "d-MMM-yyyy HH:mm:ss", "dd-MMM-yyyy HH:mm",
+ "dd-MMM-yyyy", "dd/MMM/yyyy HH:mm:ss", "dd/MMM/yyyy HH:mm",
+ "dd/MMM/yyyy", "dd.MMM.yyyy HH:mm:ss", "dd.MMM.yyyy",
+ "MMM-dd-yyyy HH:mm:ss", "MMM dd yyyy HH:mm:ss",
+ "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm",
+ "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "MM/dd/yyyy HH:mm:ss",
+ "MM/dd/yyyy hh:mm AP", "MM/dd/yyyy", "dd-MM-yyyy HH:mm:ss",
+ "dd-MM-yyyy HH:mm", "dd-MM-yyyy", "dd.MM.yyyy HH:mm:ss",
+ "dd.MM.yyyy", "MMMM d, yyyy h:mm AP", "MMMM d, yyyy",
+ "MMM d, yyyy", "ddd MMM d HH:mm:ss yyyy", "yyyyMMddHHmmss",
+ "yyyyMMdd", "yyyy-MM-dd", "dd MMM yyyy",
+ };
+ return f;
+}
+
+// Pure 10-13 digit integer -> unix epoch (seconds, or ms downscaled). -1 otherwise.
+qint64 try_epoch(const QString& t) {
+ static const QRegularExpression re("^\\d{10,13}$");
+ if (!re.match(t).hasMatch())
+ return -1;
+ bool ok = false;
+ qint64 v = t.toLongLong(&ok);
+ if (!ok)
+ return -1;
+ if (t.size() >= 13)
+ v /= 1000; // milliseconds -> seconds
+ return v;
+}
+
+} // namespace
+
+qint64 parse_feed_datetime(const QString& text_in, QString& display, const QString& fmt) {
+ const QString text = text_in.trimmed();
+ if (text.isEmpty()) {
+ display.clear();
+ return 0;
+ }
+
+ auto finish = [&](const QDateTime& d) -> qint64 {
+ display = d.toLocalTime().toString("MMM dd, yyyy HH:mm");
+ return d.toSecsSinceEpoch();
+ };
+
+ QDateTime dt;
+
+ // 1. Explicit user-provided format (locale-independent).
+ if (!fmt.isEmpty()) {
+ dt = QLocale::c().toDateTime(text, fmt);
+ if (dt.isValid())
+ return finish(dt);
+ }
+
+ // 2. Unix epoch (seconds or milliseconds).
+ const qint64 ep = try_epoch(text);
+ if (ep >= 0)
+ return finish(QDateTime::fromSecsSinceEpoch(ep));
+
+ // 3. RFC 2822 (RSS) and ISO 8601 (Atom) — locale-independent, keep the offset.
+ dt = QDateTime::fromString(text, Qt::RFC2822Date);
+ if (dt.isValid())
+ return finish(dt);
+ dt = QDateTime::fromString(text, Qt::ISODate);
+ if (dt.isValid())
+ return finish(dt);
+ dt = QDateTime::fromString(text, Qt::ISODateWithMs);
+ if (dt.isValid())
+ return finish(dt);
+
+ // 4. Named timezone -> numeric offset, then retry RFC2822 (preserves offset).
+ {
+ static const QRegularExpression tzRe("\\s+([A-Za-z]{2,5})$");
+ const auto m = tzRe.match(text);
+ if (m.hasMatch() && zone_offsets().contains(m.captured(1).toUpper())) {
+ const QString repl = text.left(m.capturedStart(0)).trimmed() + " " + zone_offsets().value(m.captured(1).toUpper());
+ dt = QDateTime::fromString(repl, Qt::RFC2822Date);
+ if (dt.isValid())
+ return finish(dt);
+ }
+ }
+
+ // 5. Strip timezone cruft and try the explicit-format battery (C locale).
+ QString core = text;
+ core.remove(QRegularExpression("\\s*\\([^)]*\\)\\s*$")); // "(UTC)"
+ core.remove(QRegularExpression("\\s*(Z|[+-]\\d{2}:?\\d{2})\\s*$")); // trailing offset / Z
+ { // trailing known zone abbrev (not AM/PM)
+ static const QRegularExpression zr("\\s+([A-Za-z]{2,5})$");
+ const auto m = zr.match(core);
+ if (m.hasMatch() && zone_offsets().contains(m.captured(1).toUpper()))
+ core = core.left(m.capturedStart(0)).trimmed();
+ }
+ core = core.trimmed();
+ for (const QString& f : fallback_formats()) {
+ dt = QLocale::c().toDateTime(core, f);
+ if (dt.isValid())
+ return finish(dt);
+ }
+
+ // 6. Last resort: pull a leading ISO date out (date-only, local midnight).
+ static const QRegularExpression isoLead("(\\d{4})-(\\d{2})-(\\d{2})");
+ const auto im = isoLead.match(text);
+ if (im.hasMatch()) {
+ const QDate d(im.captured(1).toInt(), im.captured(2).toInt(), im.captured(3).toInt());
+ if (d.isValid())
+ return finish(QDateTime(d, QTime(0, 0)));
+ }
+
+ display = text.left(22);
+ return 0;
+}
+
+bool looks_like_html(const QByteArray& body) {
+ const QByteArray head = body.trimmed().left(64).toLower();
+ return head.contains("<html") || head.contains("<!doctype html");
+}
+
+FeedFormat sniff_format(const QByteArray& body) {
+ const QByteArray t = body.trimmed();
+ if (t.isEmpty())
+ return FeedFormat::Auto;
+ const char c = t.front();
+ if (c == '{' || c == '[')
+ return FeedFormat::Json;
+ if (c == '<') {
+ const QByteArray low = t.left(512).toLower();
+ if (low.contains("<feed"))
+ return FeedFormat::Atom;
+ if (low.contains("<rss") || low.contains("<rdf"))
+ return FeedFormat::Rss;
+ if (looks_like_html(body))
+ return FeedFormat::Html;
+ return FeedFormat::Xml;
+ }
+ const qsizetype nl = t.indexOf('\n');
+ const QByteArray firstLine = nl >= 0 ? t.left(nl) : t;
+ if (firstLine.contains(',') || firstLine.contains('\t'))
+ return FeedFormat::Csv;
+ return FeedFormat::Auto;
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedParseUtil.h b/fincept-qt/src/services/feeds/FeedParseUtil.h
new file mode 100644
index 000000000..8b3dffd2b
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedParseUtil.h
@@ -0,0 +1,23 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+
+#include <QByteArray>
+#include <QString>
+
+namespace fincept::feeds {
+
+/// Strip HTML tags + collapse whitespace + unescape common entities; cap length.
+QString strip_html(const QString& in, int max_chars = 300);
+
+/// Parse a feed timestamp through the RSS/Atom format cascade (optional explicit
+/// `fmt`, then RFC2822, ISO, "ddd, dd MMM yyyy HH:mm:ss"). Returns epoch secs and
+/// fills `display` ("MMM dd, HH:mm"); returns 0 if unparseable.
+qint64 parse_feed_datetime(const QString& text, QString& display, const QString& fmt = {});
+
+/// True if the body looks like an HTML page (access-denied / captcha), not a feed.
+bool looks_like_html(const QByteArray& body);
+
+/// Sniff the format from raw bytes (used when sub.format == Auto).
+FeedFormat sniff_format(const QByteArray& body);
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedScraper.cpp b/fincept-qt/src/services/feeds/FeedScraper.cpp
new file mode 100644
index 000000000..35335ca39
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedScraper.cpp
@@ -0,0 +1,503 @@
+#include "services/feeds/FeedScraper.h"
+
+#include "services/feeds/FeedParseUtil.h"
+
+#include <QCryptographicHash>
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QXmlStreamReader>
+
+#include <functional>
+#include <initializer_list>
+
+namespace fincept::feeds {
+
+namespace {
+
+constexpr int kSampleMax = 60;
+
+QString make_id(const QString& feed_id, const FeedItem& it) {
+ const QString basis = feed_id + "|" + (it.link.isEmpty() ? it.title : it.link);
+ return QString::fromLatin1(QCryptographicHash::hash(basis.toUtf8(), QCryptographicHash::Sha1).toHex());
+}
+
+// Resolve a JSON dot-path ("data.items" / "meta.url"). Returns the value or undefined.
+QJsonValue json_path(const QJsonValue& root, const QString& path) {
+ if (path.isEmpty())
+ return root;
+ QJsonValue cur = root;
+ for (const QString& key : path.split('.', Qt::SkipEmptyParts)) {
+ if (cur.isObject())
+ cur = cur.toObject().value(key);
+ else
+ return QJsonValue::Undefined;
+ }
+ return cur;
+}
+
+QString json_str(const QJsonValue& v) {
+ if (v.isString())
+ return v.toString();
+ if (v.isDouble())
+ return QString::number(v.toDouble());
+ if (v.isBool())
+ return v.toBool() ? QStringLiteral("true") : QStringLiteral("false");
+ if (v.isArray())
+ return QStringLiteral("[…]");
+ if (v.isObject())
+ return QStringLiteral("{…}");
+ return {};
+}
+
+// Apply a subscription's manual mapping to one record, given a value extractor.
+// Roles drive the card view (title/summary/link/time); other fields become table
+// columns. Returns false if the record produced nothing useful.
+bool build_mapped_item(const FeedSubscription& sub, const std::function<QString(const QString&)>& get, FeedItem& it) {
+ it = {};
+ it.source = sub.name;
+ for (const auto& f : sub.mapping.fields) {
+ const QString val = get(f.path);
+ if (f.role == "title")
+ it.title = val.left(300);
+ else if (f.role == "summary")
+ it.summary = strip_html(val);
+ else if (f.role == "link")
+ it.link = val;
+ else if (f.role == "time")
+ it.sort_ts = parse_feed_datetime(val, it.time, sub.mapping.time_format);
+ else if (!f.label.isEmpty())
+ it.fields.insert(f.label, val);
+ }
+ if (it.title.isEmpty() && it.link.isEmpty() && it.fields.isEmpty())
+ return false;
+ if (it.time.isEmpty())
+ it.time = QDateTime::currentDateTime().toString("MMM dd, HH:mm");
+ if (it.sort_ts == 0)
+ it.sort_ts = QDateTime::currentSecsSinceEpoch();
+ it.id = make_id(sub.id, it);
+ return true;
+}
+
+} // namespace
+
+QVector<FeedItem> FeedScraper::parse(const QByteArray& body, const FeedSubscription& sub) {
+ if (looks_like_html(body))
+ return {}; // caller surfaces access-denied as Error
+
+ FeedFormat fmt = sub.format;
+ if (fmt == FeedFormat::Auto)
+ fmt = sniff_format(body);
+
+ if (sub.parse_mode == ParseMode::Manual) {
+ switch (fmt) {
+ case FeedFormat::Json: return parse_json(body, sub);
+ case FeedFormat::Csv: return parse_csv(body, sub);
+ default: return parse_xml_manual(body, sub); // rss/atom/xml all element-based
+ }
+ }
+ switch (fmt) {
+ case FeedFormat::Json: return parse_json(body, sub);
+ case FeedFormat::Csv: return parse_csv(body, sub);
+ case FeedFormat::Html: return {}; // auto HTML table extraction out of scope for v1 auto mode
+ default: return parse_rss_atom(body, sub);
+ }
+}
+
+// ── Auto RSS/Atom (ported from NewsService::parse_rss_xml, emitting FeedItem) ──
+QVector<FeedItem> FeedScraper::parse_rss_atom(const QByteArray& xml, const FeedSubscription& sub) {
+ QVector<FeedItem> items;
+ QXmlStreamReader reader(xml);
+ bool in_item = false;
+ FeedItem cur;
+ QString tag;
+
+ while (!reader.atEnd()) {
+ const auto token = reader.readNext();
+ if (token == QXmlStreamReader::StartElement) {
+ tag = reader.name().toString();
+ if (tag == "item" || tag == "entry") {
+ in_item = true;
+ cur = {};
+ cur.source = sub.name;
+ }
+ if (in_item && tag == "link") {
+ const auto href = reader.attributes().value("href").toString();
+ const auto rel = reader.attributes().value("rel").toString();
+ if (!href.isEmpty() && (rel.isEmpty() || rel == "alternate") && cur.link.isEmpty())
+ cur.link = href;
+ }
+ } else if (token == QXmlStreamReader::Characters && in_item) {
+ const QString text = reader.text().toString().trimmed();
+ if (text.isEmpty())
+ continue;
+ if (tag == "title" && cur.title.isEmpty()) {
+ cur.title = text.left(200);
+ } else if ((tag == "description" || tag == "summary" || tag == "encoded") && cur.summary.isEmpty()) {
+ cur.summary = strip_html(text);
+ } else if (tag == "link" && cur.link.isEmpty()) {
+ cur.link = text;
+ } else if ((tag == "guid" || tag == "id") && cur.link.isEmpty() && text.startsWith("http")) {
+ cur.link = text;
+ } else if (tag == "pubDate" || tag == "published" || tag == "updated" || tag == "date") {
+ if (cur.sort_ts == 0)
+ cur.sort_ts = parse_feed_datetime(text, cur.time);
+ }
+ } else if (token == QXmlStreamReader::EndElement) {
+ const QString end = reader.name().toString();
+ if ((end == "item" || end == "entry") && in_item) {
+ in_item = false;
+ if (cur.title.isEmpty())
+ continue;
+ if (cur.time.isEmpty())
+ cur.time = QDateTime::currentDateTime().toString("MMM dd, HH:mm");
+ if (cur.sort_ts == 0)
+ cur.sort_ts = QDateTime::currentSecsSinceEpoch();
+ cur.id = make_id(sub.id, cur);
+ items.append(std::move(cur));
+ }
+ }
+ }
+ return items;
+}
+
+// ── Manual XML: read each item_selector element into a tag bucket, then map ──
+QVector<FeedItem> FeedScraper::parse_xml_manual(const QByteArray& xml, const FeedSubscription& sub) {
+ const QString itemTag = sub.mapping.item_selector.isEmpty() ? QStringLiteral("item") : sub.mapping.item_selector;
+ QVector<FeedItem> items;
+ QXmlStreamReader reader(xml);
+ bool in_item = false;
+ QHash<QString, QString> bucket; // element-name (or name@attr / @attr) -> text
+
+ QString tag;
+ while (!reader.atEnd()) {
+ const auto token = reader.readNext();
+ if (token == QXmlStreamReader::StartElement) {
+ tag = reader.name().toString();
+ if (tag == itemTag) {
+ in_item = true;
+ bucket.clear();
+ for (const auto& a : reader.attributes())
+ bucket.insert("@" + a.name().toString(), a.value().toString());
+ } else if (in_item) {
+ for (const auto& a : reader.attributes())
+ bucket.insert(tag + "@" + a.name().toString(), a.value().toString());
+ }
+ } else if (token == QXmlStreamReader::Characters && in_item) {
+ const QString text = reader.text().toString().trimmed();
+ if (!text.isEmpty() && tag != itemTag && !bucket.contains(tag))
+ bucket.insert(tag, text);
+ } else if (token == QXmlStreamReader::EndElement) {
+ if (reader.name().toString() == itemTag && in_item) {
+ in_item = false;
+ FeedItem it;
+ if (build_mapped_item(sub, [&](const QString& p) { return bucket.value(p); }, it))
+ items.append(std::move(it));
+ }
+ }
+ }
+ return items;
+}
+
+// ── JSON: auto maps common keys; manual applies sub.mapping ──
+QVector<FeedItem> FeedScraper::parse_json(const QByteArray& body, const FeedSubscription& sub) {
+ QJsonParseError err;
+ const QJsonDocument doc = QJsonDocument::fromJson(body, &err);
+ if (err.error != QJsonParseError::NoError)
+ return {};
+
+ const bool manual = sub.parse_mode == ParseMode::Manual;
+ const QJsonValue root = doc.isArray() ? QJsonValue(doc.array()) : QJsonValue(doc.object());
+ QJsonValue arrVal =
+ manual && !sub.mapping.item_selector.isEmpty() ? json_path(root, sub.mapping.item_selector) : root;
+ if (!arrVal.isArray() && doc.isObject()) {
+ for (const char* k : {"items", "data", "results", "articles", "entries"}) {
+ const QJsonValue v = doc.object().value(QLatin1String(k));
+ if (v.isArray()) {
+ arrVal = v;
+ break;
+ }
+ }
+ }
+ if (!arrVal.isArray())
+ return {};
+
+ QVector<FeedItem> items;
+ for (const auto& v : arrVal.toArray()) {
+ if (!v.isObject())
+ continue;
+ const QJsonObject o = v.toObject();
+ FeedItem it;
+ if (manual) {
+ if (build_mapped_item(sub, [&](const QString& p) { return json_str(json_path(o, p)); }, it))
+ items.append(std::move(it));
+ continue;
+ }
+ // Auto: map common keys.
+ auto pick = [&](std::initializer_list<const char*> defs) -> QString {
+ for (const char* d : defs) {
+ const auto val = o.value(QLatin1String(d));
+ if (!val.isUndefined())
+ return json_str(val);
+ }
+ return {};
+ };
+ it.source = sub.name;
+ it.title = pick({"title", "headline", "name"});
+ it.summary = strip_html(pick({"summary", "description", "abstract"}));
+ it.link = pick({"url", "link", "href"});
+ const QString ts = pick({"published", "date", "pubDate", "created_at", "time"});
+ if (!ts.isEmpty())
+ it.sort_ts = parse_feed_datetime(ts, it.time);
+ if (it.title.isEmpty())
+ continue;
+ if (it.time.isEmpty())
+ it.time = QDateTime::currentDateTime().toString("MMM dd, HH:mm");
+ if (it.sort_ts == 0)
+ it.sort_ts = QDateTime::currentSecsSinceEpoch();
+ it.id = make_id(sub.id, it);
+ items.append(std::move(it));
+ }
+ return items;
+}
+
+// ── CSV: header row -> columns; auto = all columns; manual = mapped ──
+QVector<FeedItem> FeedScraper::parse_csv(const QByteArray& body, const FeedSubscription& sub) {
+ const QString text = QString::fromUtf8(body);
+ const QStringList lines = text.split('\n', Qt::SkipEmptyParts);
+ if (lines.size() < 2)
+ return {};
+ const QChar delim = lines.first().contains('\t') ? QChar('\t') : QChar(',');
+ const QStringList headers = lines.first().split(delim);
+ const bool manual = sub.parse_mode == ParseMode::Manual;
+
+ auto col_index = [&](const QString& path) -> int {
+ if (path.isEmpty())
+ return -1;
+ if (path.startsWith('#'))
+ return path.mid(1).toInt();
+ return headers.indexOf(path);
+ };
+
+ QVector<FeedItem> items;
+ for (int r = 1; r < lines.size(); ++r) {
+ const QStringList cells = lines[r].split(delim);
+ auto cell = [&](int i) { return (i >= 0 && i < cells.size()) ? cells[i].trimmed() : QString(); };
+ FeedItem it;
+ if (manual) {
+ if (build_mapped_item(sub, [&](const QString& p) { return cell(col_index(p)); }, it))
+ items.append(std::move(it));
+ continue;
+ }
+ it.source = sub.name;
+ it.title = cell(0);
+ for (int c = 0; c < headers.size() && c < cells.size(); ++c)
+ it.fields.insert(headers[c].trimmed(), cell(c));
+ if (it.title.isEmpty() && it.fields.isEmpty())
+ continue;
+ it.time = QDateTime::currentDateTime().toString("MMM dd, HH:mm");
+ it.sort_ts = QDateTime::currentSecsSinceEpoch();
+ it.id = make_id(sub.id, it);
+ items.append(std::move(it));
+ }
+ return items;
+}
+
+// ════════════════════════════ Discovery ════════════════════════════════════════
+
+DiscoveredSchema FeedScraper::discover(const QByteArray& body, const FeedSubscription& sub) {
+ if (looks_like_html(body))
+ return {};
+ FeedFormat fmt = sub.format;
+ if (fmt == FeedFormat::Auto)
+ fmt = sniff_format(body);
+ switch (fmt) {
+ case FeedFormat::Json: return discover_json(body, sub);
+ case FeedFormat::Csv: return discover_csv(body);
+ case FeedFormat::Html: return {};
+ default: return discover_xml(body);
+ }
+}
+
+DiscoveredSchema FeedScraper::discover_xml(const QByteArray& xml) {
+ DiscoveredSchema s;
+
+ // Pass 1: count element occurrences + first-seen depth to find the repeating record.
+ QHash<QString, int> count;
+ QHash<QString, int> firstDepth;
+ QStringList order;
+ bool sawFeedRoot = false;
+ bool sawRssRoot = false;
+ {
+ QXmlStreamReader r(xml);
+ int depth = 0;
+ while (!r.atEnd()) {
+ const auto t = r.readNext();
+ if (t == QXmlStreamReader::StartElement) {
+ ++depth;
+ const QString n = r.name().toString();
+ if (n == "feed")
+ sawFeedRoot = true;
+ if (n == "rss" || n == "rdf" || n == "RDF")
+ sawRssRoot = true;
+ if (!count.contains(n)) {
+ firstDepth[n] = depth;
+ order << n;
+ }
+ ++count[n];
+ } else if (t == QXmlStreamReader::EndElement) {
+ --depth;
+ }
+ }
+ }
+
+ QStringList cands;
+ for (const QString& n : order)
+ if (count.value(n) >= 2 && firstDepth.value(n) >= 2)
+ cands << n;
+
+ QString item;
+ if (cands.contains("item"))
+ item = "item";
+ else if (cands.contains("entry"))
+ item = "entry";
+ else if (!cands.isEmpty()) {
+ item = cands.first();
+ int best = firstDepth.value(item);
+ for (const QString& n : cands)
+ if (firstDepth.value(n) < best) {
+ best = firstDepth.value(n);
+ item = n;
+ }
+ } else {
+ for (const QString& n : order)
+ if (firstDepth.value(n) == 2) {
+ item = n;
+ break;
+ }
+ }
+
+ s.format = sawFeedRoot ? "atom" : (sawRssRoot ? "rss" : "xml");
+ s.item_selector = item;
+ s.item_options = cands.isEmpty() ? order : cands;
+ if (item.isEmpty())
+ return s;
+
+ // Pass 2: collect the chosen record's child tags + attributes (first occurrence).
+ QStringList fieldOrder;
+ QHash<QString, QString> sample;
+ auto addF = [&](const QString& p, const QString& v) {
+ if (p.isEmpty())
+ return;
+ if (!sample.contains(p)) {
+ fieldOrder << p;
+ sample[p] = v.left(kSampleMax);
+ }
+ };
+ {
+ QXmlStreamReader r(xml);
+ bool in = false;
+ bool done = false;
+ QString tag;
+ while (!r.atEnd() && !done) {
+ const auto t = r.readNext();
+ if (t == QXmlStreamReader::StartElement) {
+ tag = r.name().toString();
+ if (tag == item) {
+ in = true;
+ for (const auto& a : r.attributes())
+ addF("@" + a.name().toString(), a.value().toString());
+ } else if (in) {
+ for (const auto& a : r.attributes())
+ addF(tag + "@" + a.name().toString(), a.value().toString());
+ }
+ } else if (t == QXmlStreamReader::Characters && in) {
+ const QString txt = r.text().toString().trimmed();
+ if (!txt.isEmpty() && tag != item)
+ addF(tag, txt);
+ } else if (t == QXmlStreamReader::EndElement) {
+ if (r.name().toString() == item && in)
+ done = true;
+ }
+ }
+ }
+ for (const QString& p : fieldOrder)
+ s.fields.append({p, sample.value(p)});
+ s.ok = !s.fields.isEmpty();
+ return s;
+}
+
+DiscoveredSchema FeedScraper::discover_json(const QByteArray& body, const FeedSubscription& sub) {
+ DiscoveredSchema s;
+ s.format = "json";
+ QJsonParseError e;
+ const QJsonDocument doc = QJsonDocument::fromJson(body, &e);
+ if (e.error != QJsonParseError::NoError)
+ return s;
+
+ QJsonArray arr;
+ QString path;
+ if (doc.isArray()) {
+ arr = doc.array();
+ } else {
+ const QJsonObject obj = doc.object();
+ QStringList tryKeys{"items", "data", "results", "articles", "entries"};
+ for (auto it = obj.begin(); it != obj.end(); ++it)
+ if (it.value().isArray() && !tryKeys.contains(it.key()))
+ tryKeys << it.key();
+ for (const QString& k : tryKeys) {
+ if (obj.value(k).isArray()) {
+ arr = obj.value(k).toArray();
+ path = k;
+ s.item_options << k;
+ break;
+ }
+ }
+ }
+ // Honour an explicit override if the user already picked an array path.
+ if (!sub.mapping.item_selector.isEmpty()) {
+ const QJsonValue v = json_path(doc.isArray() ? QJsonValue(doc.array()) : QJsonValue(doc.object()),
+ sub.mapping.item_selector);
+ if (v.isArray()) {
+ arr = v.toArray();
+ path = sub.mapping.item_selector;
+ }
+ }
+ s.item_selector = path;
+ if (!path.isEmpty() && !s.item_options.contains(path))
+ s.item_options << path;
+ if (arr.isEmpty())
+ return s;
+
+ const QJsonObject first = arr.first().toObject();
+ for (auto it = first.begin(); it != first.end(); ++it) {
+ if (it.value().isObject()) {
+ const QJsonObject sub2 = it.value().toObject();
+ for (auto j = sub2.begin(); j != sub2.end(); ++j)
+ s.fields.append({it.key() + "." + j.key(), json_str(j.value()).left(kSampleMax)});
+ } else {
+ s.fields.append({it.key(), json_str(it.value()).left(kSampleMax)});
+ }
+ }
+ s.ok = !s.fields.isEmpty();
+ return s;
+}
+
+DiscoveredSchema FeedScraper::discover_csv(const QByteArray& body) {
+ DiscoveredSchema s;
+ s.format = "csv";
+ const QString text = QString::fromUtf8(body);
+ const QStringList lines = text.split('\n', Qt::SkipEmptyParts);
+ if (lines.isEmpty())
+ return s;
+ const QChar delim = lines.first().contains('\t') ? QChar('\t') : QChar(',');
+ const QStringList headers = lines.first().split(delim);
+ const QStringList firstRow = lines.size() > 1 ? lines[1].split(delim) : QStringList();
+ for (int i = 0; i < headers.size(); ++i)
+ s.fields.append({headers[i].trimmed(), i < firstRow.size() ? firstRow[i].trimmed().left(kSampleMax) : QString()});
+ s.ok = !s.fields.isEmpty();
+ return s;
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedScraper.h b/fincept-qt/src/services/feeds/FeedScraper.h
new file mode 100644
index 000000000..9b8642017
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedScraper.h
@@ -0,0 +1,47 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+
+#include <QByteArray>
+#include <QStringList>
+#include <QVector>
+
+namespace fincept::feeds {
+
+/// A source tag found by discovery, with a sample value to help the user choose.
+struct DiscoveredField {
+ QString path; // tag path the parser understands (element / json key / csv header)
+ QString sample; // first observed value (truncated), for preview
+};
+
+/// The structure auto-detected from one fetch of a feed — used to populate the
+/// manual-mapping UI so the user just picks tags instead of typing paths.
+struct DiscoveredSchema {
+ bool ok = false;
+ QString format; // "rss" | "atom" | "xml" | "json" | "csv"
+ QString item_selector; // best-guess repeating record (XML element / JSON array path)
+ QStringList item_options; // candidate repeating records the user can switch to
+ QVector<DiscoveredField> fields;
+};
+
+/// Stateless parser: raw bytes + a subscription -> feed items.
+/// Auto mode sniffs the format and maps obvious fields; Manual mode applies sub.mapping.
+class FeedScraper {
+ public:
+ static QVector<FeedItem> parse(const QByteArray& body, const FeedSubscription& sub);
+
+ /// Probe one fetched body and report its repeating record + available tags so the
+ /// manual-mapping UI can be filled in by selection rather than typing.
+ static DiscoveredSchema discover(const QByteArray& body, const FeedSubscription& sub);
+
+ private:
+ static QVector<FeedItem> parse_rss_atom(const QByteArray& xml, const FeedSubscription& sub);
+ static QVector<FeedItem> parse_json(const QByteArray& body, const FeedSubscription& sub);
+ static QVector<FeedItem> parse_csv(const QByteArray& body, const FeedSubscription& sub);
+ static QVector<FeedItem> parse_xml_manual(const QByteArray& xml, const FeedSubscription& sub);
+
+ static DiscoveredSchema discover_xml(const QByteArray& xml);
+ static DiscoveredSchema discover_json(const QByteArray& body, const FeedSubscription& sub);
+ static DiscoveredSchema discover_csv(const QByteArray& body);
+};
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedSelfTest.cpp b/fincept-qt/src/services/feeds/FeedSelfTest.cpp
new file mode 100644
index 000000000..7d8496861
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedSelfTest.cpp
@@ -0,0 +1,149 @@
+#include "services/feeds/FeedSelfTest.h"
+
+#include "services/feeds/FeedParseUtil.h"
+#include "services/feeds/FeedScraper.h"
+#include "services/feeds/FeedTypes.h"
+
+#include <QDateTime>
+#include <QString>
+
+#include <cstdio>
+
+namespace fincept::feeds {
+
+int run_feed_selftest() {
+ int failures = 0;
+ auto check = [&](const char* label, bool ok) {
+ std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", label);
+ if (!ok)
+ ++failures;
+ };
+
+ { // RSS 2.0 auto
+ FeedSubscription s;
+ s.id = "t1";
+ s.name = "RSS";
+ s.format = FeedFormat::Auto;
+ const QByteArray rss = "<?xml version=\"1.0\"?><rss version=\"2.0\"><channel>"
+ "<item><title>Hello</title><link>http://x/1</link>"
+ "<description>&lt;b&gt;Body&lt;/b&gt;</description>"
+ "<pubDate>Wed, 04 Jun 2025 10:00:00 GMT</pubDate></item>"
+ "<item><title>World</title><link>http://x/2</link></item>"
+ "</channel></rss>";
+ const auto items = FeedScraper::parse(rss, s);
+ check("rss: 2 items", items.size() == 2);
+ check("rss: title", !items.isEmpty() && items[0].title == "Hello");
+ check("rss: html stripped", !items.isEmpty() && items[0].summary == "Body");
+ }
+ { // Atom auto
+ FeedSubscription s;
+ s.id = "t2";
+ s.name = "Atom";
+ s.format = FeedFormat::Auto;
+ const QByteArray atom = "<?xml version=\"1.0\"?><feed xmlns=\"http://www.w3.org/2005/Atom\">"
+ "<entry><title>AT</title><link rel=\"alternate\" href=\"http://a/1\"/>"
+ "<summary>S</summary><updated>2025-06-04T10:00:00Z</updated></entry></feed>";
+ const auto items = FeedScraper::parse(atom, s);
+ check("atom: 1 item", items.size() == 1);
+ check("atom: link href", !items.isEmpty() && items[0].link == "http://a/1");
+ }
+ { // JSON auto (items[] container)
+ FeedSubscription s;
+ s.id = "t3";
+ s.name = "JSON";
+ s.format = FeedFormat::Auto;
+ const QByteArray json = R"({"items":[{"title":"J1","url":"http://j/1"},{"title":"J2"}]})";
+ const auto items = FeedScraper::parse(json, s);
+ check("json: 2 items", items.size() == 2);
+ check("json: link from url", !items.isEmpty() && items[0].link == "http://j/1");
+ }
+ { // CSV auto
+ FeedSubscription s;
+ s.id = "t4";
+ s.name = "CSV";
+ s.format = FeedFormat::Csv;
+ const QByteArray csv = "name,price\nAAPL,200\nMSFT,410\n";
+ const auto items = FeedScraper::parse(csv, s);
+ check("csv: 2 rows", items.size() == 2);
+ check("csv: field price", !items.isEmpty() && items[0].fields.value("price") == "200");
+ }
+ const QByteArray custom_xml =
+ "<data><record><headline>H1</headline><url>http://m/1</url><sym>ABC</sym></record>"
+ "<record><headline>H2</headline><url>http://m/2</url><sym>XYZ</sym></record></data>";
+
+ { // Manual XML mapping (role-based field list)
+ FeedSubscription s;
+ s.id = "t5";
+ s.name = "Manual";
+ s.format = FeedFormat::Xml;
+ s.parse_mode = ParseMode::Manual;
+ s.mapping.item_selector = "record";
+ s.mapping.fields = {
+ {"Title", "headline", "title"},
+ {"Link", "url", "link"},
+ {"Ticker", "sym", ""},
+ };
+ const auto items = FeedScraper::parse(custom_xml, s);
+ check("manual: 2 records", items.size() == 2);
+ check("manual: mapped title role", !items.isEmpty() && items[0].title == "H1");
+ check("manual: mapped link role", !items.isEmpty() && items[0].link == "http://m/1");
+ check("manual: extra column", !items.isEmpty() && items[0].fields.value("Ticker") == "ABC");
+ }
+ { // Field discovery on the same custom XML
+ FeedSubscription s;
+ s.id = "t5d";
+ s.format = FeedFormat::Xml;
+ const auto schema = FeedScraper::discover(custom_xml, s);
+ check("discover: ok", schema.ok);
+ check("discover: item selector", schema.item_selector == "record");
+ QStringList paths;
+ for (const auto& f : schema.fields)
+ paths << f.path;
+ check("discover: found headline", paths.contains("headline"));
+ check("discover: found sym", paths.contains("sym"));
+ }
+ { // Field discovery on JSON
+ FeedSubscription s;
+ s.id = "t5j";
+ s.format = FeedFormat::Json;
+ const QByteArray json = R"({"results":[{"hl":"X","u":"http://k/1","t":"2025-01-01"}]})";
+ const auto schema = FeedScraper::discover(json, s);
+ check("discover json: ok", schema.ok);
+ check("discover json: array path", schema.item_selector == "results");
+ QStringList paths;
+ for (const auto& f : schema.fields)
+ paths << f.path;
+ check("discover json: keys", paths.contains("hl") && paths.contains("u"));
+ }
+ { // HTML access-denied guard
+ FeedSubscription s;
+ s.id = "t6";
+ s.name = "HTML";
+ s.format = FeedFormat::Auto;
+ const auto items = FeedScraper::parse("<!doctype html><html><body>nope</body></html>", s);
+ check("html: zero items (guarded)", items.isEmpty());
+ }
+ { // Date/time parsing across real-world pubDate formats
+ const qint64 ref = QDateTime::fromString("2025-06-04T10:00:00Z", Qt::ISODate).toSecsSinceEpoch();
+ QString disp;
+ check("date rfc822 GMT", parse_feed_datetime("Wed, 04 Jun 2025 10:00:00 GMT", disp) == ref);
+ check("date rfc822 +0000", parse_feed_datetime("Wed, 04 Jun 2025 10:00:00 +0000", disp) == ref);
+ check("date rfc822 no-day", parse_feed_datetime("04 Jun 2025 10:00:00 +0000", disp) == ref);
+ check("date iso Z", parse_feed_datetime("2025-06-04T10:00:00Z", disp) == ref);
+ check("date iso ms Z", parse_feed_datetime("2025-06-04T10:00:00.000Z", disp) == ref);
+ check("date iso offset", parse_feed_datetime("2025-06-04T15:30:00+05:30", disp) == ref);
+ check("date rfc822 EDT", parse_feed_datetime("Wed, 04 Jun 2025 06:00:00 EDT", disp) == ref);
+ check("date epoch sec", parse_feed_datetime("1717495200", disp) == 1717495200);
+ check("date epoch ms", parse_feed_datetime("1717495200000", disp) == 1717495200);
+ check("date space sep (parsed)", parse_feed_datetime("2025-06-04 10:00:00", disp) != 0);
+ check("date date-only (parsed)", parse_feed_datetime("2025-06-04", disp) != 0);
+ check("date dd-MMM-yyyy HH:mm:ss", parse_feed_datetime("05-Jun-2026 14:35:36", disp) != 0);
+ check("date dd/MMM/yyyy", parse_feed_datetime("05/Jun/2026", disp) != 0);
+ check("date garbage -> 0", parse_feed_datetime("not a date", disp) == 0);
+ }
+
+ std::printf("\nfeed selftest: %s (%d failures)\n", failures == 0 ? "OK" : "FAILED", failures);
+ return failures == 0 ? 0 : 1;
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedSelfTest.h b/fincept-qt/src/services/feeds/FeedSelfTest.h
new file mode 100644
index 000000000..816bea47e
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedSelfTest.h
@@ -0,0 +1,6 @@
+#pragma once
+namespace fincept::feeds {
+/// Runs FeedScraper over canned RSS/Atom/JSON/CSV blobs and prints PASS/FAIL
+/// counts to stdout. Returns process exit code (0 = all pass). No GUI/network.
+int run_feed_selftest();
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/feeds/FeedTypes.h b/fincept-qt/src/services/feeds/FeedTypes.h
new file mode 100644
index 000000000..78debcc3d
--- /dev/null
+++ b/fincept-qt/src/services/feeds/FeedTypes.h
@@ -0,0 +1,160 @@
+#pragma once
+// Generalized feed subsystem — shared value types.
+// Plain data; no Qt widget or equity dependency (engine is reusable across screens).
+
+#include <QHash>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QString>
+#include <QVector>
+
+#include <utility>
+
+namespace fincept::feeds {
+
+enum class ParseMode { Auto, Manual };
+enum class FeedFormat { Auto, Rss, Atom, Xml, Json, Csv, Html };
+enum class DisplayMode { Cards, Table };
+enum class FeedStatus { Idle, Fetching, Ok, Error };
+
+/// One mapped field: an output column with a display `label`, sourced from `path`
+/// (a discovered feed tag), with an optional semantic `role`. Roles drive the card
+/// view; role == "" means a plain extra column shown only in the table view.
+/// path syntax (auto-filled by discovery, rarely typed by hand):
+/// XML : element name, optional "@attr" (e.g. "guid", "link@href")
+/// JSON: dot-path (e.g. "meta.url")
+/// CSV : header name, or "#<index>" (0-based)
+struct MappedField {
+ QString label; // display column name
+ QString path; // source tag/path
+ QString role; // "" | "title" | "summary" | "link" | "time"
+};
+
+/// Manual field mapping — an unlimited, user-editable list of MappedFields plus the
+/// repeating-record selector. Populated by auto-discovery (FeedScraper::discover).
+struct FieldMapping {
+ QString item_selector; // XML repeating element ("item"/"entry"/custom); JSON array path; CSV = ""
+ QString time_format; // optional QDateTime format hint for the "time" role
+ QVector<MappedField> fields;
+
+ /// Source path for the field tagged with `role`, or empty if none.
+ QString role_path(const QString& role) const {
+ for (const auto& f : fields)
+ if (f.role == role)
+ return f.path;
+ return {};
+ }
+
+ QJsonObject to_json() const {
+ QJsonObject o;
+ o["item_selector"] = item_selector;
+ o["time_format"] = time_format;
+ QJsonArray arr;
+ for (const auto& f : fields) {
+ QJsonObject e;
+ e["label"] = f.label;
+ e["path"] = f.path;
+ e["role"] = f.role;
+ arr.append(e);
+ }
+ o["fields"] = arr;
+ return o;
+ }
+ static FieldMapping from_json(const QJsonObject& o) {
+ FieldMapping m;
+ m.item_selector = o["item_selector"].toString();
+ m.time_format = o["time_format"].toString();
+ if (o.contains("fields")) {
+ for (const auto& v : o["fields"].toArray()) {
+ const auto e = v.toObject();
+ m.fields.append({e["label"].toString(), e["path"].toString(), e["role"].toString()});
+ }
+ } else {
+ // Back-compat with the original fixed-field shape.
+ auto add = [&](const QString& role, const QString& path, const QString& label) {
+ if (!path.isEmpty())
+ m.fields.append({label, path, role});
+ };
+ add("title", o["title_path"].toString(), "Title");
+ add("summary", o["summary_path"].toString(), "Summary");
+ add("link", o["link_path"].toString(), "Link");
+ add("time", o["time_path"].toString(), "Time");
+ for (const auto& v : o["extra"].toArray()) {
+ const auto e = v.toObject();
+ add("", e["path"].toString(), e["label"].toString());
+ }
+ }
+ return m;
+ }
+};
+
+/// A user feed configuration row (persisted in feed_subscriptions).
+struct FeedSubscription {
+ QString id; // "feed-<uuid>"
+ QString name;
+ QString url;
+ int refresh_sec = 300;
+ ParseMode parse_mode = ParseMode::Auto;
+ FeedFormat format = FeedFormat::Auto;
+ FieldMapping mapping; // used when parse_mode == Manual
+ DisplayMode display_mode = DisplayMode::Cards;
+ QHash<QString, QString> headers; // extra request headers
+ bool enabled = true;
+ bool persist = true; // store fetched items in feed_items (offline cache + history)
+ int sort_order = 0;
+};
+
+/// One parsed record from a feed.
+struct FeedItem {
+ QString id; // stable: hash(feedId + (link|title))
+ QString title;
+ QString summary;
+ QString link;
+ QString source;
+ qint64 sort_ts = 0; // epoch secs; 0 = unknown
+ QString time; // display string
+ QHash<QString, QString> fields; // mapped extra columns (manual mode)
+};
+
+// String <-> enum helpers (stable storage tokens).
+inline QString to_token(ParseMode m) { return m == ParseMode::Manual ? "manual" : "auto"; }
+inline ParseMode parse_mode_from(const QString& s) { return s == "manual" ? ParseMode::Manual : ParseMode::Auto; }
+
+inline QString to_token(DisplayMode m) { return m == DisplayMode::Table ? "table" : "cards"; }
+inline DisplayMode display_mode_from(const QString& s) { return s == "table" ? DisplayMode::Table : DisplayMode::Cards; }
+
+inline QString to_token(FeedFormat f) {
+ switch (f) {
+ case FeedFormat::Rss: return "rss";
+ case FeedFormat::Atom: return "atom";
+ case FeedFormat::Xml: return "xml";
+ case FeedFormat::Json: return "json";
+ case FeedFormat::Csv: return "csv";
+ case FeedFormat::Html: return "html";
+ default: return "auto";
+ }
+}
+inline FeedFormat feed_format_from(const QString& s) {
+ if (s == "rss") return FeedFormat::Rss;
+ if (s == "atom") return FeedFormat::Atom;
+ if (s == "xml") return FeedFormat::Xml;
+ if (s == "json") return FeedFormat::Json;
+ if (s == "csv") return FeedFormat::Csv;
+ if (s == "html") return FeedFormat::Html;
+ return FeedFormat::Auto;
+}
+
+inline QJsonObject headers_to_json(const QHash<QString, QString>& h) {
+ QJsonObject o;
+ for (auto it = h.begin(); it != h.end(); ++it)
+ o[it.key()] = it.value();
+ return o;
+}
+inline QHash<QString, QString> headers_from_json(const QJsonObject& o) {
+ QHash<QString, QString> h;
+ for (auto it = o.begin(); it != o.end(); ++it)
+ h.insert(it.key(), it.value().toString());
+ return h;
+}
+
+} // namespace fincept::feeds
diff --git a/fincept-qt/src/services/llm/LlmContentExtractors.h b/fincept-qt/src/services/llm/LlmContentExtractors.h
index 9ec7fa8bb..f2554d6fc 100644
--- a/fincept-qt/src/services/llm/LlmContentExtractors.h
+++ b/fincept-qt/src/services/llm/LlmContentExtractors.h
@@ -3,12 +3,23 @@
// the response shapes of the OpenAI / Anthropic / Gemini APIs. No state, no
// I/O — just JSON walkers used by LlmService and its tool-loop follow-ups.
+#include <QByteArray>
#include <QJsonArray>
#include <QJsonObject>
#include <QString>
namespace fincept::ai_chat {
+/// Pull a human-readable error message out of an LLM provider's non-2xx HTTP
+/// body so callers can surface the *real* reason (bad model id, unsupported
+/// parameter, quota, …) instead of Qt's generic "server replied: Bad Request".
+/// Handles the shapes seen across OpenAI / AIHubMix / OpenRouter / DeepSeek /
+/// Groq / Anthropic: top-level {"message":...}, nested {"error":{"message":...,
+/// "metadata":{"raw":...}}}, and {"error":"<string>"}. Returns empty when the
+/// body is not a recognised error object (caller then falls back to the Qt
+/// transport error string).
+QString parse_server_error_message(const QByteArray& body);
+
/// Extract user-visible text from an OpenAI-compatible `message` object.
///
/// Handles: plain `content` string, content-as-parts arrays (some providers
diff --git a/fincept-qt/src/services/llm/LlmHttpHelpers.cpp b/fincept-qt/src/services/llm/LlmHttpHelpers.cpp
index 6954b074e..4c91aa0cd 100644
--- a/fincept-qt/src/services/llm/LlmHttpHelpers.cpp
+++ b/fincept-qt/src/services/llm/LlmHttpHelpers.cpp
@@ -4,6 +4,8 @@
#include "services/llm/LlmService.h"
+#include "services/llm/LlmContentExtractors.h"
+
#include <QCoreApplication>
#include <QEvent>
#include <QEventLoop>
@@ -20,6 +22,44 @@
namespace fincept::ai_chat {
+// ── Provider error-body → message ──────────────────────────────────────────
+// Shared by the blocking (eventloop_request) and streaming (do_streaming_request)
+// paths so both surface the provider's real reason rather than Qt's generic
+// transport string.
+QString parse_server_error_message(const QByteArray& body) {
+ auto err_doc = QJsonDocument::fromJson(body);
+ if (err_doc.isNull() || !err_doc.isObject())
+ return {};
+ QJsonObject ej = err_doc.object();
+
+ QString server_msg;
+ // Top-level {"message": ...} (OpenAI/Anthropic legacy shape).
+ if (ej.contains("message") && ej["message"].isString())
+ server_msg = ej["message"].toString();
+
+ // Nested {"error": {"message": ..., "metadata": {"raw": ...}}}
+ // (OpenAI current, AIHubMix, OpenRouter, DeepSeek, Groq all use this shape).
+ if (server_msg.isEmpty() && ej.contains("error") && ej["error"].isObject()) {
+ QJsonObject eo = ej["error"].toObject();
+ if (eo.contains("message") && eo["message"].isString())
+ server_msg = eo["message"].toString();
+ // OpenRouter surfaces upstream errors in metadata.raw.
+ if (eo.contains("metadata") && eo["metadata"].isObject()) {
+ QJsonObject md = eo["metadata"].toObject();
+ QString raw = md["raw"].toString();
+ QString provider_name = md["provider_name"].toString();
+ if (!raw.isEmpty())
+ server_msg += " (upstream " + provider_name + ": " + raw + ")";
+ }
+ }
+
+ // Some gateways return {"error": "<string>"} — surface it verbatim.
+ if (server_msg.isEmpty() && ej.contains("error") && ej["error"].isString())
+ server_msg = ej["error"].toString();
+
+ return server_msg;
+}
+
// ── Blocking POST ──────────────────────────────────────────────────────────
// Background-thread only. Delegates to eventloop_request which works for
// Cloudflare-protected endpoints (the old waitForReadyRead() path failed
@@ -89,29 +129,7 @@ LlmService::HttpResult LlmService::eventloop_request(const QString& method, cons
result.body = reply->readAll();
result.success = (result.status >= 200 && result.status < 300);
if (!result.success) {
- QString server_msg;
- auto err_doc = QJsonDocument::fromJson(result.body);
- if (!err_doc.isNull() && err_doc.isObject()) {
- QJsonObject ej = err_doc.object();
- // Top-level {"message": ...} (OpenAI/Anthropic legacy shape)
- if (ej.contains("message") && ej["message"].isString())
- server_msg = ej["message"].toString();
- // Nested {"error": {"message": ..., "metadata": {"raw": ...}}}
- // (OpenAI current, OpenRouter, DeepSeek, Groq all use this shape)
- if (server_msg.isEmpty() && ej.contains("error") && ej["error"].isObject()) {
- QJsonObject eo = ej["error"].toObject();
- if (eo.contains("message") && eo["message"].isString())
- server_msg = eo["message"].toString();
- // OpenRouter surfaces upstream errors in metadata.raw
- if (eo.contains("metadata") && eo["metadata"].isObject()) {
- QJsonObject md = eo["metadata"].toObject();
- QString raw = md["raw"].toString();
- QString provider_name = md["provider_name"].toString();
- if (!raw.isEmpty())
- server_msg += " (upstream " + provider_name + ": " + raw + ")";
- }
- }
- }
+ const QString server_msg = parse_server_error_message(result.body);
result.error = server_msg.isEmpty() ? QString("HTTP %1: %2").arg(result.status).arg(reply->errorString())
: QString("HTTP %1: %2").arg(result.status).arg(server_msg);
}
diff --git a/fincept-qt/src/services/llm/LlmModelsApi.cpp b/fincept-qt/src/services/llm/LlmModelsApi.cpp
index 65f22fc7d..2adcc5d71 100644
--- a/fincept-qt/src/services/llm/LlmModelsApi.cpp
+++ b/fincept-qt/src/services/llm/LlmModelsApi.cpp
@@ -68,6 +68,7 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
if (p == "openrouter") return "https://openrouter.ai/api/v1/models";
if (p == "xai") return "https://api.x.ai/v1/models";
if (p == "kimi") return "https://api.moonshot.ai/v1/models";
+ if (p == "aihubmix") return "https://aihubmix.com/v1/models"; // fallback if prefilled base_url was cleared
if (p == "fincept") return fincept::AppConfig::instance().api_base_url() + "/research/llm/models";
// minimax has no public /v1/models — caller falls back to known models.
return {};
diff --git a/fincept-qt/src/services/llm/LlmRequestBuilders.cpp b/fincept-qt/src/services/llm/LlmRequestBuilders.cpp
index f505f5715..0f07fd448 100644
--- a/fincept-qt/src/services/llm/LlmRequestBuilders.cpp
+++ b/fincept-qt/src/services/llm/LlmRequestBuilders.cpp
@@ -35,16 +35,25 @@ QJsonObject LlmService::build_openai_request(const QString& user_message,
QJsonObject req;
req["model"] = model_;
req["messages"] = messages;
- // Temperature omitted — each provider's default. OpenAI/xAI use max_completion_tokens; others max_tokens.
+ // Temperature omitted — each provider's default.
+ // Token-limit field: OpenAI/xAI native endpoints take max_completion_tokens
+ // universally. AIHubMix is a pass-through aggregator (no param translation),
+ // so an OpenAI-family model routed through it ALSO needs max_completion_tokens —
+ // o-series and gpt-5 hard-reject max_tokens with a 400 ("Unsupported parameter:
+ // 'max_tokens' ... Use 'max_completion_tokens' instead"). Non-OpenAI models
+ // (claude/gemini/deepseek/qwen/…) keep the OpenAI-compat max_tokens.
const int mx = resolved_max_tokens();
- if (provider_ == "openai" || provider_ == "xai")
+ const bool wants_completion_tokens = provider_ == "openai" || provider_ == "xai" ||
+ (provider_ == "aihubmix" && detail::is_openai_family_model(model_lower));
+ if (wants_completion_tokens)
req["max_completion_tokens"] = mx;
else
req["max_tokens"] = mx;
if (stream) {
req["stream"] = true;
- // OpenAI/xAI omit usage on streamed responses unless we opt in.
- if (provider_ == "openai" || provider_ == "xai")
+ // OpenAI/xAI (and OpenAI-family models via AIHubMix) omit usage on streamed
+ // responses unless we opt in. Don't send stream_options to non-OpenAI routes.
+ if (wants_completion_tokens)
req["stream_options"] = QJsonObject{{"include_usage", true}};
}
diff --git a/fincept-qt/src/services/llm/LlmRequestPolicy.h b/fincept-qt/src/services/llm/LlmRequestPolicy.h
index 1a21e598a..4d2c6b380 100644
--- a/fincept-qt/src/services/llm/LlmRequestPolicy.h
+++ b/fincept-qt/src/services/llm/LlmRequestPolicy.h
@@ -90,6 +90,20 @@ inline mcp::ToolFilter apply_request_policy(const mcp::ToolFilter& base) {
return out;
}
+// True for OpenAI-family chat model ids (gpt-*, chatgpt-*, o1/o3/o4 reasoning
+// series). Used by pass-through aggregators (AIHubMix) that forward parameters
+// unchanged: these models reject the legacy `max_tokens` field and require
+// `max_completion_tokens` (o-series / gpt-5 return a 400 otherwise), whereas
+// non-OpenAI models (claude-*, gemini-*, deepseek-*, qwen-*, …) keep max_tokens.
+// `model_lower` must already be lower-cased by the caller.
+inline bool is_openai_family_model(const QString& model_lower) {
+ return model_lower.startsWith(QLatin1String("gpt-")) ||
+ model_lower.startsWith(QLatin1String("chatgpt")) ||
+ model_lower.startsWith(QLatin1String("o1")) ||
+ model_lower.startsWith(QLatin1String("o3")) ||
+ model_lower.startsWith(QLatin1String("o4"));
+}
+
// ── Tool RAG activation ──────────────────────────────────────────────────
//
// When Tool RAG is on, the model is only sent the ~7 Tier-0 tools each turn and
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index a57bc7086..e2d6a7a9d 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -382,6 +382,10 @@ QString LlmService::get_endpoint_url() const {
return "http://localhost:11434/v1/chat/completions";
if (p == "xai")
return "https://api.x.ai/v1/chat/completions";
+ if (p == "aihubmix")
+ // Fallback for when the prefilled base_url was cleared; the custom-base_url
+ // branch above wins whenever it's set (incl. regional/proxy overrides).
+ return "https://aihubmix.com/v1/chat/completions";
return {};
}
@@ -1039,7 +1043,17 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (reply->error() != QNetworkReply::NoError) {
- resp.error = reply->errorString();
+ // A non-2xx (e.g. 400 from AIHubMix routing to a model that rejects a
+ // param) carries a JSON error body that explains why. The SSE reader
+ // never parses it because it isn't a "data:" line, so pull it from the
+ // unconsumed buffer + any remainder and surface the real reason instead
+ // of Qt's opaque "server replied: Bad Request".
+ const QByteArray err_body = partial_line + reply->readAll();
+ const QString server_msg = parse_server_error_message(err_body);
+ if (!server_msg.isEmpty())
+ resp.error = status > 0 ? QString("HTTP %1: %2").arg(status).arg(server_msg) : server_msg;
+ else
+ resp.error = reply->errorString();
LOG_ERROR(kLlmSvcTag, "Stream request failed: " + resp.error);
} else if (status >= 200 && status < 300) {
resp.content = accumulated;
diff --git a/fincept-qt/src/services/llm/LlmService.h b/fincept-qt/src/services/llm/LlmService.h
index 65ecf9657..9b4c7d29a 100644
--- a/fincept-qt/src/services/llm/LlmService.h
+++ b/fincept-qt/src/services/llm/LlmService.h
@@ -24,7 +24,7 @@ inline bool provider_supports_streaming(const QString& provider) {
return provider == "openai" || provider == "anthropic" || provider == "gemini" || provider == "google" ||
provider == "groq" || provider == "deepseek" || provider == "openrouter" || provider == "minimax" ||
provider == "kimi" || provider == "ollama" || provider == "xai" || provider == "fincept" ||
- provider == "astraflow" || provider == "astraflow_cn";
+ provider == "astraflow" || provider == "astraflow_cn" || provider == "aihubmix";
}
inline bool provider_requires_api_key(const QString& provider) {
diff --git a/fincept-qt/src/services/llm/ModelCatalog.cpp b/fincept-qt/src/services/llm/ModelCatalog.cpp
index f1b472d49..2b7b1a819 100644
--- a/fincept-qt/src/services/llm/ModelCatalog.cpp
+++ b/fincept-qt/src/services/llm/ModelCatalog.cpp
@@ -153,6 +153,12 @@ const CatalogEntry kCatalog[] = {
{"astraflow", "*", kNoPublishedCap},
{"astraflow_cn", "*", kNoPublishedCap},
+ // ── AIHubMix (OpenAI-compatible aggregator) ─────────────────────────────
+ // https://aihubmix.com/models — routes 500+ upstream models; per-model cap
+ // varies and we can't know the route from the id, so use a generous default
+ // (user max_tokens still applies).
+ {"aihubmix", "*", kNoPublishedCap},
+
// ── Fincept (proxies upstream) ──────────────────────────────────────
// Fincept's /research/llm/async wraps various upstream models. We
// don't know which one is selected server-side, so go with a generous
diff --git a/fincept-qt/src/storage/repositories/FeedItemRepository.cpp b/fincept-qt/src/storage/repositories/FeedItemRepository.cpp
new file mode 100644
index 000000000..48e880317
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/FeedItemRepository.cpp
@@ -0,0 +1,74 @@
+#include "storage/repositories/FeedItemRepository.h"
+
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSqlQuery>
+
+namespace fincept {
+
+using feeds::FeedItem;
+
+FeedItemRepository& FeedItemRepository::instance() {
+ static FeedItemRepository s;
+ return s;
+}
+
+FeedItem FeedItemRepository::map_row(QSqlQuery& q) {
+ FeedItem it;
+ it.id = q.value(0).toString();
+ it.title = q.value(1).toString();
+ it.summary = q.value(2).toString();
+ it.link = q.value(3).toString();
+ it.source = q.value(4).toString();
+ it.sort_ts = q.value(5).toLongLong();
+ it.time = q.value(6).toString();
+ const QJsonObject obj = QJsonDocument::fromJson(q.value(7).toString().toUtf8()).object();
+ for (auto i = obj.begin(); i != obj.end(); ++i)
+ it.fields.insert(i.key(), i.value().toString());
+ return it;
+}
+
+Result<void> FeedItemRepository::upsert(const QString& feed_id, const QVector<FeedItem>& items,
+ qint64 fetched_at) const {
+ for (const auto& it : items) {
+ QJsonObject o;
+ for (auto i = it.fields.begin(); i != it.fields.end(); ++i)
+ o[i.key()] = i.value();
+ const QString fj = QString::fromUtf8(QJsonDocument(o).toJson(QJsonDocument::Compact));
+ auto r = exec_write(
+ "INSERT INTO feed_items "
+ "(feed_id, item_id, title, summary, link, source, sort_ts, time, fields_json, fetched_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(feed_id, item_id) DO NOTHING",
+ {feed_id, it.id, it.title, it.summary, it.link, it.source, it.sort_ts, it.time, fj, fetched_at});
+ if (r.is_err())
+ return r;
+ }
+ return Result<void>::ok();
+}
+
+Result<QVector<FeedItem>> FeedItemRepository::recent(const QString& feed_id, int limit) const {
+ return query_list("SELECT item_id, title, summary, link, source, sort_ts, time, fields_json "
+ "FROM feed_items WHERE feed_id = ? ORDER BY sort_ts DESC LIMIT ?",
+ {feed_id, limit}, map_row);
+}
+
+Result<QVector<FeedItem>> FeedItemRepository::history(const QString& feed_id, qint64 from_ts, qint64 to_ts,
+ int limit) const {
+ return query_list("SELECT item_id, title, summary, link, source, sort_ts, time, fields_json "
+ "FROM feed_items WHERE feed_id = ? AND sort_ts BETWEEN ? AND ? "
+ "ORDER BY sort_ts DESC LIMIT ?",
+ {feed_id, from_ts, to_ts, limit}, map_row);
+}
+
+Result<void> FeedItemRepository::prune(const QString& feed_id, int keep) const {
+ return exec_write("DELETE FROM feed_items WHERE feed_id = ? AND item_id NOT IN "
+ "(SELECT item_id FROM feed_items WHERE feed_id = ? ORDER BY sort_ts DESC LIMIT ?)",
+ {feed_id, feed_id, keep});
+}
+
+Result<void> FeedItemRepository::clear(const QString& feed_id) const {
+ return exec_write("DELETE FROM feed_items WHERE feed_id = ?", {feed_id});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/FeedItemRepository.h b/fincept-qt/src/storage/repositories/FeedItemRepository.h
new file mode 100644
index 000000000..4a3181499
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/FeedItemRepository.h
@@ -0,0 +1,31 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+#include "storage/repositories/BaseRepository.h"
+
+#include <QVector>
+
+namespace fincept {
+
+/// Persisted feed item history (feed_items table, v044). Enables offline cache
+/// (show last-known items when a feed is down) and historical queries. Items are
+/// keyed by (feed_id, item_id); inserts ignore duplicates to preserve first-seen.
+class FeedItemRepository : public BaseRepository<feeds::FeedItem> {
+ public:
+ static FeedItemRepository& instance();
+
+ /// Insert new items for a feed (existing item_ids are left untouched).
+ Result<void> upsert(const QString& feed_id, const QVector<feeds::FeedItem>& items, qint64 fetched_at) const;
+ /// Newest-first cached items for a feed.
+ Result<QVector<feeds::FeedItem>> recent(const QString& feed_id, int limit) const;
+ /// Newest-first items in [from_ts, to_ts] (epoch secs) for historical queries.
+ Result<QVector<feeds::FeedItem>> history(const QString& feed_id, qint64 from_ts, qint64 to_ts, int limit) const;
+ /// Keep only the `keep` newest items for a feed; drop the rest.
+ Result<void> prune(const QString& feed_id, int keep) const;
+ Result<void> clear(const QString& feed_id) const;
+
+ private:
+ FeedItemRepository() = default;
+ static feeds::FeedItem map_row(QSqlQuery& q);
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/FeedSubscriptionRepository.cpp b/fincept-qt/src/storage/repositories/FeedSubscriptionRepository.cpp
new file mode 100644
index 000000000..844f4714a
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/FeedSubscriptionRepository.cpp
@@ -0,0 +1,66 @@
+#include "storage/repositories/FeedSubscriptionRepository.h"
+
+#include <QJsonDocument>
+#include <QSqlQuery>
+
+namespace fincept {
+
+using feeds::FeedSubscription;
+
+FeedSubscriptionRepository& FeedSubscriptionRepository::instance() {
+ static FeedSubscriptionRepository s;
+ return s;
+}
+
+FeedSubscription FeedSubscriptionRepository::map_row(QSqlQuery& q) {
+ FeedSubscription s;
+ s.id = q.value(0).toString();
+ s.name = q.value(1).toString();
+ s.url = q.value(2).toString();
+ s.refresh_sec = q.value(3).toInt();
+ s.parse_mode = feeds::parse_mode_from(q.value(4).toString());
+ s.format = feeds::feed_format_from(q.value(5).toString());
+ s.mapping = feeds::FieldMapping::from_json(QJsonDocument::fromJson(q.value(6).toString().toUtf8()).object());
+ s.display_mode = feeds::display_mode_from(q.value(7).toString());
+ s.headers = feeds::headers_from_json(QJsonDocument::fromJson(q.value(8).toString().toUtf8()).object());
+ s.enabled = q.value(9).toBool();
+ s.sort_order = q.value(10).toInt();
+ s.persist = q.value(11).toBool();
+ return s;
+}
+
+Result<QVector<FeedSubscription>> FeedSubscriptionRepository::list_all() const {
+ return query_list("SELECT id, name, url, refresh_sec, parse_mode, format, field_map, "
+ "display_mode, headers, enabled, sort_order, persist "
+ "FROM feed_subscriptions ORDER BY sort_order ASC, name ASC",
+ {}, map_row);
+}
+
+Result<void> FeedSubscriptionRepository::upsert(const FeedSubscription& s) const {
+ const QString fm = QString::fromUtf8(QJsonDocument(s.mapping.to_json()).toJson(QJsonDocument::Compact));
+ const QString hd =
+ QString::fromUtf8(QJsonDocument(feeds::headers_to_json(s.headers)).toJson(QJsonDocument::Compact));
+ return exec_write(
+ "INSERT INTO feed_subscriptions "
+ "(id, name, url, refresh_sec, parse_mode, format, field_map, display_mode, headers, enabled, sort_order, "
+ "persist, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now')) "
+ "ON CONFLICT(id) DO UPDATE SET "
+ " name=excluded.name, url=excluded.url, refresh_sec=excluded.refresh_sec, "
+ " parse_mode=excluded.parse_mode, format=excluded.format, field_map=excluded.field_map, "
+ " display_mode=excluded.display_mode, headers=excluded.headers, enabled=excluded.enabled, "
+ " sort_order=excluded.sort_order, persist=excluded.persist, updated_at=datetime('now')",
+ {s.id, s.name, s.url, s.refresh_sec, feeds::to_token(s.parse_mode), feeds::to_token(s.format), fm,
+ feeds::to_token(s.display_mode), hd, s.enabled ? 1 : 0, s.sort_order, s.persist ? 1 : 0});
+}
+
+Result<void> FeedSubscriptionRepository::remove(const QString& id) const {
+ return exec_write("DELETE FROM feed_subscriptions WHERE id = ?", {id});
+}
+
+Result<void> FeedSubscriptionRepository::set_enabled(const QString& id, bool enabled) const {
+ return exec_write("UPDATE feed_subscriptions SET enabled = ?, updated_at = datetime('now') WHERE id = ?",
+ {enabled ? 1 : 0, id});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/FeedSubscriptionRepository.h b/fincept-qt/src/storage/repositories/FeedSubscriptionRepository.h
new file mode 100644
index 000000000..2109cb202
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/FeedSubscriptionRepository.h
@@ -0,0 +1,27 @@
+#pragma once
+#include "services/feeds/FeedTypes.h"
+#include "storage/repositories/BaseRepository.h"
+
+#include <QVector>
+
+namespace fincept {
+
+/// SQLite persistence for generalized feed monitor subscriptions (feed_subscriptions
+/// table, v043). Separate from RssFeedRepository so arbitrary user feeds never leak
+/// into the curated News catalog. Mirrors the RssFeedRepository pattern; JSON columns
+/// (field_map, headers) are serialized via QJsonDocument. No cloud sync.
+class FeedSubscriptionRepository : public BaseRepository<feeds::FeedSubscription> {
+ public:
+ static FeedSubscriptionRepository& instance();
+
+ Result<QVector<feeds::FeedSubscription>> list_all() const;
+ Result<void> upsert(const feeds::FeedSubscription& row) const;
+ Result<void> remove(const QString& id) const;
+ Result<void> set_enabled(const QString& id, bool enabled) const;
+
+ private:
+ FeedSubscriptionRepository() = default;
+ static feeds::FeedSubscription map_row(QSqlQuery& q);
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
index 5f3438086..d70564330 100644
--- a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
+++ b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
@@ -42,6 +42,8 @@ PtOrder PaperTradingRepository::map_order(QSqlQuery& q) {
o.reduce_only = q.value(11).toBool();
o.created_at = q.value(12).toString();
o.filled_at = q.value(13).isNull() ? std::nullopt : std::optional<QString>(q.value(13).toString());
+ o.product = q.value(14).toString();
+ o.exchange = q.value(15).toString();
return o;
}
@@ -59,6 +61,11 @@ PtPosition PaperTradingRepository::map_position(QSqlQuery& q) {
p.leverage = q.value(9).toDouble();
p.liquidation_price = q.value(10).isNull() ? std::nullopt : std::optional<double>(q.value(10).toDouble());
p.opened_at = q.value(11).toString();
+ // Blank product = a legacy position from before product tracking. Treat it as
+ // delivery (carry-forward / Holdings), NOT MIS — defaulting to MIS made the
+ // 15:30 auto-square wrongly close pre-existing positions.
+ p.product = q.value(12).toString().isEmpty() ? QStringLiteral("CNC") : q.value(12).toString();
+ p.held_margin = q.value(13).toDouble();
return p;
}
@@ -82,11 +89,14 @@ PtTrade PaperTradingRepository::map_trade(QSqlQuery& q) {
static const char* kPortfolioCols =
"id, name, initial_balance, balance, currency, leverage, margin_mode, fee_rate, exchange, created_at";
+// product/exchange were in the v001 schema but never read/written before v040.
static const char* kOrderCols = "id, portfolio_id, symbol, side, order_type, quantity, price, stop_price, "
- "filled_qty, avg_price, status, reduce_only, created_at, filled_at";
+ "filled_qty, avg_price, status, reduce_only, created_at, filled_at, product, exchange";
+// product/held_margin added in v040.
static const char* kPositionCols = "id, portfolio_id, symbol, side, quantity, entry_price, current_price, "
- "unrealized_pnl, realized_pnl, leverage, liquidation_price, opened_at";
+ "unrealized_pnl, realized_pnl, leverage, liquidation_price, opened_at, "
+ "product, held_margin";
static const char* kTradeCols = "id, portfolio_id, order_id, symbol, side, price, quantity, fee, pnl, timestamp";
@@ -137,13 +147,13 @@ Result<void> PaperTradingRepository::delete_portfolio(const QString& id) {
Result<void> PaperTradingRepository::insert_order(const PtOrder& o) {
return exec_write("INSERT INTO pt_orders (id, portfolio_id, symbol, side, order_type, quantity, "
- "price, stop_price, filled_qty, avg_price, status, reduce_only, created_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "price, stop_price, filled_qty, avg_price, status, reduce_only, created_at, product, exchange) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
{o.id, o.portfolio_id, o.symbol, o.side, o.order_type, o.quantity,
o.price.has_value() ? QVariant(o.price.value()) : QVariant(),
o.stop_price.has_value() ? QVariant(o.stop_price.value()) : QVariant(), o.filled_qty,
o.avg_price.has_value() ? QVariant(o.avg_price.value()) : QVariant(), o.status,
- o.reduce_only ? 1 : 0, o.created_at});
+ o.reduce_only ? 1 : 0, o.created_at, o.product, o.exchange});
}
Result<PtOrder> PaperTradingRepository::get_order(const QString& id) {
@@ -174,6 +184,23 @@ Result<QVector<PtOrder>> PaperTradingRepository::get_orders(const QString& portf
return Result<QVector<PtOrder>>::ok(std::move(result));
}
+Result<QVector<PtOrder>> PaperTradingRepository::get_orders_between(const QString& portfolio_id,
+ const QString& from_iso, const QString& to_iso) {
+ // created_at is stored as a naive UTC ISO string (fixed width), so lexical
+ // comparison on the [from, to) UTC bounds yields the right day's orders.
+ auto r = db().execute(QString("SELECT %1 FROM pt_orders WHERE portfolio_id = ? AND created_at >= ? "
+ "AND created_at < ? ORDER BY created_at DESC")
+ .arg(kOrderCols),
+ {portfolio_id, from_iso, to_iso});
+ if (r.is_err())
+ return Result<QVector<PtOrder>>::err(r.error());
+ QVector<PtOrder> result;
+ auto& q = r.value();
+ while (q.next())
+ result.append(map_order(q));
+ return Result<QVector<PtOrder>>::ok(std::move(result));
+}
+
Result<void> PaperTradingRepository::update_order_fill(const QString& id, double filled_qty, double avg_price,
const QString& status, const QString& filled_at) {
return exec_write("UPDATE pt_orders SET filled_qty = ?, avg_price = ?, status = ?, filled_at = ? WHERE id = ?",
@@ -193,12 +220,23 @@ Result<void> PaperTradingRepository::cancel_all_orders(const QString& portfolio_
Result<void> PaperTradingRepository::insert_position(const PtPosition& p) {
return exec_write("INSERT INTO pt_positions (id, portfolio_id, symbol, side, quantity, entry_price, "
- "current_price, unrealized_pnl, realized_pnl, leverage, liquidation_price, opened_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "current_price, unrealized_pnl, realized_pnl, leverage, liquidation_price, opened_at, "
+ "product, held_margin) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
{p.id, p.portfolio_id, p.symbol, p.side, p.quantity, p.entry_price, p.current_price,
p.unrealized_pnl, p.realized_pnl, p.leverage,
p.liquidation_price.has_value() ? QVariant(p.liquidation_price.value()) : QVariant(),
- p.opened_at});
+ p.opened_at, p.product, p.held_margin});
+}
+
+Result<PtPosition> PaperTradingRepository::get_position(const QString& id) {
+ auto r = db().execute(QString("SELECT %1 FROM pt_positions WHERE id = ?").arg(kPositionCols), {id});
+ if (r.is_err())
+ return Result<PtPosition>::err(r.error());
+ auto& q = r.value();
+ if (!q.next())
+ return Result<PtPosition>::err("Position not found");
+ return Result<PtPosition>::ok(map_position(q));
}
Result<QVector<PtPosition>> PaperTradingRepository::get_positions(const QString& portfolio_id) {
@@ -247,6 +285,14 @@ Result<void> PaperTradingRepository::add_realized_pnl(const QString& id, double
return exec_write("UPDATE pt_positions SET realized_pnl = realized_pnl + ? WHERE id = ?", {pnl, id});
}
+Result<void> PaperTradingRepository::set_position_margin(const QString& id, double held_margin) {
+ return exec_write("UPDATE pt_positions SET held_margin = ? WHERE id = ?", {held_margin, id});
+}
+
+Result<void> PaperTradingRepository::set_position_product(const QString& id, const QString& product) {
+ return exec_write("UPDATE pt_positions SET product = ? WHERE id = ?", {product, id});
+}
+
Result<void> PaperTradingRepository::delete_position(const QString& id) {
return exec_write("DELETE FROM pt_positions WHERE id = ?", {id});
}
@@ -308,6 +354,21 @@ Result<QVector<PtTrade>> PaperTradingRepository::get_trades(const QString& portf
return Result<QVector<PtTrade>>::ok(std::move(result));
}
+Result<QVector<PtTrade>> PaperTradingRepository::get_trades_between(const QString& portfolio_id,
+ const QString& from_iso, const QString& to_iso) {
+ auto r = db().execute(QString("SELECT %1 FROM pt_trades WHERE portfolio_id = ? AND timestamp >= ? "
+ "AND timestamp < ? ORDER BY timestamp DESC")
+ .arg(kTradeCols),
+ {portfolio_id, from_iso, to_iso});
+ if (r.is_err())
+ return Result<QVector<PtTrade>>::err(r.error());
+ QVector<PtTrade> result;
+ auto& q = r.value();
+ while (q.next())
+ result.append(map_trade(q));
+ return Result<QVector<PtTrade>>::ok(std::move(result));
+}
+
Result<void> PaperTradingRepository::delete_all_trades(const QString& portfolio_id) {
return exec_write("DELETE FROM pt_trades WHERE portfolio_id = ?", {portfolio_id});
}
@@ -315,15 +376,25 @@ Result<void> PaperTradingRepository::delete_all_trades(const QString& portfolio_
// ── Stats ────────────────────────────────────────────────────────────────────
Result<PtStats> PaperTradingRepository::get_stats(const QString& portfolio_id) {
- auto r = db().execute("SELECT "
- " COALESCE(SUM(pnl), 0),"
- " COUNT(*),"
- " SUM(CASE WHEN pnl > 0 THEN 1 ELSE 0 END),"
- " SUM(CASE WHEN pnl < 0 THEN 1 ELSE 0 END),"
- " COALESCE(MAX(pnl), 0),"
- " COALESCE(MIN(pnl), 0)"
- " FROM pt_trades WHERE portfolio_id = ?",
- {portfolio_id});
+ // today_pnl uses an IST (+330 min) day boundary so "today" matches the Indian
+ // trading session regardless of the machine's local timezone. timestamp is a
+ // naive UTC ISO string, so datetime() parses it and the +330 shift gives IST.
+ auto r = db().execute(
+ "SELECT "
+ " COALESCE(SUM(pnl), 0)," // 0 realized
+ " COUNT(*)," // 1 fills
+ " SUM(CASE WHEN pnl > 0 THEN 1 ELSE 0 END)," // 2 winners
+ " SUM(CASE WHEN pnl < 0 THEN 1 ELSE 0 END)," // 3 losers
+ " COALESCE(MAX(pnl), 0)," // 4 max win
+ " COALESCE(MIN(pnl), 0)," // 5 max loss
+ " COALESCE(SUM(CASE WHEN pnl > 0 THEN pnl ELSE 0 END), 0)," // 6 gross+
+ " COALESCE(SUM(CASE WHEN pnl < 0 THEN pnl ELSE 0 END), 0)," // 7 gross-
+ " COALESCE(SUM(fee), 0)," // 8 fees
+ " COALESCE(SUM(price * quantity), 0)," // 9 turnover
+ " COALESCE(SUM(CASE WHEN date(datetime(timestamp, '+330 minutes')) "
+ " = date(datetime('now', '+330 minutes')) THEN pnl ELSE 0 END), 0)" // 10 today
+ " FROM pt_trades WHERE portfolio_id = ?",
+ {portfolio_id});
if (r.is_err())
return Result<PtStats>::err(r.error());
@@ -339,7 +410,20 @@ Result<PtStats> PaperTradingRepository::get_stats(const QString& portfolio_id) {
s.losing_trades = q.value(3).toLongLong();
s.largest_win = q.value(4).toDouble();
s.largest_loss = q.value(5).toDouble();
- s.win_rate = s.total_trades > 0 ? static_cast<double>(s.winning_trades) / static_cast<double>(s.total_trades) : 0.0;
+ s.gross_profit = q.value(6).toDouble();
+ s.gross_loss = q.value(7).toDouble(); // <= 0
+ s.total_fees = q.value(8).toDouble();
+ s.turnover = q.value(9).toDouble();
+ s.today_pnl = q.value(10).toDouble();
+
+ // Win rate over *decided* trades (winners + losers), excluding zero-P&L opening
+ // fills — a truer hit-rate than dividing by every fill.
+ const int64_t decided = s.winning_trades + s.losing_trades;
+ s.win_rate = decided > 0 ? static_cast<double>(s.winning_trades) / static_cast<double>(decided) : 0.0;
+ s.avg_win = s.winning_trades > 0 ? s.gross_profit / static_cast<double>(s.winning_trades) : 0.0;
+ s.avg_loss = s.losing_trades > 0 ? s.gross_loss / static_cast<double>(s.losing_trades) : 0.0;
+ const double gross_loss_abs = s.gross_loss < 0 ? -s.gross_loss : s.gross_loss;
+ s.profit_factor = gross_loss_abs > 0 ? s.gross_profit / gross_loss_abs : (s.gross_profit > 0 ? s.gross_profit : 0.0);
return Result<PtStats>::ok(s);
}
diff --git a/fincept-qt/src/storage/repositories/PaperTradingRepository.h b/fincept-qt/src/storage/repositories/PaperTradingRepository.h
index d747a3c19..4f546d399 100644
--- a/fincept-qt/src/storage/repositories/PaperTradingRepository.h
+++ b/fincept-qt/src/storage/repositories/PaperTradingRepository.h
@@ -24,6 +24,10 @@ class PaperTradingRepository : public BaseRepository<trading::PtPortfolio> {
Result<void> insert_order(const trading::PtOrder& o);
Result<trading::PtOrder> get_order(const QString& id);
Result<QVector<trading::PtOrder>> get_orders(const QString& portfolio_id, const QString& status = {});
+ /// Orders whose created_at falls in [from_iso, to_iso) (UTC ISO strings). Used
+ /// by the order book's per-day view so each day starts empty.
+ Result<QVector<trading::PtOrder>> get_orders_between(const QString& portfolio_id, const QString& from_iso,
+ const QString& to_iso);
Result<void> update_order_fill(const QString& id, double filled_qty, double avg_price, const QString& status,
const QString& filled_at);
Result<void> cancel_order(const QString& id);
@@ -31,12 +35,18 @@ class PaperTradingRepository : public BaseRepository<trading::PtPortfolio> {
// ── Positions ────────────────────────────────────────────────────────────
Result<void> insert_position(const trading::PtPosition& p);
+ Result<trading::PtPosition> get_position(const QString& id);
Result<QVector<trading::PtPosition>> get_positions(const QString& portfolio_id);
std::optional<trading::PtPosition> find_position(const QString& portfolio_id, const QString& symbol,
const QString& side);
Result<void> update_position(const QString& id, double quantity, double entry_price);
Result<void> update_position_price(const QString& portfolio_id, const QString& symbol, double price);
Result<void> add_realized_pnl(const QString& id, double pnl);
+ /// Set the margin currently locked by an open position (v040). Released to
+ /// available balance, proportionally, when the position is closed/reduced.
+ Result<void> set_position_margin(const QString& id, double held_margin);
+ /// Change a position's broker product (e.g. MIS -> CNC on conversion, v040).
+ Result<void> set_position_product(const QString& id, const QString& product);
Result<void> delete_position(const QString& id);
Result<void> delete_all_positions(const QString& portfolio_id);
@@ -54,6 +64,9 @@ class PaperTradingRepository : public BaseRepository<trading::PtPortfolio> {
// ── Trades ───────────────────────────────────────────────────────────────
Result<void> insert_trade(const trading::PtTrade& t);
Result<QVector<trading::PtTrade>> get_trades(const QString& portfolio_id, int64_t limit = 100);
+ /// Trades whose timestamp falls in [from_iso, to_iso) (UTC ISO strings).
+ Result<QVector<trading::PtTrade>> get_trades_between(const QString& portfolio_id, const QString& from_iso,
+ const QString& to_iso);
Result<void> delete_all_trades(const QString& portfolio_id);
// ── Stats ────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/storage/repositories/ScanEventRepository.cpp b/fincept-qt/src/storage/repositories/ScanEventRepository.cpp
new file mode 100644
index 000000000..994cba065
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/ScanEventRepository.cpp
@@ -0,0 +1,48 @@
+// src/storage/repositories/ScanEventRepository.cpp
+#include "storage/repositories/ScanEventRepository.h"
+
+#include <QUuid>
+
+namespace fincept {
+
+namespace {
+// Coerce possibly-null QString to non-null '' so NOT NULL TEXT binds never become SQL NULL.
+QString nn(const QString& s) { return s.isNull() ? QString::fromLatin1("") : s; }
+const char* kCols = "id, watch_id, symbol, detail, fired_at";
+} // namespace
+
+ScanEventRepository& ScanEventRepository::instance() {
+ static ScanEventRepository s;
+ return s;
+}
+
+ScanWatchEvent ScanEventRepository::map_row(QSqlQuery& q) {
+ ScanWatchEvent e;
+ e.id = q.value(0).toString();
+ e.watch_id = q.value(1).toString();
+ e.symbol = q.value(2).toString();
+ e.detail = q.value(3).toString();
+ e.fired_at = q.value(4).toLongLong();
+ return e;
+}
+
+Result<void> ScanEventRepository::record(const QString& watch_id, const QString& symbol,
+ const QString& detail, qint64 fired_at) {
+ const QString id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ return exec_write(
+ "INSERT INTO scan_watch_events (id, watch_id, symbol, detail, fired_at)"
+ " VALUES (?,?,?,?,?)",
+ {id, nn(watch_id), nn(symbol), nn(detail), fired_at});
+}
+
+Result<void> ScanEventRepository::clear_for(const QString& watch_id) {
+ return exec_write("DELETE FROM scan_watch_events WHERE watch_id=?", {watch_id});
+}
+
+Result<QVector<ScanWatchEvent>> ScanEventRepository::recent(int limit) {
+ return query_list(
+ QString("SELECT %1 FROM scan_watch_events ORDER BY fired_at DESC LIMIT ?").arg(kCols),
+ {limit}, map_row);
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/ScanEventRepository.h b/fincept-qt/src/storage/repositories/ScanEventRepository.h
new file mode 100644
index 000000000..02202efcd
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/ScanEventRepository.h
@@ -0,0 +1,32 @@
+// src/storage/repositories/ScanEventRepository.h
+#pragma once
+#include "storage/repositories/BaseRepository.h"
+
+#include <QString>
+#include <QVector>
+
+namespace fincept {
+
+struct ScanWatchEvent {
+ QString id;
+ QString watch_id;
+ QString symbol;
+ QString detail;
+ qint64 fired_at = 0;
+};
+
+class ScanEventRepository : public BaseRepository<ScanWatchEvent> {
+ public:
+ static ScanEventRepository& instance();
+
+ Result<void> record(const QString& watch_id, const QString& symbol,
+ const QString& detail, qint64 fired_at);
+ Result<void> clear_for(const QString& watch_id); // cascade on watch delete
+ Result<QVector<ScanWatchEvent>> recent(int limit = 100);
+
+ private:
+ ScanEventRepository() = default;
+ static ScanWatchEvent map_row(QSqlQuery& q);
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp b/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp
new file mode 100644
index 000000000..8a1343e08
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/ScanWatchRepository.cpp
@@ -0,0 +1,131 @@
+// src/storage/repositories/ScanWatchRepository.cpp
+#include "storage/repositories/ScanWatchRepository.h"
+
+#include "storage/sync/SyncOutbox.h"
+
+#include <QDateTime>
+#include <QJsonDocument>
+#include <QUuid>
+
+namespace fincept {
+
+namespace {
+const char* kCols =
+ "id, name, conditions_json, logic, symbols, timeframe, lookback_days,"
+ " data_source, broker_id, account_id, mode, interval_sec, cooldown_min,"
+ " actions_json, active, status, last_eval_at, last_fired_at";
+
+QString json_array_to_str(const QJsonArray& a) {
+ return QString::fromUtf8(QJsonDocument(a).toJson(QJsonDocument::Compact));
+}
+QString json_obj_to_str(const QJsonObject& o) {
+ return QString::fromUtf8(QJsonDocument(o).toJson(QJsonDocument::Compact));
+}
+// Coerce a possibly-null QString to a non-null empty string so it binds as ''
+// (not SQL NULL) into NOT NULL TEXT columns.
+QString nn(const QString& s) { return s.isNull() ? QString::fromLatin1("") : s; }
+} // namespace
+
+ScanWatchRepository& ScanWatchRepository::instance() {
+ static ScanWatchRepository s;
+ return s;
+}
+
+ScanWatch ScanWatchRepository::map_row(QSqlQuery& q) {
+ ScanWatch w;
+ w.id = q.value(0).toString();
+ w.name = q.value(1).toString();
+ w.conditions = QJsonDocument::fromJson(q.value(2).toString().toUtf8()).array();
+ w.logic = q.value(3).toString();
+ w.symbols = q.value(4).toString().split('\n', Qt::SkipEmptyParts);
+ w.timeframe = q.value(5).toString();
+ w.lookback_days = q.value(6).toInt();
+ w.data_source = q.value(7).toString();
+ w.broker_id = q.value(8).toString();
+ w.account_id = q.value(9).toString();
+ w.mode = q.value(10).toString();
+ w.interval_sec = q.value(11).toInt();
+ w.cooldown_min = q.value(12).toInt();
+ w.actions = QJsonDocument::fromJson(q.value(13).toString().toUtf8()).object();
+ w.active = q.value(14).toInt() != 0;
+ w.status = q.value(15).toString();
+ w.last_eval_at = q.value(16).toLongLong();
+ w.last_fired_at = q.value(17).toLongLong();
+ return w;
+}
+
+Result<ScanWatch> ScanWatchRepository::create(const ScanWatch& in) {
+ ScanWatch w = in;
+ if (w.id.isEmpty())
+ w.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ auto r = exec_write(
+ "INSERT INTO scan_watches (id, name, conditions_json, logic, symbols, timeframe,"
+ " lookback_days, data_source, broker_id, account_id, mode, interval_sec, cooldown_min,"
+ " actions_json, active, status, last_eval_at, last_fired_at, created_at, updated_at)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ {nn(w.id), nn(w.name), nn(json_array_to_str(w.conditions)), nn(w.logic), nn(w.symbols.join('\n')),
+ nn(w.timeframe), w.lookback_days, nn(w.data_source), nn(w.broker_id), nn(w.account_id), nn(w.mode),
+ w.interval_sec, w.cooldown_min, nn(json_obj_to_str(w.actions)), w.active ? 1 : 0,
+ nn(w.status), w.last_eval_at, w.last_fired_at, now, now});
+ if (r.is_err())
+ return Result<ScanWatch>::err(r.error());
+ SyncOutbox::record("scan_watch", w.id, "create");
+ return get(w.id);
+}
+
+Result<void> ScanWatchRepository::update(const ScanWatch& w) {
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ auto r = exec_write(
+ "UPDATE scan_watches SET name=?, conditions_json=?, logic=?, symbols=?, timeframe=?,"
+ " lookback_days=?, data_source=?, broker_id=?, account_id=?, mode=?, interval_sec=?,"
+ " cooldown_min=?, actions_json=?, active=?, updated_at=? WHERE id=?",
+ {nn(w.name), nn(json_array_to_str(w.conditions)), nn(w.logic), nn(w.symbols.join('\n')), nn(w.timeframe),
+ w.lookback_days, nn(w.data_source), nn(w.broker_id), nn(w.account_id), nn(w.mode), w.interval_sec,
+ w.cooldown_min, nn(json_obj_to_str(w.actions)), w.active ? 1 : 0, now, nn(w.id)});
+ if (r.is_ok())
+ SyncOutbox::record("scan_watch", w.id, "update");
+ return r;
+}
+
+Result<void> ScanWatchRepository::remove(const QString& id) {
+ auto r = exec_write("DELETE FROM scan_watches WHERE id=?", {id});
+ if (r.is_ok())
+ SyncOutbox::record("scan_watch", id, "delete");
+ return r;
+}
+
+Result<void> ScanWatchRepository::set_active(const QString& id, bool active) {
+ auto r = exec_write("UPDATE scan_watches SET active=?, updated_at=? WHERE id=?",
+ {active ? 1 : 0, QDateTime::currentMSecsSinceEpoch(), id});
+ if (r.is_ok())
+ SyncOutbox::record("scan_watch", id, "update");
+ return r;
+}
+
+Result<void> ScanWatchRepository::touch_status(const QString& id, const QString& status,
+ qint64 last_eval_at) {
+ return exec_write("UPDATE scan_watches SET status=?, last_eval_at=? WHERE id=?",
+ {status, last_eval_at, id});
+}
+
+Result<void> ScanWatchRepository::touch_fired(const QString& id, qint64 last_fired_at) {
+ return exec_write("UPDATE scan_watches SET last_fired_at=? WHERE id=?",
+ {last_fired_at, id});
+}
+
+Result<QVector<ScanWatch>> ScanWatchRepository::list_all() {
+ return query_list(QString("SELECT %1 FROM scan_watches ORDER BY created_at DESC").arg(kCols),
+ {}, map_row);
+}
+
+Result<QVector<ScanWatch>> ScanWatchRepository::list_active() {
+ return query_list(QString("SELECT %1 FROM scan_watches WHERE active=1").arg(kCols),
+ {}, map_row);
+}
+
+Result<ScanWatch> ScanWatchRepository::get(const QString& id) {
+ return query_one(QString("SELECT %1 FROM scan_watches WHERE id=?").arg(kCols), {id}, map_row);
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/ScanWatchRepository.h b/fincept-qt/src/storage/repositories/ScanWatchRepository.h
new file mode 100644
index 000000000..90b5da21f
--- /dev/null
+++ b/fincept-qt/src/storage/repositories/ScanWatchRepository.h
@@ -0,0 +1,53 @@
+// src/storage/repositories/ScanWatchRepository.h
+#pragma once
+#include "storage/repositories/BaseRepository.h"
+
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QString>
+#include <QStringList>
+#include <QVector>
+
+namespace fincept {
+
+struct ScanWatch {
+ QString id;
+ QString name;
+ QJsonArray conditions;
+ QString logic = QStringLiteral("AND");
+ QStringList symbols;
+ QString timeframe = QStringLiteral("1m");
+ int lookback_days = 5;
+ QString data_source = QStringLiteral("Broker");
+ QString broker_id;
+ QString account_id;
+ QString mode = QStringLiteral("poll");
+ int interval_sec = 60;
+ int cooldown_min = 15;
+ QJsonObject actions;
+ bool active = true;
+ QString status = QStringLiteral("idle");
+ qint64 last_eval_at = 0;
+ qint64 last_fired_at = 0;
+};
+
+class ScanWatchRepository : public BaseRepository<ScanWatch> {
+ public:
+ static ScanWatchRepository& instance();
+
+ Result<ScanWatch> create(const ScanWatch& in); // generates id if empty
+ Result<void> update(const ScanWatch& w);
+ Result<void> remove(const QString& id);
+ Result<void> set_active(const QString& id, bool active);
+ Result<void> touch_status(const QString& id, const QString& status, qint64 last_eval_at);
+ Result<void> touch_fired(const QString& id, qint64 last_fired_at);
+ Result<QVector<ScanWatch>> list_all();
+ Result<QVector<ScanWatch>> list_active();
+ Result<ScanWatch> get(const QString& id);
+
+ private:
+ ScanWatchRepository() = default;
+ static ScanWatch map_row(QSqlQuery& q);
+};
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index f1922c168..c754ad4e6 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -86,5 +86,10 @@ void register_migration_v036();
void register_migration_v037();
void register_migration_v038();
void register_migration_v039();
+void register_migration_v040();
+void register_migration_v041();
+void register_migration_v042();
+void register_migration_v043();
+void register_migration_v044();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v040_paper_trading_realism.cpp b/fincept-qt/src/storage/sqlite/migrations/v040_paper_trading_realism.cpp
new file mode 100644
index 000000000..f0a08b102
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v040_paper_trading_realism.cpp
@@ -0,0 +1,71 @@
+// v040_paper_trading_realism — make the paper simulator behave like a real Indian
+// broker. pt_positions gains a `product` column (MIS/CNC/NRML) so the engine can
+// tell intraday from delivery (for the 15:30 MIS auto-square and MIS->CNC convert),
+// and a `held_margin` column so an open position keeps its margin locked from
+// available balance until it is closed (previously margin was released on fill, so
+// available balance never reflected open positions — the "stuck at 10 lakh" bug).
+//
+// Columns are added idempotently (add-if-missing) so freshly created DBs (which get
+// them here) and any DB already at >=40 converge. pt_orders already carries
+// product/exchange (v001) and pt_holdings already exists (v001) — no change needed
+// there; the repository simply starts persisting/reading them.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+bool v040_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> v040_add_if_missing(QSqlDatabase& db, const QString& table, const QString& column,
+ const QString& decl) {
+ if (v040_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_v040(QSqlDatabase& db) {
+ struct Col {
+ const char* table;
+ const char* column;
+ const char* decl;
+ };
+ const Col cols[] = {
+ // Pre-existing positions have no product intent — default them to delivery
+ // (CNC, carry-forward) so the 15:30 intraday auto-square never closes them.
+ // New orders set the real product (MIS/CNC/NRML) explicitly.
+ {"pt_positions", "product", "TEXT DEFAULT 'CNC'"},
+ {"pt_positions", "held_margin", "REAL DEFAULT 0"},
+ };
+ for (const auto& c : cols) {
+ auto r = v040_add_if_missing(db, c.table, c.column, c.decl);
+ if (r.is_err())
+ return r;
+ }
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v040() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({40, "paper_trading_realism", apply_v040});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v041_scan_watches.cpp b/fincept-qt/src/storage/sqlite/migrations/v041_scan_watches.cpp
new file mode 100644
index 000000000..454795568
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v041_scan_watches.cpp
@@ -0,0 +1,54 @@
+// v041_scan_watches — persisted alert watches for the Algo→Scanner live monitor.
+// One row per watch: serialized conditions (JSON array), symbols, data source,
+// poll/realtime mode, interval, cooldown, action config (JSON), and live status.
+// CREATE-IF-NOT-EXISTS so fresh and existing DBs converge.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+Result<void> apply_v041(QSqlDatabase& db) {
+ QSqlQuery q(db);
+ const char* sql =
+ "CREATE TABLE IF NOT EXISTS scan_watches ("
+ " id TEXT PRIMARY KEY,"
+ " name TEXT NOT NULL,"
+ " conditions_json TEXT NOT NULL DEFAULT '[]',"
+ " logic TEXT NOT NULL DEFAULT 'AND',"
+ " symbols TEXT NOT NULL DEFAULT '',"
+ " timeframe TEXT NOT NULL DEFAULT '1m',"
+ " lookback_days INTEGER NOT NULL DEFAULT 5,"
+ " data_source TEXT NOT NULL DEFAULT 'Broker',"
+ " broker_id TEXT NOT NULL DEFAULT '',"
+ " account_id TEXT NOT NULL DEFAULT '',"
+ " mode TEXT NOT NULL DEFAULT 'poll',"
+ " interval_sec INTEGER NOT NULL DEFAULT 60,"
+ " cooldown_min INTEGER NOT NULL DEFAULT 15,"
+ " actions_json TEXT NOT NULL DEFAULT '{}',"
+ " active INTEGER NOT NULL DEFAULT 1,"
+ " status TEXT NOT NULL DEFAULT 'idle',"
+ " last_eval_at INTEGER NOT NULL DEFAULT 0,"
+ " last_fired_at INTEGER NOT NULL DEFAULT 0,"
+ " created_at INTEGER NOT NULL DEFAULT 0,"
+ " updated_at INTEGER NOT NULL DEFAULT 0"
+ ")";
+ if (!q.exec(QString::fromUtf8(sql)))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v041() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({41, "scan_watches", apply_v041});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v042_scan_watch_events.cpp b/fincept-qt/src/storage/sqlite/migrations/v042_scan_watch_events.cpp
new file mode 100644
index 000000000..d1a56cc19
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v042_scan_watch_events.cpp
@@ -0,0 +1,41 @@
+// v042_scan_watch_events — one row per fired alert (a watch condition met). Lets
+// the UI show alert history and lets a watch's events be cascade-removed when the
+// watch is deleted. UUID primary key avoids collisions across watches/fires.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+Result<void> apply_v042(QSqlDatabase& db) {
+ QSqlQuery q(db);
+ const char* sql =
+ "CREATE TABLE IF NOT EXISTS scan_watch_events ("
+ " id TEXT PRIMARY KEY,"
+ " watch_id TEXT NOT NULL DEFAULT '',"
+ " symbol TEXT NOT NULL DEFAULT '',"
+ " detail TEXT NOT NULL DEFAULT '',"
+ " fired_at INTEGER NOT NULL DEFAULT 0"
+ ")";
+ if (!q.exec(QString::fromUtf8(sql)))
+ return Result<void>::err(q.lastError().text().toStdString());
+ QSqlQuery idx(db);
+ if (!idx.exec(QStringLiteral("CREATE INDEX IF NOT EXISTS idx_scan_watch_events_watch"
+ " ON scan_watch_events(watch_id)")))
+ return Result<void>::err(idx.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v042() {
+ static bool done = false;
+ if (done) return;
+ done = true;
+ MigrationRunner::register_migration({42, "scan_watch_events", apply_v042});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v043_feed_subscriptions.cpp b/fincept-qt/src/storage/sqlite/migrations/v043_feed_subscriptions.cpp
new file mode 100644
index 000000000..df31aa74a
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v043_feed_subscriptions.cpp
@@ -0,0 +1,54 @@
+// v043_feed_subscriptions — generalized feed monitor subscriptions.
+//
+// Separate from rss_feeds (news catalog) so arbitrary user feeds never leak into
+// the News screen. Managed by FeedSubscriptionRepository / FeedMonitor.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+static Result<void> sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v043(QSqlDatabase& db) {
+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS feed_subscriptions ("
+ " id TEXT PRIMARY KEY,"
+ " name TEXT NOT NULL,"
+ " url TEXT NOT NULL,"
+ " refresh_sec INTEGER NOT NULL DEFAULT 300,"
+ " parse_mode TEXT NOT NULL DEFAULT 'auto',"
+ " format TEXT NOT NULL DEFAULT 'auto',"
+ " field_map TEXT NOT NULL DEFAULT '{}',"
+ " display_mode TEXT NOT NULL DEFAULT 'cards',"
+ " headers TEXT NOT NULL DEFAULT '{}',"
+ " enabled INTEGER NOT NULL DEFAULT 1,"
+ " sort_order INTEGER NOT NULL DEFAULT 0,"
+ " created_at TEXT DEFAULT (datetime('now')),"
+ " updated_at TEXT DEFAULT (datetime('now'))"
+ ")");
+ if (r.is_err())
+ return r;
+
+ return sql(db, "CREATE INDEX IF NOT EXISTS idx_feed_subs_order "
+ "ON feed_subscriptions(sort_order)");
+}
+
+} // anonymous namespace
+
+void register_migration_v043() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({43, "feed_subscriptions", apply_v043});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v044_feed_items.cpp b/fincept-qt/src/storage/sqlite/migrations/v044_feed_items.cpp
new file mode 100644
index 000000000..6eca9a9ab
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v044_feed_items.cpp
@@ -0,0 +1,65 @@
+// v044_feed_items — persisted feed item history + per-feed "store history" flag.
+//
+// feed_items accumulates fetched items per subscription so the panel can show
+// cached data when a feed is down and query historical entries. feed_subscriptions
+// gains a `persist` flag (default on) controlling whether a feed is stored.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+static Result<void> sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v044(QSqlDatabase& db) {
+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS feed_items ("
+ " feed_id TEXT NOT NULL,"
+ " item_id TEXT NOT NULL,"
+ " title TEXT,"
+ " summary TEXT,"
+ " link TEXT,"
+ " source TEXT,"
+ " sort_ts INTEGER NOT NULL DEFAULT 0,"
+ " time TEXT,"
+ " fields_json TEXT NOT NULL DEFAULT '{}',"
+ " fetched_at INTEGER NOT NULL DEFAULT 0,"
+ " PRIMARY KEY (feed_id, item_id)"
+ ")");
+ if (r.is_err())
+ return r;
+
+ r = sql(db, "CREATE INDEX IF NOT EXISTS idx_feed_items_feed_ts "
+ "ON feed_items(feed_id, sort_ts DESC)");
+ if (r.is_err())
+ return r;
+
+ // Per-feed storage toggle. The column may already exist on re-run; ignore the
+ // duplicate-column error so the migration stays idempotent.
+ QSqlQuery alter(db);
+ if (!alter.exec("ALTER TABLE feed_subscriptions ADD COLUMN persist INTEGER NOT NULL DEFAULT 1")) {
+ const QString err = alter.lastError().text();
+ if (!err.contains("duplicate column", Qt::CaseInsensitive))
+ return Result<void>::err(err.toStdString());
+ }
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v044() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({44, "feed_items", apply_v044});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/trading/PaperTrading.cpp b/fincept-qt/src/trading/PaperTrading.cpp
index 420ab5691..ec5502a96 100644
--- a/fincept-qt/src/trading/PaperTrading.cpp
+++ b/fincept-qt/src/trading/PaperTrading.cpp
@@ -9,6 +9,7 @@
#include "storage/repositories/PaperTradingRepository.h"
#include "storage/sqlite/Database.h"
+#include <QDate>
#include <QDateTime>
#include <QHash>
#include <QMutex>
@@ -394,7 +395,8 @@ QVector<PtOrder> pt_get_orders(const QString& portfolio_id, const QString& statu
// Fill Order — The Core Engine
// ============================================================================
-PtTrade pt_fill_order(const QString& order_id, double fill_price, std::optional<double> fill_qty) {
+PtTrade pt_fill_order(const QString& order_id, double fill_price, std::optional<double> fill_qty,
+ const QString& fill_time) {
if (!std::isfinite(fill_price) || fill_price <= 0.0)
throw std::runtime_error("Invalid fill price");
if (fill_qty && (!std::isfinite(*fill_qty) || *fill_qty <= 0.0))
@@ -420,107 +422,100 @@ PtTrade pt_fill_order(const QString& order_id, double fill_price, std::optional<
if (qty <= 0.0)
throw std::runtime_error("Nothing left to fill");
double fee = qty * fill_price * portfolio.fee_rate;
- QString now = now_rfc3339();
+ QString now = fill_time.isEmpty() ? now_rfc3339() : fill_time;
QString position_side = (order.side == "buy") ? "long" : "short";
QString opposite_side = (order.side == "buy") ? "short" : "long";
double pnl = 0.0;
+ double new_filled = order.filled_qty + qty;
+ bool fully_filled = (new_filled >= order.quantity);
// ── Begin DB transaction for atomicity ──────────────────────────────
auto& db = Database::instance();
db.begin_transaction();
try {
- // 4. Check opposite-side position (closing)
+ // Net change to available cash from this fill. Margin model (v040):
+ // • Opening exposure KEEPS its margin locked on the position (held_margin)
+ // — it is NOT released to cash on fill. This is what finally makes
+ // available balance drop when a position is opened (the old code released
+ // the block on fill, so an open position locked no cash — "stuck at 10L").
+ // • Closing/reducing a position RELEASES that position's held margin back
+ // to cash, proportionally, plus realized P&L.
+ // • Brokerage (fee) is charged on every fill.
+ double balance_delta = -fee;
+ const double order_blocked = repo().get_margin_block(order_id);
+ double block_consumed = 0.0; // portion of the order's block turned into position margin
+
+ // ── Closing leg: net against an opposite-side position ──
+ double close_qty = 0.0;
auto opp = repo().find_position(order.portfolio_id, order.symbol, opposite_side);
- bool had_opposite = false;
-
if (opp) {
- had_opposite = true;
PtPosition pos = *opp;
- double close_qty = std::min(qty, pos.quantity);
+ close_qty = std::min(qty, pos.quantity);
pnl = (pos.side == "long") ? (fill_price - pos.entry_price) * close_qty
: (pos.entry_price - fill_price) * close_qty;
-
+ const double frac_close = pos.quantity > 0.0 ? (close_qty / pos.quantity) : 1.0;
+ const double margin_released = pos.held_margin * frac_close;
if (close_qty >= pos.quantity) {
repo().delete_position(pos.id);
} else {
repo().update_position(pos.id, pos.quantity - close_qty, pos.entry_price);
+ repo().set_position_margin(pos.id, pos.held_margin - margin_released);
repo().add_realized_pnl(pos.id, pnl);
}
-
- // Position flip: remaining qty becomes new opposite position
- if (qty > close_qty) {
- double new_qty = qty - close_qty;
- PtPosition np;
- np.id = generate_uuid();
- np.portfolio_id = order.portfolio_id;
- np.symbol = order.symbol;
- np.side = position_side;
- np.quantity = new_qty;
- np.entry_price = fill_price;
- np.current_price = fill_price;
- np.leverage = portfolio.leverage;
- np.opened_at = now;
- repo().insert_position(np);
- }
+ balance_delta += margin_released + pnl;
}
- if (!had_opposite) {
- // 5. Same-side position (averaging)
+ // ── Opening leg: net-new exposure on the order's own side ──
+ const double open_qty = qty - close_qty;
+ if (open_qty > 0.0) {
+ // Margin the new exposure must lock, per product / leverage at fill price.
+ double open_margin = pt_calculate_required_margin(order.portfolio_id, order.symbol, order.exchange,
+ order.product, open_qty, fill_price, order.side);
+ // That margin was pre-blocked on the order at placement: convert the
+ // block into position margin (release the block, re-lock the actual).
+ block_consumed = fully_filled ? order_blocked : std::min(order_blocked, open_margin);
+ balance_delta += block_consumed - open_margin;
+
+ const QString product = order.product.isEmpty() ? QStringLiteral("MIS") : order.product;
auto same = repo().find_position(order.portfolio_id, order.symbol, position_side);
if (same) {
PtPosition pos = *same;
- double new_qty = pos.quantity + qty;
+ double new_qty = pos.quantity + open_qty;
if (new_qty <= 0.0)
throw std::runtime_error("Invalid position quantity after averaging");
- double new_entry = (pos.entry_price * pos.quantity + fill_price * qty) / new_qty;
+ double new_entry = (pos.entry_price * pos.quantity + fill_price * open_qty) / new_qty;
repo().update_position(pos.id, new_qty, new_entry);
+ repo().set_position_margin(pos.id, pos.held_margin + open_margin);
} else {
- // 6. Brand new position
PtPosition np;
np.id = generate_uuid();
np.portfolio_id = order.portfolio_id;
np.symbol = order.symbol;
np.side = position_side;
- np.quantity = qty;
+ np.quantity = open_qty;
np.entry_price = fill_price;
np.current_price = fill_price;
- np.leverage = portfolio.leverage;
+ np.leverage = open_margin > 0.0 ? (open_qty * fill_price) / open_margin : portfolio.leverage;
np.opened_at = now;
+ np.product = product;
+ np.held_margin = open_margin;
repo().insert_position(np);
}
}
- // 7a. Release blocked margin (Phase 3 §4).
- // Margin was blocked from balance at placement for the net-new exposure.
- // Release it proportionally to the filled quantity on each (possibly
- // partial) fill. On the final fill, release whatever remains so rounding
- // never leaves margin stuck.
- double new_filled = order.filled_qty + qty;
- bool fully_filled = (new_filled >= order.quantity);
- double order_blocked = repo().get_margin_block(order_id);
- double margin_release = 0.0;
+ // ── Settle the order's margin block ──
if (order_blocked > 0.0) {
if (fully_filled) {
- margin_release = order_blocked; // release all remaining
repo().delete_margin_block(order_id);
} else {
- double frac = (order.quantity > 0.0) ? (qty / order.quantity) : 1.0;
- margin_release = order_blocked * frac;
- double remaining = std::max(0.0, order_blocked - margin_release);
+ double remaining = std::max(0.0, order_blocked - block_consumed);
repo().insert_margin_block(generate_uuid(), order.portfolio_id, order_id, order.symbol, remaining);
}
}
- // 7b. Update balance
- // Fee model: deduct fee only on closing fills (when realized PnL is produced).
- // Entry fees are NOT deducted from balance at open — they are included in the
- // exit fee when the position is closed. This matches how most exchanges present
- // unrealized P&L (gross of entry fee) and only settle fees on close.
- // Released margin is credited back to available balance alongside realized P&L.
- double balance_change = (had_opposite ? (pnl - fee) : pnl) + margin_release;
- repo().update_balance(order.portfolio_id, portfolio.balance + balance_change);
+ repo().update_balance(order.portfolio_id, portfolio.balance + balance_delta);
// 8. Update order
QString new_status = fully_filled ? "filled" : "partial";
@@ -591,4 +586,165 @@ PtStats pt_get_stats(const QString& portfolio_id) {
return r.value();
}
+// ============================================================================
+// Day-scoped queries / Settlement / Product conversion (v040)
+// ============================================================================
+
+namespace {
+
+// IST = UTC + 5:30. The UTC instant at which the given IST calendar day begins.
+QDateTime ist_day_start_utc(const QDate& ist_day) {
+ QDateTime utc_midnight(ist_day, QTime(0, 0, 0), Qt::UTC);
+ return utc_midnight.addSecs(-330 * 60); // shift IST-midnight back to its UTC instant
+}
+
+// The IST calendar date of a stored (naive/Z UTC) ISO timestamp.
+QDate ist_date_of(const QString& iso_utc, const QDate& fallback) {
+ QDateTime dt = QDateTime::fromString(iso_utc, Qt::ISODate);
+ if (!dt.isValid())
+ return fallback;
+ dt.setTimeSpec(Qt::UTC); // timestamps are UTC; reinterpret if no zone was parsed
+ return dt.addSecs(330 * 60).date();
+}
+
+} // namespace
+
+QVector<PtOrder> pt_get_orders_for_day(const QString& portfolio_id, const QDate& ist_day) {
+ const QDateTime start = ist_day_start_utc(ist_day);
+ auto r = repo().get_orders_between(portfolio_id, start.toString(Qt::ISODate),
+ start.addDays(1).toString(Qt::ISODate));
+ return r.is_ok() ? r.value() : QVector<PtOrder>{};
+}
+
+QVector<PtTrade> pt_get_trades_for_day(const QString& portfolio_id, const QDate& ist_day) {
+ const QDateTime start = ist_day_start_utc(ist_day);
+ auto r = repo().get_trades_between(portfolio_id, start.toString(Qt::ISODate),
+ start.addDays(1).toString(Qt::ISODate));
+ return r.is_ok() ? r.value() : QVector<PtTrade>{};
+}
+
+void pt_convert_position_product(const QString& position_id, const QString& new_product) {
+ QMutexLocker lock(&s_fill_mutex);
+
+ auto pr = repo().get_position(position_id);
+ if (pr.is_err())
+ throw std::runtime_error(pr.error());
+ PtPosition pos = pr.value();
+ if (pos.product.compare(new_product, Qt::CaseInsensitive) == 0)
+ return; // already that product — no-op
+
+ auto portfolio = pt_get_portfolio(pos.portfolio_id);
+
+ // Margin the position would lock under the NEW product, at its entry basis.
+ // (CNC/delivery = full notional at 1x; MIS = notional/leverage.)
+ const QString side = (pos.side == "long") ? "buy" : "sell";
+ const double new_margin = pt_calculate_required_margin(pos.portfolio_id, pos.symbol, QString(), new_product,
+ pos.quantity, pos.entry_price, side);
+ const double extra = new_margin - pos.held_margin; // additional cash to lock (CNC needs more than MIS)
+ if (extra > portfolio.balance + 1e-6)
+ throw std::runtime_error(("Insufficient balance to convert to " + new_product).toStdString());
+
+ auto& db = Database::instance();
+ db.begin_transaction();
+ try {
+ repo().update_balance(pos.portfolio_id, portfolio.balance - extra);
+ repo().set_position_margin(position_id, new_margin);
+ repo().set_position_product(position_id, new_product);
+ db.commit();
+ } catch (...) {
+ db.rollback();
+ throw;
+ }
+}
+
+int pt_settle_intraday(const QString& portfolio_id) {
+ // Intraday auto-square applies ONLY to Indian (INR) equity portfolios. Crypto
+ // and US (USD) paper portfolios trade on other schedules and must never be
+ // squared at the IST 15:30 cutoff (this previously closed month-old crypto
+ // positions because their product had defaulted to MIS).
+ PtPortfolio portfolio;
+ try {
+ portfolio = pt_get_portfolio(portfolio_id);
+ } catch (...) {
+ return 0;
+ }
+ if (portfolio.currency.compare("INR", Qt::CaseInsensitive) != 0)
+ return 0;
+
+ const QDateTime ist_now = QDateTime::currentDateTimeUtc().addSecs(330 * 60);
+ const QDate ist_today = ist_now.date();
+ const bool past_close = ist_now.time() >= QTime(15, 30);
+
+ int squared = 0;
+ const auto positions = pt_get_positions(portfolio_id);
+ for (const auto& pos : positions) {
+ if (!product_is_intraday(pos.product))
+ continue; // CNC / NRML carry forward
+ const QDate opened_ist = ist_date_of(pos.opened_at, ist_today);
+ const bool from_prior_day = opened_ist < ist_today;
+ if (!past_close && !from_prior_day)
+ continue; // still within today's session and not yet 15:30
+
+ const double price = pos.current_price > 0.0 ? pos.current_price : pos.entry_price;
+ if (price <= 0.0)
+ continue; // can't price the square-off
+
+ // Stamp the square-off at the session close it actually belongs to: 15:30
+ // IST on the day the position was opened. For a same-day position past the
+ // cutoff that's today's 15:30; for a carried-over position it's that prior
+ // day's close — so a catch-up auto-square lands in THAT day's book, never
+ // polluting today's order list with trades the user didn't place.
+ const QDateTime close_utc = QDateTime(opened_ist, QTime(15, 30, 0), Qt::UTC).addSecs(-330 * 60);
+ const QString close_iso = close_utc.toString(Qt::ISODate);
+
+ // Square off = insert a reduce-only market order on the opposite side and
+ // fill it at the last price. Reuses the fill engine's closing leg (margin
+ // release + realized P&L + trade record), and leaves an auto-square order
+ // in the book just like a real broker's 3:30 cutoff.
+ try {
+ PtOrder o;
+ o.id = generate_uuid();
+ o.portfolio_id = portfolio_id;
+ o.symbol = pos.symbol;
+ o.side = (pos.side == "long") ? QStringLiteral("sell") : QStringLiteral("buy");
+ o.order_type = "market";
+ o.quantity = pos.quantity;
+ o.price = price;
+ o.filled_qty = 0.0;
+ o.status = "pending";
+ o.reduce_only = true;
+ o.margin_blocked = 0.0;
+ o.product = pos.product;
+ o.created_at = close_iso;
+ auto ir = repo().insert_order(o);
+ if (ir.is_err())
+ continue;
+ pt_fill_order(o.id, price, std::nullopt, close_iso);
+ ++squared;
+ } catch (const std::exception& e) {
+ LOG_WARN("PaperTrading", QString("Auto-square failed for %1: %2").arg(pos.symbol, e.what()));
+ }
+ }
+
+ // Stale DAY orders from earlier IST sessions expire at the close — cancel them
+ // so they don't linger as pending or fire on a later day.
+ const auto pending = pt_get_orders(portfolio_id, "pending");
+ for (const auto& o : pending) {
+ if (ist_date_of(o.created_at, ist_today) < ist_today) {
+ try {
+ pt_cancel_order(o.id);
+ } catch (...) {
+ }
+ }
+ }
+ return squared;
+}
+
+int pt_settle_intraday_all() {
+ int total = 0;
+ for (const auto& p : pt_list_portfolios())
+ total += pt_settle_intraday(p.id);
+ return total;
+}
+
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/PaperTrading.h b/fincept-qt/src/trading/PaperTrading.h
index 98860370b..2c4c5f10f 100644
--- a/fincept-qt/src/trading/PaperTrading.h
+++ b/fincept-qt/src/trading/PaperTrading.h
@@ -4,6 +4,8 @@
#include "trading/TradingTypes.h"
+#include <QDate>
+
#include <optional>
#include <vector>
@@ -70,8 +72,37 @@ PtOrder pt_place_order(const QString& portfolio_id, const QString& symbol, const
void pt_cancel_order(const QString& order_id);
QVector<PtOrder> pt_get_orders(const QString& portfolio_id, const QString& status = "");
+// --- Day-scoped order/trade queries (v040) ---
+// Orders / executions whose timestamp falls on the given IST calendar day. Backs
+// the order book's per-day view (default today, date-selector for history), so the
+// book starts empty each session instead of accumulating every past order.
+QVector<PtOrder> pt_get_orders_for_day(const QString& portfolio_id, const QDate& ist_day);
+QVector<PtTrade> pt_get_trades_for_day(const QString& portfolio_id, const QDate& ist_day);
+
+// --- Product conversion (v040) ---
+// Convert an open position's broker product in place (e.g. MIS -> CNC). Re-prices
+// the locked margin to the new product (CNC/delivery needs full notional vs MIS
+// notional/leverage) and locks the extra from available balance; throws
+// std::runtime_error if the balance is insufficient. After an MIS->CNC convert the
+// position carries overnight (skipped by the 15:30 auto-square) and the Equity
+// screen renders it in the Holdings tab.
+void pt_convert_position_product(const QString& position_id, const QString& new_product);
+
+// --- Intraday settlement / auto square-off (v040) ---
+// Square off every open MIS (intraday) position at its last known price when the
+// IST clock is at/after 15:30, OR when the position was opened on an earlier IST
+// day (catch-up for when the app was closed at the cutoff). Also cancels stale
+// pending DAY orders left from prior sessions. CNC/NRML carry-forward positions are
+// untouched. Returns the number of positions squared off.
+int pt_settle_intraday(const QString& portfolio_id);
+int pt_settle_intraday_all();
+
// --- Fill (core engine logic) ---
-PtTrade pt_fill_order(const QString& order_id, double fill_price, std::optional<double> fill_qty = std::nullopt);
+// `fill_time` (ISO UTC) overrides the trade/fill timestamp; empty = now. Used by
+// intraday settlement to stamp an auto-square at the session close it belongs to
+// (so a catch-up square-off lands in that day's book, not today's).
+PtTrade pt_fill_order(const QString& order_id, double fill_price, std::optional<double> fill_qty = std::nullopt,
+ const QString& fill_time = {});
// --- Positions ---
QVector<PtPosition> pt_get_positions(const QString& portfolio_id);
diff --git a/fincept-qt/src/trading/TradingTypes.h b/fincept-qt/src/trading/TradingTypes.h
index 4ca1972eb..6034b9c01 100644
--- a/fincept-qt/src/trading/TradingTypes.h
+++ b/fincept-qt/src/trading/TradingTypes.h
@@ -93,6 +93,17 @@ struct PtPosition {
double leverage = 1.0;
std::optional<double> liquidation_price;
QString opened_at;
+
+ // NEW (v040): broker product type ("MIS"/"CNC"/"NRML") so the engine can tell
+ // intraday from delivery (15:30 MIS auto-square, MIS->CNC convert), and the
+ // margin locked from available balance while this position is open (released on
+ // close). Persisted in pt_positions. Defaults preserve pre-v040 behavior.
+ //
+ // Storage model: ALL open exposure lives in pt_positions tagged by product.
+ // The Equity screen renders CNC/delivery positions in the Holdings tab and
+ // MIS/NRML in the Positions tab (single source of truth, one fill path).
+ QString product = "MIS";
+ double held_margin = 0.0;
};
struct PtTrade {
@@ -109,13 +120,23 @@ struct PtTrade {
};
struct PtStats {
- double total_pnl = 0.0;
- double win_rate = 0.0;
+ double total_pnl = 0.0; // realized P&L from closed trades
+ double win_rate = 0.0; // winning_trades / total_trades (0..1)
int64_t total_trades = 0;
int64_t winning_trades = 0;
int64_t losing_trades = 0;
double largest_win = 0.0;
double largest_loss = 0.0;
+
+ // NEW: richer trade-derived aggregates (all from pt_trades).
+ double gross_profit = 0.0; // sum of positive trade P&L
+ double gross_loss = 0.0; // sum of negative trade P&L (<= 0)
+ double avg_win = 0.0; // gross_profit / winning_trades
+ double avg_loss = 0.0; // gross_loss / losing_trades (<= 0)
+ double profit_factor = 0.0; // gross_profit / |gross_loss|
+ double total_fees = 0.0; // sum of trade fees / charges
+ double turnover = 0.0; // sum of price * quantity across trades
+ double today_pnl = 0.0; // realized P&L from trades dated today (local)
};
struct PriceData {
@@ -207,6 +228,53 @@ inline const char* product_type_str(ProductType p) {
return "intraday";
}
+/// Indian-broker product mnemonic (MIS/CNC/NRML/...) for a ProductType. Used by
+/// the paper engine to tag positions/orders so intraday (MIS) can be told apart
+/// from delivery (CNC) for auto-square-off, product conversion and leverage.
+inline const char* product_to_broker_str(ProductType p) {
+ switch (p) {
+ case ProductType::Intraday:
+ return "MIS";
+ case ProductType::Delivery:
+ return "CNC";
+ case ProductType::Margin:
+ return "NRML";
+ case ProductType::CoverOrder:
+ return "CO";
+ case ProductType::BracketOrder:
+ return "BO";
+ case ProductType::MTF:
+ return "MTF";
+ }
+ return "MIS";
+}
+
+/// True when a broker product string denotes an intraday position that must be
+/// auto-squared at session close. Treats MIS / INTRADAY as intraday; everything
+/// else (CNC / NRML / delivery / margin / blank) is carry-forward.
+inline bool product_is_intraday(const QString& product) {
+ return product.compare("MIS", Qt::CaseInsensitive) == 0 ||
+ product.compare("intraday", Qt::CaseInsensitive) == 0;
+}
+
+/// True when a broker product string denotes a delivery holding (CNC / delivery).
+inline bool product_is_delivery(const QString& product) {
+ return product.compare("CNC", Qt::CaseInsensitive) == 0 ||
+ product.compare("delivery", Qt::CaseInsensitive) == 0;
+}
+
+/// Parse a broker product mnemonic (MIS/CNC/NRML/MTF) back to a ProductType.
+/// Inverse of product_to_broker_str; unknown/blank defaults to Intraday (MIS).
+inline ProductType product_from_broker_str(const QString& s) {
+ if (s.compare("CNC", Qt::CaseInsensitive) == 0 || s.compare("delivery", Qt::CaseInsensitive) == 0)
+ return ProductType::Delivery;
+ if (s.compare("NRML", Qt::CaseInsensitive) == 0 || s.compare("margin", Qt::CaseInsensitive) == 0)
+ return ProductType::Margin;
+ if (s.compare("MTF", Qt::CaseInsensitive) == 0)
+ return ProductType::MTF;
+ return ProductType::Intraday;
+}
+
struct UnifiedOrder {
QString symbol;
QString exchange;
diff --git a/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp b/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp
index 961b737d5..13c9b34e8 100644
--- a/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp
@@ -128,6 +128,37 @@ QString format_strike(double strike) {
return s;
}
+QString expiry_friendly(const QString& display_expiry) {
+ // Stored form is "DD-MMM-YY" (e.g. "07-JUL-26"). Make it "7 Jul 26": drop the
+ // day's leading zero and title-case the month.
+ const QStringList parts = display_expiry.split('-', Qt::SkipEmptyParts);
+ if (parts.size() != 3)
+ return display_expiry;
+ const int day = parts[0].toInt();
+ if (day <= 0)
+ return display_expiry;
+ const QString mon = parts[1].left(1).toUpper() + parts[1].mid(1).toLower();
+ return QStringLiteral("%1 %2 %3").arg(QString::number(day), mon, parts[2]);
+}
+
+QString display_name(const QString& name, InstrumentType itype, const QString& expiry, double strike,
+ const QString& fallback_symbol) {
+ switch (itype) {
+ case InstrumentType::FUT:
+ return QStringLiteral("%1 %2 FUT").arg(name, expiry_friendly(expiry));
+ case InstrumentType::CE:
+ return QStringLiteral("%1 %2 %3 CE").arg(name, expiry_friendly(expiry), format_strike(strike));
+ case InstrumentType::PE:
+ return QStringLiteral("%1 %2 %3 PE").arg(name, expiry_friendly(expiry), format_strike(strike));
+ case InstrumentType::INDEX:
+ return name.isEmpty() ? fallback_symbol : name;
+ case InstrumentType::EQ:
+ case InstrumentType::UNKNOWN:
+ default:
+ return fallback_symbol.isEmpty() ? name : fallback_symbol;
+ }
+}
+
QString strip_eq_suffix(const QString& trading_symbol) {
QString s = trading_symbol.trimmed().toUpper();
static const QRegularExpression re("(-EQ|-BE|-MF|-SG|-SM)$");
diff --git a/fincept-qt/src/trading/instruments/InstrumentNormalize.h b/fincept-qt/src/trading/instruments/InstrumentNormalize.h
index ca0999903..fafaf95b2 100644
--- a/fincept-qt/src/trading/instruments/InstrumentNormalize.h
+++ b/fincept-qt/src/trading/instruments/InstrumentNormalize.h
@@ -32,6 +32,20 @@ QString expiry_display(const QString& raw);
/// decimal; fractional values are trimmed of trailing zeros.
QString format_strike(double strike);
+/// Human-friendly expiry for symbol pickers: "07-JUL-26" → "7 Jul 26".
+/// Returns the input unchanged if it isn't the stored DD-MMM-YY form.
+QString expiry_friendly(const QString& display_expiry);
+
+/// Human-readable picker label so users aren't shown the raw canonical symbol
+/// (e.g. NIFTY07JUL2618250CE). Built from the catalog fields:
+/// FUT → "NIFTY 30 Jun 26 FUT"
+/// CE/PE → "NIFTY 7 Jul 26 18250 CE"
+/// EQ → the trading symbol (already clean, e.g. RELIANCE)
+/// INDEX → the underlying name (e.g. NIFTY)
+/// `fallback_symbol` is used for EQ / when fields are missing.
+QString display_name(const QString& name, InstrumentType itype, const QString& expiry, double strike,
+ const QString& fallback_symbol);
+
/// RELIANCE-EQ / -BE / -MF / -SG / -SM → RELIANCE (case-insensitive suffix).
QString strip_eq_suffix(const QString& trading_symbol);
diff --git a/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp b/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp
index 057fa6ada..a88be052e 100644
--- a/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp
+++ b/fincept-qt/src/ui/components/ComponentBrowserDialog.cpp
@@ -3,6 +3,7 @@
#include "core/components/ComponentCatalog.h"
#include "core/components/PopularityTracker.h"
#include "ui/components/ComponentCard.h"
+#include "ui/theme/Theme.h"
#include <QGridLayout>
#include <QHBoxLayout>
@@ -39,7 +40,10 @@ ComponentBrowserDialog::ComponentBrowserDialog(QWidget* parent) : QDialog(parent
setWindowTitle(tr("Component Browser"));
setModal(true);
resize(960, 640);
- setStyleSheet("QDialog{background:#0f172a;} QLabel{color:#e5e7eb;}");
+ setStyleSheet(QString("QDialog{background:%1;font-family:%2;} QLabel{color:%3;}")
+ .arg(colors::BG_BASE())
+ .arg(fonts::DATA_FAMILY())
+ .arg(colors::TEXT_PRIMARY()));
build_ui();
rebuild_cards();
}
@@ -52,13 +56,16 @@ void ComponentBrowserDialog::build_ui() {
// Header bar — title + search.
auto* header = new QWidget(this);
header->setFixedHeight(56);
- header->setStyleSheet("background:#111827;border-bottom:1px solid #374151;");
+ header->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
+ .arg(colors::BG_RAISED())
+ .arg(colors::BORDER_MED()));
auto* hl = new QHBoxLayout(header);
hl->setContentsMargins(16, 8, 16, 8);
hl->setSpacing(12);
title_label_ = new QLabel(tr("COMPONENT BROWSER"), header);
- title_label_->setStyleSheet("color:#d97706;font-size:13px;font-weight:700;letter-spacing:2px;");
+ title_label_->setStyleSheet(
+ QString("color:%1;font-size:13px;font-weight:700;letter-spacing:2px;").arg(colors::AMBER()));
hl->addWidget(title_label_);
hl->addSpacing(24);
@@ -67,16 +74,20 @@ void ComponentBrowserDialog::build_ui() {
search_->setPlaceholderText(tr("Search components…"));
search_->setClearButtonEnabled(true);
search_->setStyleSheet(
- "QLineEdit{background:#0b1220;border:1px solid #374151;border-radius:3px;"
- "color:#f3f4f6;padding:6px 10px;min-width:280px;}"
- "QLineEdit:focus{border-color:#d97706;}");
+ QString("QLineEdit{background:%1;border:1px solid %2;border-radius:2px;"
+ "color:%3;padding:6px 10px;min-width:280px;}"
+ "QLineEdit:focus{border-color:%4;}")
+ .arg(colors::BG_SURFACE())
+ .arg(colors::BORDER_MED())
+ .arg(colors::TEXT_PRIMARY())
+ .arg(colors::AMBER()));
connect(search_, &QLineEdit::textChanged, this, &ComponentBrowserDialog::on_search_changed);
hl->addWidget(search_);
hl->addStretch(1);
count_label_ = new QLabel(header);
- count_label_->setStyleSheet("color:#9ca3af;font-size:11px;");
+ count_label_->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
hl->addWidget(count_label_);
root->addWidget(header);
@@ -90,10 +101,16 @@ void ComponentBrowserDialog::build_ui() {
category_list_ = new QListWidget(split);
category_list_->setFixedWidth(180);
category_list_->setStyleSheet(
- "QListWidget{background:#0b1220;border:none;border-right:1px solid #374151;color:#e5e7eb;}"
- "QListWidget::item{padding:8px 14px;border:none;}"
- "QListWidget::item:selected{background:#1f2937;color:#d97706;border-left:3px solid #d97706;}"
- "QListWidget::item:hover{background:#111827;}");
+ QString("QListWidget{background:%1;border:none;border-right:1px solid %2;color:%3;}"
+ "QListWidget::item{padding:8px 14px;border:none;}"
+ "QListWidget::item:selected{background:%4;color:%5;border-left:3px solid %5;}"
+ "QListWidget::item:hover{background:%6;}")
+ .arg(colors::BG_SURFACE())
+ .arg(colors::BORDER_MED())
+ .arg(colors::TEXT_SECONDARY())
+ .arg(colors::BG_HOVER())
+ .arg(colors::AMBER())
+ .arg(colors::BG_RAISED()));
// Row 0 is the "All" sentinel: translated display text, empty UserRole.
// Other rows store the real (non-translated) category id in UserRole so
// filtering stays stable regardless of the active locale.
@@ -111,7 +128,7 @@ void ComponentBrowserDialog::build_ui() {
scroll_ = new QScrollArea(split);
scroll_->setWidgetResizable(true);
scroll_->setFrameShape(QFrame::NoFrame);
- scroll_->setStyleSheet("background:#0f172a;");
+ scroll_->setStyleSheet(QString("background:%1;").arg(colors::BG_BASE()));
grid_host_ = new QWidget;
grid_host_->setStyleSheet("background:transparent;");
grid_layout_ = new QGridLayout(grid_host_);
diff --git a/fincept-qt/src/ui/components/ComponentCard.cpp b/fincept-qt/src/ui/components/ComponentCard.cpp
index 11b391917..7d71d7541 100644
--- a/fincept-qt/src/ui/components/ComponentCard.cpp
+++ b/fincept-qt/src/ui/components/ComponentCard.cpp
@@ -1,5 +1,7 @@
#include "ui/components/ComponentCard.h"
+#include "ui/theme/Theme.h"
+
#include <QApplication>
#include <QDrag>
#include <QFontMetrics>
@@ -78,18 +80,19 @@ void ComponentCard::build_ui() {
cat_row->addWidget(cat);
cat_row->addStretch(1);
auto* stars = new QLabel(popularity_stars(meta_.popularity), body);
- stars->setStyleSheet("color:#d97706;font-size:12px;");
+ stars->setStyleSheet(QString("color:%1;font-size:12px;").arg(colors::AMBER()));
stars->setToolTip(QString("Use count: %1").arg(meta_.popularity));
cat_row->addWidget(stars);
bl->addLayout(cat_row);
auto* title = new QLabel(meta_.title, body);
- title->setStyleSheet("color:#f3f4f6;font-size:14px;font-weight:700;");
+ title->setStyleSheet(
+ QString("color:%1;font-size:14px;font-weight:700;").arg(colors::TEXT_PRIMARY()));
bl->addWidget(title);
auto* desc = new QLabel(body);
desc->setWordWrap(true);
- desc->setStyleSheet("color:#9ca3af;font-size:11px;");
+ desc->setStyleSheet(QString("color:%1;font-size:11px;").arg(colors::TEXT_SECONDARY()));
const QString text = meta_.description.isEmpty() ? QStringLiteral(" ") : meta_.description;
desc->setText(text);
desc->setMaximumHeight(36);
@@ -100,16 +103,16 @@ void ComponentCard::build_ui() {
}
void ComponentCard::restyle() {
- QString border = "#374151";
- QString bg = "#111827";
+ QString border = colors::BORDER_MED();
+ QString bg = colors::BG_SURFACE();
if (selected_) {
- border = "#d97706";
- bg = "#1f2937";
+ border = colors::AMBER();
+ bg = colors::BG_HOVER();
} else if (hovered_) {
- border = "#6b7280";
- bg = "#1a2332";
+ border = colors::BORDER_BRIGHT();
+ bg = colors::BG_RAISED();
}
- setStyleSheet(QString("#componentCard{background:%1;border:1px solid %2;border-radius:4px;}")
+ setStyleSheet(QString("#componentCard{background:%1;border:1px solid %2;border-radius:2px;}")
.arg(bg, border));
}
diff --git a/fincept-qt/src/ui/notifications/DesktopNotifier.cpp b/fincept-qt/src/ui/notifications/DesktopNotifier.cpp
new file mode 100644
index 000000000..09aaef933
--- /dev/null
+++ b/fincept-qt/src/ui/notifications/DesktopNotifier.cpp
@@ -0,0 +1,127 @@
+// src/ui/notifications/DesktopNotifier.cpp
+#include "ui/notifications/DesktopNotifier.h"
+
+#include "core/logging/Logger.h"
+#include "ui/notifications/NotificationService.h" // ToastService
+
+#include <QApplication>
+#include <QGuiApplication>
+#include <QIcon>
+#include <QLabel>
+#include <QMenu>
+#include <QScreen>
+#include <QStyle>
+#include <QSystemTrayIcon>
+#include <QTimer>
+#include <QVBoxLayout>
+#include <QWidget>
+
+namespace fincept::ui {
+
+DesktopNotifier& DesktopNotifier::instance() {
+ static DesktopNotifier s;
+ return s;
+}
+
+void DesktopNotifier::init() {
+ if (tray_)
+ return;
+ if (!QSystemTrayIcon::isSystemTrayAvailable()) {
+ LOG_WARN("DesktopNotifier", "No system tray available — native notifications disabled");
+ return;
+ }
+
+ tray_ = new QSystemTrayIcon(this);
+ QIcon ico = QApplication::windowIcon();
+ if (ico.isNull())
+ ico = qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation);
+ tray_->setIcon(ico);
+ tray_->setToolTip(QStringLiteral("Fincept Terminal"));
+
+ auto* menu = new QMenu();
+ menu->addAction(QStringLiteral("Show Fincept"), qApp, []() {
+ for (auto* tw : qApp->topLevelWidgets()) {
+ if (tw->isWindow() && !tw->inherits("QMenu")) {
+ tw->showNormal();
+ tw->raise();
+ tw->activateWindow();
+ break;
+ }
+ }
+ });
+ menu->addSeparator();
+ menu->addAction(QStringLiteral("Quit"), qApp, &QApplication::quit);
+ tray_->setContextMenu(menu);
+ tray_->show();
+
+ // The missing wire: ToastService::posted had no listener, so every alert
+ // toast was silent. Mirror each one to a native OS notification.
+ connect(&ToastService::instance(), &ToastService::posted, this,
+ [this](const ToastService::Notification& n) {
+ const QString title = n.source.startsWith(QStringLiteral("scan:"))
+ ? QStringLiteral("Fincept Alert")
+ : QStringLiteral("Fincept Terminal");
+ notify(title, n.message, static_cast<int>(n.severity));
+ show_inapp(title, n.message, static_cast<int>(n.severity));
+ });
+
+ LOG_INFO("DesktopNotifier", "Native desktop notifications enabled");
+}
+
+void DesktopNotifier::notify(const QString& title, const QString& body, int severity) {
+ if (!tray_ || !QSystemTrayIcon::supportsMessages())
+ return;
+ QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::Information;
+ switch (static_cast<ToastService::Severity>(severity)) {
+ case ToastService::Severity::Warning:
+ icon = QSystemTrayIcon::Warning;
+ break;
+ case ToastService::Severity::Error:
+ icon = QSystemTrayIcon::Critical;
+ break;
+ case ToastService::Severity::Info:
+ case ToastService::Severity::Success:
+ default:
+ icon = QSystemTrayIcon::Information;
+ break;
+ }
+ tray_->showMessage(title, body, icon, 30000);
+}
+
+void DesktopNotifier::show_inapp(const QString& title, const QString& body, int severity) {
+ QString accent = QStringLiteral("#00BFA5");
+ switch (static_cast<ToastService::Severity>(severity)) {
+ case ToastService::Severity::Warning: accent = QStringLiteral("#FFC400"); break;
+ case ToastService::Severity::Error: accent = QStringLiteral("#FF5252"); break;
+ case ToastService::Severity::Success: accent = QStringLiteral("#26C281"); break;
+ default: break;
+ }
+ if (!toast_) {
+ toast_ = new QWidget(nullptr, Qt::ToolTip | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
+ toast_->setAttribute(Qt::WA_ShowWithoutActivating);
+ toast_->setFixedWidth(360);
+ auto* lay = new QVBoxLayout(toast_);
+ lay->setContentsMargins(14, 12, 14, 12);
+ toast_lbl_ = new QLabel(toast_);
+ toast_lbl_->setTextFormat(Qt::RichText);
+ toast_lbl_->setWordWrap(true);
+ lay->addWidget(toast_lbl_);
+ toast_timer_ = new QTimer(this);
+ toast_timer_->setSingleShot(true);
+ connect(toast_timer_, &QTimer::timeout, toast_, [this]() { if (toast_) toast_->hide(); });
+ }
+ toast_->setStyleSheet(QString("background:#15181d; border:1px solid %1; border-radius:8px;").arg(accent));
+ toast_lbl_->setStyleSheet(QStringLiteral("color:#e6e6e6; font-size:12px; background:transparent; border:none;"));
+ toast_lbl_->setText(QString("<b style='color:%1; font-size:13px;'>%2</b><br><span>%3</span>")
+ .arg(accent, title.toHtmlEscaped(), body.toHtmlEscaped()));
+ toast_->adjustSize();
+ if (auto* scr = QGuiApplication::primaryScreen()) {
+ const QRect g = scr->availableGeometry();
+ toast_->move(g.right() - toast_->width() - 24, g.top() + 24);
+ }
+ toast_->show();
+ toast_->raise();
+ toast_timer_->start(20000); // stay ~20s on screen
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/notifications/DesktopNotifier.h b/fincept-qt/src/ui/notifications/DesktopNotifier.h
new file mode 100644
index 000000000..3190507ca
--- /dev/null
+++ b/fincept-qt/src/ui/notifications/DesktopNotifier.h
@@ -0,0 +1,47 @@
+// src/ui/notifications/DesktopNotifier.h
+#pragma once
+#include <QObject>
+#include <QString>
+
+class QSystemTrayIcon;
+class QWidget;
+class QLabel;
+class QTimer;
+
+namespace fincept::ui {
+
+/// Cross-platform native desktop notifications, backed by QSystemTrayIcon.
+/// Qt maps showMessage() to the platform's native channel:
+/// Windows → toast / balloon, macOS → Notification Center, Linux → libnotify.
+/// Listens to ToastService::posted so every in-app toast (alerts, errors, …)
+/// also raises a real OS notification — this is the connection that was missing,
+/// which is why fired alerts were silent. Singleton; GUI thread only.
+class DesktopNotifier : public QObject {
+ Q_OBJECT
+ public:
+ static DesktopNotifier& instance();
+
+ /// Create the tray icon + wire ToastService. Call once at startup on the GUI
+ /// thread, after the app/window icon is set. No-op if already initialised or
+ /// no system tray is available.
+ void init();
+
+ /// Raise a native OS notification immediately. `severity` is a
+ /// ToastService::Severity cast to int.
+ void notify(const QString& title, const QString& body, int severity = 0);
+
+ private:
+ DesktopNotifier() = default;
+ Q_DISABLE_COPY(DesktopNotifier)
+
+ /// Self-rendered in-app toast that stays visible ~20s (native OS banners
+ /// auto-dismiss in a few seconds and ignore the duration hint on macOS).
+ void show_inapp(const QString& title, const QString& body, int severity);
+
+ QSystemTrayIcon* tray_ = nullptr;
+ QWidget* toast_ = nullptr;
+ QLabel* toast_lbl_ = nullptr;
+ QTimer* toast_timer_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/WorldMapWidget.cpp b/fincept-qt/src/ui/widgets/WorldMapWidget.cpp
index b1f9ec437..485dc82c8 100644
--- a/fincept-qt/src/ui/widgets/WorldMapWidget.cpp
+++ b/fincept-qt/src/ui/widgets/WorldMapWidget.cpp
@@ -7,7 +7,7 @@
#include <QGeoView/QGVDrawItem.h>
#include <QGeoView/QGVGlobal.h>
#include <QGeoView/QGVLayer.h>
-#include <QGeoView/QGVLayerOSM.h>
+#include <QGeoView/QGVLayerTilesOnline.h>
#include <QGeoView/QGVMap.h>
#include <QGeoView/QGVProjection.h>
#include <QGeoView/QGVWidgetScale.h>
@@ -33,6 +33,77 @@ namespace fincept::ui {
// callback. Pins that don't carry an id (the default -1) skip the wiring
// entirely so non-interactive maps stay free of click overhead.
namespace {
+
+// ── Basemap catalog ─────────────────────────────────────────────────────────
+//
+// One entry per selectable basemap. `url` is an OSM-style ${z}/${x}/${y}
+// template; some providers (Esri) order the path as ${z}/${y}/${x}. zoom
+// bounds cap tile requests so the map upscales the deepest available tile
+// instead of asking the server for a level it doesn't serve (which Esri
+// answers with a "Map data not available" placeholder image).
+struct BasemapDef {
+ QString label;
+ QString url;
+ int min_zoom;
+ int max_zoom;
+};
+
+const QVector<BasemapDef>& basemap_catalog() {
+ static const QVector<BasemapDef> kCatalog = {
+ {QStringLiteral("SATELLITE"),
+ QStringLiteral("https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/"
+ "MapServer/tile/${z}/${y}/${x}"),
+ 0, 19},
+ {QStringLiteral("DARK"),
+ QStringLiteral("https://basemaps.cartocdn.com/dark_all/${z}/${x}/${y}.png"),
+ 0, 20},
+ {QStringLiteral("OCEAN"),
+ QStringLiteral("https://server.arcgisonline.com/ArcGIS/rest/services/Ocean/"
+ "World_Ocean_Base/MapServer/tile/${z}/${y}/${x}"),
+ 0, 13},
+ {QStringLiteral("STREETS"),
+ QStringLiteral("https://tile.openstreetmap.org/${z}/${x}/${y}.png"),
+ 0, 19},
+ {QStringLiteral("LIGHT"),
+ QStringLiteral("https://basemaps.cartocdn.com/light_all/${z}/${x}/${y}.png"),
+ 0, 20},
+ {QStringLiteral("TERRAIN"),
+ QStringLiteral("https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/"
+ "MapServer/tile/${z}/${y}/${x}"),
+ 0, 19},
+ };
+ return kCatalog;
+}
+
+// ── Tile layer ──────────────────────────────────────────────────────────────
+//
+// Drop-in for QGVLayerOSM. Two reasons not to use QGVLayerOSM directly:
+// 1. Its tilePosToUrl() lowercases the WHOLE url — fatal for case-sensitive
+// provider paths like Esri's `.../World_Imagery/MapServer/...` (the
+// lowercased path 404s and the server returns an error tile).
+// 2. Its zoom range is hardcoded 0–20; per-provider caps let us stop at the
+// deepest level a service actually publishes.
+class FinceptTileLayer : public QGVLayerTilesOnline {
+ public:
+ FinceptTileLayer(QString url, int min_zoom, int max_zoom)
+ : url_(std::move(url)), min_zoom_(min_zoom), max_zoom_(max_zoom) {}
+
+ private:
+ int minZoomlevel() const override { return min_zoom_; }
+ int maxZoomlevel() const override { return max_zoom_; }
+ QString tilePosToUrl(const QGV::GeoTilePos& tilePos) const override {
+ QString url = url_; // case-preserving (unlike QGVLayerOSM)
+ url.replace(QStringLiteral("${z}"), QString::number(tilePos.zoom()));
+ url.replace(QStringLiteral("${x}"), QString::number(tilePos.pos().x()));
+ url.replace(QStringLiteral("${y}"), QString::number(tilePos.pos().y()));
+ return url;
+ }
+
+ QString url_;
+ int min_zoom_;
+ int max_zoom_;
+};
+
class ClickableIcon : public QGVIcon {
public:
explicit ClickableIcon(int id, QString tooltip, std::function<void(int)> on_click)
@@ -111,6 +182,51 @@ class ShapeDrawItem : public QGVDrawItem {
QGVMap* map_ = nullptr;
};
+// ── Track polyline item ──────────────────────────────────────────────────────
+//
+// Draws an ordered list of geo points as a connected amber polyline (a voyage
+// track). Geometry is rebuilt in projection space each paint so it follows
+// pan/zoom. Points are (lat, lng).
+class PathDrawItem : public QGVDrawItem {
+ public:
+ PathDrawItem(QVector<QPointF> pts, QGVMap* map) : pts_(std::move(pts)), map_(map) {}
+
+ QPainterPath projShape() const override {
+ QPainterPath path;
+ auto* proj = map_ ? map_->getProjection() : nullptr;
+ if (!proj || pts_.size() < 2)
+ return path;
+ bool first = true;
+ for (const QPointF& p : pts_) {
+ const QPointF pr = proj->geoToProj(QGV::GeoPos(p.x(), p.y())); // x=lat, y=lng
+ if (first) {
+ path.moveTo(pr);
+ first = false;
+ } else {
+ path.lineTo(pr);
+ }
+ }
+ return path;
+ }
+
+ void projPaint(QPainter* painter) override {
+ const QPainterPath path = projShape();
+ if (path.isEmpty())
+ return;
+ QPen pen(QColor(0xF5, 0x9E, 0x0B, 205)); // amber, matches the trail dots
+ pen.setCosmetic(true); // constant width regardless of zoom
+ pen.setWidthF(2.0);
+ pen.setJoinStyle(Qt::RoundJoin);
+ painter->setPen(pen);
+ painter->setBrush(Qt::NoBrush);
+ painter->drawPath(path);
+ }
+
+ private:
+ QVector<QPointF> pts_;
+ QGVMap* map_ = nullptr;
+};
+
} // namespace
// ── MapShape ─────────────────────────────────────────────────────────────────
@@ -151,9 +267,8 @@ WorldMapWidget::WorldMapWidget(QWidget* parent) : QWidget(parent) {
view->setBackgroundBrush(QColor(0x08, 0x08, 0x08));
}
- // Use CartoDB Dark Matter tiles
- auto* tiles = new QGVLayerOSM(QStringLiteral("https://basemaps.cartocdn.com/dark_all/${z}/${x}/${y}.png"));
- map_->addItem(tiles);
+ // Install the default basemap (SATELLITE). set_basemap() can swap it later.
+ apply_basemap(basemap_index_);
// Zoom controls
map_->addWidget(new QGVWidgetZoom());
@@ -162,6 +277,10 @@ WorldMapWidget::WorldMapWidget(QWidget* parent) : QWidget(parent) {
// Enable mouse interactions
map_->setMouseActions(QGV::MouseAction::All);
+ // Track-polyline layer (added before markers so the line draws under pins).
+ path_layer_ = new QGVLayer();
+ map_->addItem(path_layer_);
+
// Marker layer
marker_layer_ = new QGVLayer();
map_->addItem(marker_layer_);
@@ -180,6 +299,46 @@ WorldMapWidget::WorldMapWidget(QWidget* parent) : QWidget(parent) {
map_ready_ = true;
}
+// ── Basemap selection ───────────────────────────────────────────────────────
+
+QStringList WorldMapWidget::basemap_labels() {
+ QStringList out;
+ out.reserve(basemap_catalog().size());
+ for (const auto& b : basemap_catalog())
+ out << b.label;
+ return out;
+}
+
+void WorldMapWidget::set_basemap(int index) {
+ if (index == basemap_index_ && !tile_layers_.isEmpty())
+ return;
+ apply_basemap(index);
+}
+
+void WorldMapWidget::apply_basemap(int index) {
+ if (!map_)
+ return;
+ const auto& cat = basemap_catalog();
+ if (index < 0 || index >= cat.size())
+ return;
+
+ // Drop the previous tile layer(s).
+ for (auto* layer : tile_layers_) {
+ map_->removeItem(layer);
+ delete layer;
+ }
+ tile_layers_.clear();
+
+ const BasemapDef& def = cat[index];
+ auto* layer = new FinceptTileLayer(def.url, def.min_zoom, def.max_zoom);
+ map_->addItem(layer);
+ // Tiles must sit beneath the marker and shape layers regardless of when
+ // the basemap is swapped, so push them to the back of the z-order.
+ layer->sendToBack();
+ tile_layers_.append(layer);
+ basemap_index_ = index;
+}
+
// ── Marker image generation ─────────────────────────────────────────────────
QImage WorldMapWidget::make_marker_image(const QColor& color, double radius) const {
@@ -255,6 +414,35 @@ void WorldMapWidget::rebuild_markers() {
void WorldMapWidget::set_pins(const QVector<MapPin>& pins) {
pins_ = pins;
rebuild_markers();
+ // A fresh pin set implies a new context — drop any stale track polyline.
+ // Callers that want a path (e.g. voyage history) call set_track_path after.
+ clear_track_path();
+}
+
+// ── Track polyline ──────────────────────────────────────────────────────────
+
+void WorldMapWidget::set_track_path(const QVector<QPointF>& latlng_points) {
+ track_points_ = latlng_points;
+ rebuild_path_overlay();
+}
+
+void WorldMapWidget::clear_track_path() {
+ if (track_points_.isEmpty())
+ return;
+ track_points_.clear();
+ rebuild_path_overlay();
+}
+
+void WorldMapWidget::rebuild_path_overlay() {
+ if (!map_ready_ || !path_layer_)
+ return;
+ while (path_layer_->countItems() > 0) {
+ auto* item = path_layer_->getItem(0);
+ path_layer_->removeItem(item);
+ delete item;
+ }
+ if (track_points_.size() >= 2)
+ path_layer_->addItem(new PathDrawItem(track_points_, map_));
}
void WorldMapWidget::add_pin(const MapPin& pin) {
@@ -284,7 +472,9 @@ void WorldMapWidget::fly_to(double lat, double lng, int zoom) {
Q_UNUSED(zoom);
if (!map_ready_)
return;
- double d = 5.0;
+ // ~2.5° half-extent → a close regional zoom centred on the point, tight
+ // enough to clearly show a single tracked vessel / port with context.
+ double d = 2.5;
auto target = QGV::GeoRect(QGV::GeoPos(lat + d, lng - d * 1.5), QGV::GeoPos(lat - d, lng + d * 1.5));
map_->flyTo(QGVCameraActions(map_).scaleTo(target));
}
@@ -319,11 +509,11 @@ void WorldMapWidget::fit_to_pins() {
return;
}
- // Pad proportionally to the span — 10% per side. Floor of 4° / 6° keeps a
- // single pin or tightly-clustered pins from zooming in absurdly far while
- // staying visually tight enough to avoid empty black space.
- double lat_pad = std::max(lat_span * 0.1, 4.0);
- double lng_pad = std::max(lng_span * 0.1, 6.0);
+ // Pad proportionally to the span — 10% per side. Small floors keep a single
+ // pin / tight cluster from zooming in absurdly far, but stay tight enough to
+ // actually frame the vessels instead of opening on a near-global view.
+ double lat_pad = std::max(lat_span * 0.1, 1.5);
+ double lng_pad = std::max(lng_span * 0.1, 2.0);
double box_min_lat = min_lat - lat_pad;
double box_max_lat = max_lat + lat_pad;
diff --git a/fincept-qt/src/ui/widgets/WorldMapWidget.h b/fincept-qt/src/ui/widgets/WorldMapWidget.h
index c0f9151a4..f842ca20f 100644
--- a/fincept-qt/src/ui/widgets/WorldMapWidget.h
+++ b/fincept-qt/src/ui/widgets/WorldMapWidget.h
@@ -3,12 +3,15 @@
#include <QColor>
#include <QHash>
#include <QImage>
+#include <QPoint>
#include <QString>
+#include <QStringList>
#include <QVector>
#include <QWidget>
class QGVMap;
class QGVLayer;
+class QGVItem;
namespace fincept::ui {
@@ -60,6 +63,22 @@ class WorldMapWidget : public QWidget {
void clear_pins();
int pin_count() const { return pins_.size(); }
+ /// Draw a connecting polyline through the ordered lat/lng points (a voyage
+ /// track), rendered beneath the marker pins. Each QPointF is (lat, lng).
+ /// Fewer than 2 points clears it. set_pins() also clears any existing path.
+ void set_track_path(const QVector<QPointF>& latlng_points);
+ void clear_track_path();
+
+ // ── Basemap selection ───────────────────────────────────────────────────
+ /// Display labels for the available basemaps, in selector order
+ /// (SATELLITE, DARK, OCEAN, STREETS, LIGHT, TERRAIN). Use to populate a
+ /// QComboBox; the index maps 1:1 to set_basemap().
+ static QStringList basemap_labels();
+ /// Switch the active basemap by index into basemap_labels(). Preserves the
+ /// current camera, pins, and drawn shapes. Out-of-range indices are ignored.
+ void set_basemap(int index);
+ int current_basemap_index() const { return basemap_index_; }
+
/// Fly the camera to show a specific region
void fly_to(double lat, double lng, int zoom = 5);
@@ -88,7 +107,12 @@ class WorldMapWidget : public QWidget {
bool eventFilter(QObject* watched, QEvent* event) override;
private:
+ /// Tear down the current tile layer(s) and install the basemap at `index`
+ /// from the internal catalog. Sends the new tiles to the back so the
+ /// marker and shape layers keep drawing on top.
+ void apply_basemap(int index);
void rebuild_markers();
+ void rebuild_path_overlay();
void rebuild_shape_overlays();
QImage make_marker_image(const QColor& color, double radius) const;
/// Convert a viewport pixel (in the QGraphicsView) to geographic lat/lng.
@@ -101,7 +125,14 @@ class WorldMapWidget : public QWidget {
QGVMap* map_ = nullptr;
QGVLayer* marker_layer_ = nullptr;
+ QGVLayer* path_layer_ = nullptr;
QGVLayer* shape_layer_ = nullptr;
+ /// Ordered (lat, lng) points of the current track polyline, if any.
+ QVector<QPointF> track_points_;
+ /// Active basemap tile layer(s). Owned by the map once added; replaced
+ /// wholesale on set_basemap(). Usually one layer.
+ QVector<QGVItem*> tile_layers_;
+ int basemap_index_ = 0; // index into the basemap catalog; 0 = SATELLITE
QVector<MapPin> pins_;
mutable QHash<QString, QImage> marker_cache_;
bool map_ready_ = false;
diff --git a/fincept-qt/src/ui/widgets/algo/SymbolChipInput.cpp b/fincept-qt/src/ui/widgets/algo/SymbolChipInput.cpp
new file mode 100644
index 000000000..e7c5f49d8
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/SymbolChipInput.cpp
@@ -0,0 +1,291 @@
+// src/ui/widgets/algo/SymbolChipInput.cpp
+#include "ui/widgets/algo/SymbolChipInput.h"
+
+#include "services/markets/MarketDataService.h"
+#include "trading/AccountManager.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentService.h"
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
+#include <QCompleter>
+#include <QEvent>
+#include <QFontMetrics>
+#include <QFrame>
+#include <QHBoxLayout>
+#include <QKeyEvent>
+#include <QLabel>
+#include <QLayout>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QRegularExpression>
+#include <QStringListModel>
+#include <QStyle>
+
+namespace fincept::ui::algo {
+
+// ── Minimal flow layout (wraps children to new rows) — standard Qt example ──
+class FlowLayout : public QLayout {
+ public:
+ explicit FlowLayout(QWidget* parent, int margin = 4, int hspace = 4, int vspace = 4)
+ : QLayout(parent), hspace_(hspace), vspace_(vspace) { setContentsMargins(margin, margin, margin, margin); }
+ ~FlowLayout() override { QLayoutItem* it; while ((it = takeAt(0))) delete it; }
+ void addItem(QLayoutItem* item) override { items_.append(item); }
+ int count() const override { return items_.size(); }
+ QLayoutItem* itemAt(int i) const override { return items_.value(i); }
+ QLayoutItem* takeAt(int i) override { return (i >= 0 && i < items_.size()) ? items_.takeAt(i) : nullptr; }
+ Qt::Orientations expandingDirections() const override { return {}; }
+ bool hasHeightForWidth() const override { return true; }
+ int heightForWidth(int w) const override { return do_layout(QRect(0, 0, w, 0), true); }
+ void setGeometry(const QRect& r) override { QLayout::setGeometry(r); do_layout(r, false); }
+ QSize sizeHint() const override { return minimumSize(); }
+ QSize minimumSize() const override {
+ QSize s; for (auto* it : items_) s = s.expandedTo(it->minimumSize());
+ const QMargins m = contentsMargins(); s += QSize(m.left() + m.right(), m.top() + m.bottom()); return s;
+ }
+ private:
+ int do_layout(const QRect& rect, bool test) const {
+ const QMargins m = contentsMargins();
+ QRect eff = rect.adjusted(m.left(), m.top(), -m.right(), -m.bottom());
+ int x = eff.x(), y = eff.y(), line_h = 0;
+ for (auto* it : items_) {
+ const QSize sz = it->sizeHint();
+ int next_x = x + sz.width() + hspace_;
+ if (next_x - hspace_ > eff.right() && line_h > 0) { x = eff.x(); y += line_h + vspace_; next_x = x + sz.width() + hspace_; line_h = 0; }
+ if (!test) it->setGeometry(QRect(QPoint(x, y), sz));
+ x = next_x; line_h = qMax(line_h, sz.height());
+ }
+ return y + line_h - rect.y() + m.bottom();
+ }
+ QList<QLayoutItem*> items_; int hspace_, vspace_;
+};
+
+namespace {
+QStringList loaded_broker_ids() {
+ QStringList ids;
+ for (const auto& a : fincept::trading::AccountManager::instance().list_accounts())
+ if (!ids.contains(a.broker_id) && fincept::trading::InstrumentService::instance().is_loaded(a.broker_id))
+ ids << a.broker_id;
+ return ids;
+}
+} // namespace
+
+SymbolChipInput::SymbolChipInput(QWidget* parent) : QFrame(parent) {
+ setStyleSheet(QString("QFrame { background:%1; border:1px solid %2; }")
+ .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM()));
+ flow_ = new FlowLayout(this, 6, 4, 4);
+
+ edit_ = new QLineEdit(this);
+ edit_->setFrame(false);
+ edit_->setPlaceholderText(tr("type a ticker…"));
+ edit_->setMinimumWidth(120);
+ edit_->setStyleSheet(QString("QLineEdit { background:transparent; border:none; color:%1; font-family:%2; font-size:%3px; }")
+ .arg(fincept::ui::colors::TEXT_PRIMARY())
+ .arg(QString(fincept::ui::fonts::DATA_FAMILY))
+ .arg(fincept::ui::fonts::SMALL));
+ edit_->installEventFilter(this);
+ flow_->addWidget(edit_);
+
+ model_ = new QStringListModel(this);
+ completer_ = new QCompleter(model_, this);
+ completer_->setCaseSensitivity(Qt::CaseInsensitive);
+ completer_->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
+ completer_->setMaxVisibleItems(8);
+ edit_->setCompleter(completer_);
+
+ // The completer popup is a separate top-level QListView that no global
+ // stylesheet covers — without this it renders transparent and the controls
+ // behind it bleed through. Give it an opaque, themed look + click-to-add.
+ if (auto* popup = completer_->popup()) {
+ popup->setObjectName("symChipCompleterPopup");
+ popup->setTextElideMode(Qt::ElideNone); // show full label, never "…"
+ popup->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ popup->setStyleSheet(
+ QString("QListView { background:%1; color:%2; border:1px solid %3; outline:none;"
+ " font-family:%4; font-size:%5px; padding:3px; }"
+ "QListView::item { padding:5px 10px; border:none; border-radius:2px; }"
+ "QListView::item:hover { background:%6; }"
+ "QListView::item:selected { background:%6; color:%7; }"
+ "QScrollBar:vertical { background:%1; width:8px; margin:0; }"
+ "QScrollBar::handle:vertical { background:%3; border-radius:4px; min-height:20px; }"
+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")
+ .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(), fincept::ui::colors::AMBER()));
+ connect(popup, &QAbstractItemView::clicked, this, [this](const QModelIndex& idx) {
+ commit_label(idx.data().toString());
+ });
+ }
+
+ connect(edit_, &QLineEdit::textEdited, this, &SymbolChipInput::on_text_changed);
+ connect(edit_, &QLineEdit::returnPressed, this, [this]() { commit_text(edit_->text()); });
+ connect(completer_, QOverload<const QString&>::of(&QCompleter::activated), this,
+ [this](const QString& label) { commit_label(label); });
+}
+
+// Show only canonical alphabetic exchanges (NSE/BSE/NFO…); hide broker numeric
+// segment codes that would otherwise render as a meaningless "· 1".
+static QString pretty_exchange(const QString& ex) {
+ const QString e = ex.trimmed().toUpper();
+ if (e.endsWith(QStringLiteral("_INDEX"))) return e.left(e.size() - 6) + QStringLiteral(" IDX");
+ static const QStringList known = {"NSE", "BSE", "NFO", "BFO", "MCX", "CDS", "BCD", "NCDEX"};
+ return known.contains(e) ? e : QString();
+}
+
+void SymbolChipInput::on_text_changed(const QString& text) {
+ const QString q = text.trimmed();
+ if (q.isEmpty()) { model_->setStringList({}); sugg_map_.clear(); return; }
+ const auto results = fincept::trading::InstrumentService::instance().search_all(q, "", loaded_broker_ids(), 16);
+ QStringList labels;
+ sugg_map_.clear();
+ for (const auto& r : results) {
+ // Friendly label (clean F&O / underlying name) instead of the raw canonical
+ // symbol; remember the real symbol so a pick commits the right ticker.
+ const QString friendly = fincept::trading::norm::display_name(
+ r.name, r.instrument_type, r.expiry, r.strike, r.symbol);
+ const QString ex = pretty_exchange(r.exchange);
+ const QString label = ex.isEmpty() ? friendly : QStringLiteral("%1 · %2").arg(friendly, ex);
+ if (sugg_map_.contains(label)) continue; // collapse identical labels across brokers
+ sugg_map_.insert(label, r.symbol);
+ labels << label;
+ }
+ model_->setStringList(labels);
+
+ // Widen the popup to fit the longest label so nothing is truncated (the
+ // popup otherwise inherits the narrow line-edit width).
+ if (auto* popup = completer_->popup()) {
+ const QFontMetrics fm(edit_->font());
+ int w = 0;
+ for (const auto& l : labels) w = qMax(w, fm.horizontalAdvance(l));
+ popup->setMinimumWidth(qBound(220, w + 56, 560));
+ }
+}
+
+bool SymbolChipInput::eventFilter(QObject* obj, QEvent* ev) {
+ if (obj == edit_ && ev->type() == QEvent::KeyPress) {
+ auto* ke = static_cast<QKeyEvent*>(ev);
+ if (ke->key() == Qt::Key_Tab) {
+ // accept the highlighted/first suggestion if the popup is up, else raw text
+ if (completer_->popup() && completer_->popup()->isVisible()) {
+ const auto idx = completer_->popup()->currentIndex();
+ const QString label = idx.isValid() ? idx.data().toString() : completer_->currentCompletion();
+ if (!label.trimmed().isEmpty()) { commit_label(label); return true; }
+ }
+ if (!edit_->text().trimmed().isEmpty()) { commit_text(edit_->text()); return true; }
+ } else if (ke->key() == Qt::Key_Backspace && edit_->text().isEmpty() && !symbols_.isEmpty()) {
+ remove_chip(symbols_.last()); return true; // backspace on empty edit removes last chip
+ } else if (ke->key() == Qt::Key_Comma) {
+ commit_text(edit_->text()); return true;
+ }
+ }
+ return QFrame::eventFilter(obj, ev);
+}
+
+void SymbolChipInput::commit_text(const QString& raw) {
+ // If the whole text is a picked suggestion label (e.g. "HINDUNILVR · NSE"),
+ // resolve it to its single real symbol instead of fragmenting it.
+ const QString whole = raw.trimmed();
+ if (sugg_map_.contains(whole)) { commit_label(whole); return; }
+ // Split ONLY on comma/newline (never space) so a "SYMBOL · EXCH" label is
+ // never broken into pieces; a bare ticker has no spaces.
+ const auto parts = raw.split(QRegularExpression("[,\\n\\r]+"), Qt::SkipEmptyParts);
+ for (const auto& p : parts) {
+ const QString t = p.trimmed();
+ if (t.isEmpty()) continue;
+ add_chip(sugg_map_.contains(t) ? sugg_map_.value(t) : t.toUpper());
+ }
+ edit_->clear();
+ model_->setStringList({});
+ sugg_map_.clear();
+ if (completer_->popup()) completer_->popup()->hide();
+}
+
+void SymbolChipInput::commit_label(const QString& label) {
+ // Resolve the friendly suggestion label back to its real canonical symbol.
+ QString sym = sugg_map_.value(label);
+ if (sym.isEmpty()) sym = label.section(QStringLiteral(" · "), 0, 0).trimmed().toUpper();
+ add_chip(sym);
+ edit_->clear();
+ model_->setStringList({});
+ sugg_map_.clear();
+ if (completer_->popup()) completer_->popup()->hide();
+}
+
+void SymbolChipInput::add_chip(const QString& symbol) {
+ if (symbol.isEmpty() || symbols_.contains(symbol)) return;
+ symbols_ << symbol;
+
+ auto* chip = new QFrame(this);
+ chip->setStyleSheet(QString("QFrame { background:%1; border:1px solid %2; border-radius:3px; }")
+ .arg(fincept::ui::colors::BG_RAISED(), fincept::ui::colors::AMBER()));
+ auto* hl = new QHBoxLayout(chip);
+ hl->setContentsMargins(6, 2, 4, 2); hl->setSpacing(4);
+ auto* lbl = new QLabel(symbol, chip);
+ lbl->setObjectName("sym");
+ lbl->setStyleSheet(QString("color:%1; font-family:%2; font-size:%3px; font-weight:700; border:none; background:transparent;")
+ .arg(fincept::ui::colors::TEXT_PRIMARY())
+ .arg(QString(fincept::ui::fonts::DATA_FAMILY))
+ .arg(fincept::ui::fonts::SMALL));
+ auto* x = new QPushButton("✕", chip);
+ x->setCursor(Qt::PointingHandCursor);
+ x->setFixedSize(16, 16);
+ x->setStyleSheet(QString("QPushButton { color:%1; border:none; background:transparent; font-size:%2px; }"
+ "QPushButton:hover { color:%3; }")
+ .arg(fincept::ui::colors::TEXT_TERTIARY())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(fincept::ui::colors::NEGATIVE()));
+ connect(x, &QPushButton::clicked, this, [this, symbol]() { remove_chip(symbol); });
+ hl->addWidget(lbl); hl->addWidget(x);
+
+ // insert the chip BEFORE the trailing edit_
+ flow_->removeWidget(edit_);
+ flow_->addWidget(chip);
+ flow_->addWidget(edit_);
+ chips_ << chip;
+
+ emit symbols_changed();
+ fetch_price(symbol);
+ edit_->setFocus();
+}
+
+void SymbolChipInput::remove_chip(const QString& symbol) {
+ const int i = symbols_.indexOf(symbol);
+ if (i < 0) return;
+ symbols_.removeAt(i);
+ QWidget* chip = chips_.takeAt(i);
+ flow_->removeWidget(chip);
+ chip->deleteLater();
+ emit symbols_changed();
+}
+
+void SymbolChipInput::fetch_price(const QString& symbol) {
+ // Namespace is fincept::services (not fincept::services::markets).
+ // QuoteCallback = std::function<void(bool, QVector<QuoteData>)> — by value, not const-ref.
+ fincept::services::MarketDataService::instance().fetch_quotes(
+ {symbol}, [this, symbol](bool ok, QVector<fincept::services::QuoteData> quotes) {
+ if (!ok || quotes.isEmpty()) return;
+ const double px = quotes.first().price;
+ const int i = symbols_.indexOf(symbol);
+ if (i >= 0 && i < chips_.size())
+ if (auto* lbl = chips_[i]->findChild<QLabel*>("sym"))
+ lbl->setText(QString("%1 %2").arg(symbol, QString::number(px, 'f', 2)));
+ emit price_resolved(symbol, px);
+ });
+}
+
+QStringList SymbolChipInput::symbols() const { return symbols_; }
+
+void SymbolChipInput::set_symbols(const QStringList& syms) {
+ clear();
+ for (const auto& s : syms) add_chip(s.trimmed().toUpper());
+}
+
+void SymbolChipInput::clear() {
+ for (auto* c : chips_) { flow_->removeWidget(c); c->deleteLater(); }
+ chips_.clear();
+ symbols_.clear();
+ emit symbols_changed();
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/SymbolChipInput.h b/fincept-qt/src/ui/widgets/algo/SymbolChipInput.h
new file mode 100644
index 000000000..0b6221521
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/SymbolChipInput.h
@@ -0,0 +1,50 @@
+// src/ui/widgets/algo/SymbolChipInput.h
+#pragma once
+#include <QFrame>
+#include <QHash>
+#include <QStringList>
+#include <QVector>
+
+class QLineEdit;
+class QCompleter;
+class QStringListModel;
+
+namespace fincept::ui::algo {
+
+/// A bordered box that holds removable symbol "chips" plus an inline search field
+/// with instrument autocomplete. Tab/Enter/click commits a suggestion; the live
+/// price is fetched async and shown on the chip. Reusable across panels.
+class SymbolChipInput : public QFrame {
+ Q_OBJECT
+ public:
+ explicit SymbolChipInput(QWidget* parent = nullptr);
+
+ QStringList symbols() const; // current chips, in order
+ void set_symbols(const QStringList& syms); // replace all chips
+ void clear();
+
+ signals:
+ void symbols_changed();
+ void price_resolved(const QString& symbol, double price); // emitted when a chip's quote arrives
+
+ protected:
+ bool eventFilter(QObject* obj, QEvent* ev) override; // Tab-to-complete on the line edit
+
+ private:
+ void commit_text(const QString& raw); // add one-or-many raw (comma/space/newline split)
+ void commit_label(const QString& label); // resolve a picked suggestion label → real symbol
+ void add_chip(const QString& symbol);
+ void remove_chip(const QString& symbol);
+ void on_text_changed(const QString& text);
+ void fetch_price(const QString& symbol);
+
+ class FlowLayout* flow_ = nullptr;
+ QLineEdit* edit_ = nullptr;
+ QCompleter* completer_ = nullptr;
+ QStringListModel* model_ = nullptr;
+ QHash<QString, QString> sugg_map_; // suggestion label → real symbol
+ QStringList symbols_; // source of truth, upper-cased
+ QVector<QWidget*> chips_; // parallel to symbols_
+};
+
+} // namespace fincept::ui::algo