FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
// src/screens/portfolio/PortfolioScreen_Handlers.cpp
//
// Service-event slots (on_portfolios_loaded / on_summary_loaded / on_metrics_computed
// / on_snapshots_loaded / on_portfolio_created/deleted / on_asset_changed),
// user-action slots (create / delete / detail_view / refresh interval /
// request_refresh / symbol_selected / buy / sell / order_panel close / animate /
// reposition), and load_demo_portfolio.
//
// Part of the partial-class split of PortfolioScreen.cpp.
#include "core/session/ScreenStateManager.h"
#include "core/symbol/SymbolContext.h"
#include "core/symbol/SymbolRef.h"
#include "screens/portfolio/PortfolioBlotter.h"
#include "screens/portfolio/PortfolioCommandBar.h"
#include "screens/portfolio/PortfolioDetailWrapper.h"
#include "screens/portfolio/PortfolioDialogs.h"
#include "screens/portfolio/PortfolioFFNView.h"
#include "screens/portfolio/PortfolioHeatmap.h"
#include "screens/portfolio/PortfolioInsightsPanel.h"
#include "screens/portfolio/PortfolioOrderPanel.h"
#include "screens/portfolio/PortfolioPanelHeader.h"
#include "screens/portfolio/PortfolioPerfChart.h"
#include "screens/portfolio/PortfolioScreen.h"
#include "screens/portfolio/PortfolioSectorPanel.h"
#include "screens/portfolio/PortfolioStatsRibbon.h"
#include "screens/portfolio/PortfolioStatusBar.h"
#include "screens/portfolio/PortfolioTxnPanel.h"
#include "services/file_manager/FileManagerService.h"
#include "services/portfolio/PortfolioService.h"
#include "storage/repositories/SettingsRepository.h"
#include "ui/theme/Theme.h"
#include <QDate>
#include <QFileDialog>
#include <QFrame>
#include <QGraphicsOpacityEffect>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QResizeEvent>
#include <QShowEvent>
#include <QSplitter>
#include <QVBoxLayout>
#include <algorithm>
#include <memory>
namespace fincept::screens {
void PortfolioScreen::on_portfolios_loaded(QVector<portfolio::Portfolio> portfolios) {
portfolios_ = portfolios;
command_bar_->set_portfolios(portfolios);
if (portfolios.isEmpty()) {
command_bar_->set_has_portfolios(false);
selected_id_.clear();
summary_loaded_ = false;
} else {
command_bar_->set_has_portfolios(true);
const auto selected_it =
std::find_if(portfolios.begin(), portfolios.end(),
[this](const portfolio::Portfolio& p) { return p.id == selected_id_; });
if (selected_id_.isEmpty() || selected_it == portfolios.end()) {
// Nothing selected - or the remembered selection (restore_state) names
// a portfolio that no longer exists, which would otherwise park the
// screen on a permanent "could not load" caption.
on_portfolio_selected(portfolios.first().id);
} else {
// restore_state() runs before this list exists, so on_portfolio_selected()
// could not look the portfolio up then: the selector still read
// "SELECT PORTFOLIO" and the status bar had no name. Sync them now.
command_bar_->set_selected_portfolio(*selected_it);
status_bar_->set_portfolio_name(selected_it->name);
}
}
update_content_state();
}
void PortfolioScreen::on_portfolio_selected(const QString& id) {
if (id == selected_id_ && summary_loaded_)
return;
selected_id_ = id;
ScreenStateManager::instance().notify_changed(this);
summary_loaded_ = false;
// Drop any error caption left over from a previous failed load.
if (loading_label_) {
loading_label_->setText(tr("Loading portfolio data…"));
loading_label_->setStyleSheet(
QString("color:%1; font-size:11px; font-weight:600; letter-spacing:0.8px;").arg(ui::colors::AMBER()));
}
active_detail_ = std::nullopt;
command_bar_->set_detail_view(std::nullopt);
status_bar_->set_analytics_note({}, {}, false); // belonged to the previous portfolio
if (txn_panel_)
txn_panel_->clear();
if (blotter_)
blotter_->set_sector_filter({});
// Find portfolio and update UI
for (const auto& p : portfolios_) {
if (p.id == id) {
command_bar_->set_selected_portfolio(p);
status_bar_->set_portfolio_name(p.name);
break;
}
}
update_content_state();
services::PortfolioService::instance().load_summary(id);
}
void PortfolioScreen::on_summary_loaded(portfolio::PortfolioSummary summary) {
if (summary.portfolio.id != selected_id_)
return; // Stale response
current_summary_ = summary;
summary_loaded_ = true;
command_bar_->set_refreshing(false);
stats_ribbon_->set_summary(summary);
status_bar_->set_summary(summary);
status_bar_->set_feed_state(true);
update_main_view_data();
update_content_state();
// Keep an open detail view / FFN view live. They were only handed the summary
// when first opened, so prices, P&L and weights froze until the user left and
// re-entered the tab (and F5 appeared to do nothing there).
if (active_detail_.has_value() && detail_wrapper_)
detail_wrapper_->update_data(summary, summary.portfolio.currency);
if (show_ffn_ && ffn_view_)
ffn_view_->set_data(summary, summary.portfolio.currency);
// Auto-select highest weighted holding if none selected
if (selected_symbol_.isEmpty() && !summary.holdings.isEmpty()) {
double max_w = -1;
QString top;
for (const auto& h : summary.holdings) {
if (h.weight > max_w) {
max_w = h.weight;
top = h.symbol;
}
}
on_symbol_selected(top);
}
auto& svc = services::PortfolioService::instance();
// Correlation, benchmark history, risk-free rate and ex-ante risk in ONE
// Python call, cached per (portfolio, day, holdings). A cache hit lands
// synchronously and recomputes the metrics through on_market_analytics().
if (!summary.holdings.isEmpty())
svc.fetch_market_analytics(summary);
// Metrics from what is known right now (realised TWR + last analytics).
svc.compute_metrics(summary);
// Load performance history for the chart
svc.load_snapshots(summary.portfolio.id, kSnapshotHistoryDays);
// Load recent transactions for the history panel
if (txn_panel_)
svc.load_transactions(summary.portfolio.id, PortfolioTxnPanel::kRecentRows);
}
void PortfolioScreen::on_market_analytics(bool ok, const QString& error) {
auto& svc = services::PortfolioService::instance();
const auto a = svc.last_market_analytics(selected_id_);
if (!ok && a.portfolio_id.isEmpty()) {
status_bar_->set_analytics_note(tr("RISK DATA UNAVAILABLE"),
tr("Price history for the risk figures could not be downloaded:\n%1\n"
"Volatility, beta and VaR fall back to the portfolio's own history. "
"Press ↻ (F5) to retry.")
.arg(error),
true);
return;
}
if (a.portfolio_id.isEmpty())
return;
if (sector_panel_)
sector_panel_->set_correlation(a.correlation);
if (detail_wrapper_)
detail_wrapper_->update_analytics(a);
if (perf_chart_)
perf_chart_->set_benchmark_history(a.benchmark, a.benchmark_dates, a.benchmark_closes);
if (ffn_view_)
ffn_view_->set_benchmark(a.benchmark, a.benchmark_closes, svc.risk_free_rate());
QString tip = tr("Risk figures use daily closes up to %1 (%2 observations, %3% of the book by weight).\n"
"Benchmark: %4. Risk-free rate: %5% — %6.")
.arg(a.as_of)
.arg(a.observations)
.arg(QString::number(a.coverage * 100.0, 'f', 0))
.arg(a.benchmark)
.arg(QString::number(svc.risk_free_rate() * 100.0, 'f', 2))
.arg(svc.risk_free_source());
if (!a.missing.isEmpty())
tip += tr("\nNo price history (excluded): %1").arg(a.missing.join(QStringLiteral(", ")));
if (!ok)
tip += tr("\nLatest refresh failed — showing the previous result: %1").arg(error);
status_bar_->set_analytics_note(tr("RISK DATA %1").arg(a.as_of), tip, !ok || !a.missing.isEmpty());
if (summary_loaded_)
svc.compute_metrics(current_summary_);
}
void PortfolioScreen::on_summary_error(QString portfolio_id, QString error) {
if (portfolio_id != selected_id_)
return;
// Always clear the spinner — it used to spin forever after a failed
// refresh because only the success path called set_refreshing(false).
command_bar_->set_refreshing(false);
if (summary_loaded_) {
// We already have data on screen. Keep showing it (P11: never blank a
// populated view) and flag the feed as stale instead.
status_bar_->set_feed_state(
false, error.isEmpty() ? tr("The last refresh failed — values shown may be out of date.")
: tr("The last refresh failed — values shown may be out of date.\n%1").arg(error));
return;
}
// Nothing rendered yet. update_content_state() parks on the loading
// skeleton whenever a portfolio is selected but no summary has arrived, so
// a first-load failure used to shimmer "Loading portfolio data…" forever
// with no way to tell that it had already given up. Turn the skeleton
// caption into an error + retry hint instead.
summary_loaded_ = false;
status_bar_->set_feed_state(false, error);
if (loading_label_) {
loading_label_->setText(error.isEmpty()
? tr("Could not load this portfolio. Press ↻ (F5) to retry.")
: tr("Could not load this portfolio: %1\nPress ↻ (F5) to retry.").arg(error));
loading_label_->setStyleSheet(
QString("color:%1; font-size:11px; font-weight:600; letter-spacing:0.8px;").arg(ui::colors::NEGATIVE()));
}
update_content_state();
}
void PortfolioScreen::on_metrics_computed(portfolio::ComputedMetrics metrics) {
current_metrics_ = metrics;
stats_ribbon_->set_metrics(metrics);
if (perf_chart_)
perf_chart_->set_twr_series(metrics.twr_series);
if (heatmap_)
heatmap_->set_metrics(metrics);
if (detail_wrapper_)
detail_wrapper_->update_metrics(metrics);
}
void PortfolioScreen::on_snapshots_loaded(QString portfolio_id, QVector<portfolio::PortfolioSnapshot> snapshots) {
if (portfolio_id != selected_id_)
return;
if (perf_chart_)
perf_chart_->set_snapshots(snapshots);
if (detail_wrapper_)
detail_wrapper_->update_snapshots(snapshots);
}
void PortfolioScreen::on_portfolio_created(portfolio::Portfolio portfolio) {
// portfolios_loaded fires asynchronously after creation, so the new portfolio
// may not be in portfolios_ yet when on_portfolio_selected looks it up.
// Append it immediately so the selector label and status bar show the correct
// name without waiting for the reload round-trip.
bool already_present = false;
for (const auto& p : portfolios_) {
if (p.id == portfolio.id) {
already_present = true;
break;
}
}
if (!already_present)
portfolios_.append(portfolio);
on_portfolio_selected(portfolio.id);
}
void PortfolioScreen::on_portfolio_deleted(QString id) {
if (id == selected_id_) {
selected_id_.clear();
summary_loaded_ = false;
update_content_state();
}
}
void PortfolioScreen::on_asset_changed(QString portfolio_id) {
if (portfolio_id != selected_id_)
return;
// A burst of add_asset()/sell_asset() calls (the demo portfolio adds twelve in
// a row, an import adds one per holding) emits this once per asset. Each
// refresh is a quote fetch plus correlation/benchmark/metrics work, and the
// earlier ones are immediately superseded - queue one refresh for the burst.
if (asset_refresh_queued_)
return;
asset_refresh_queued_ = true;
QMetaObject::invokeMethod(
this,
[this]() {
asset_refresh_queued_ = false;
if (!selected_id_.isEmpty())
services::PortfolioService::instance().refresh_summary(selected_id_);
},
Qt::QueuedConnection);
}
void PortfolioScreen::on_create_requested() {
CreatePortfolioDialog dlg(this);
if (dlg.exec() == QDialog::Accepted) {
services::PortfolioService::instance().create_portfolio(dlg.name(), dlg.owner(), dlg.currency());
}
}
void PortfolioScreen::on_delete_requested(const QString& id) {
QString name;
for (const auto& p : portfolios_) {
if (p.id == id) {
name = p.name;
break;
}
}
ConfirmDeleteDialog dlg(name, this);
if (dlg.exec() == QDialog::Accepted) {
services::PortfolioService::instance().delete_portfolio(id);
}
}
void PortfolioScreen::on_detail_view_selected(portfolio::DetailView view) {
if (active_detail_.has_value() && *active_detail_ == view) {
// Toggle off — go back to main view
active_detail_ = std::nullopt;
} else {
active_detail_ = view;
// Show the detail view with current data
detail_wrapper_->show_view(view, current_summary_, current_summary_.portfolio.currency);
}
command_bar_->set_detail_view(active_detail_);
update_content_state();
}
void PortfolioScreen::on_refresh_interval_changed(int ms) {
refresh_interval_ms_ = ms;
refresh_timer_->setInterval(ms);
SettingsRepository::instance().set("portfolio.refresh_interval_ms", QString::number(ms), "portfolio");
}
void PortfolioScreen::request_refresh() {
if (!selected_id_.isEmpty()) {
command_bar_->set_refreshing(true);
services::PortfolioService::instance().refresh_summary(selected_id_);
}
}
// ── Phase 3: Main view construction ──────────────────────────────────────────
void PortfolioScreen::on_symbol_selected(const QString& symbol) {
selected_symbol_ = symbol;
if (heatmap_)
heatmap_->set_selected_symbol(symbol);
if (blotter_)
blotter_->set_selected_symbol(symbol);
if (order_panel_)
order_panel_->set_holding(find_holding(symbol));
// Publish to the linked group so other panels (Equity Research, Watchlist
// …) follow the selection. Only when actually linked.
if (link_group_ != SymbolGroup::None && !symbol.isEmpty()) {
SymbolContext::instance().set_group_symbol(link_group_, SymbolRef::equity(symbol), this);
}
}
void PortfolioScreen::on_buy_requested() {
order_panel_visible_ = true;
order_panel_->set_side("BUY");
animate_order_panel_in();
}
void PortfolioScreen::on_sell_requested() {
order_panel_visible_ = true;
order_panel_->set_side("SELL");
animate_order_panel_in();
}
void PortfolioScreen::on_order_panel_close() {
order_panel_visible_ = false;
order_panel_->setVisible(false);
}
// ── Order panel overlay helpers ──────────────────────────────────────────────
void PortfolioScreen::reposition_order_panel() {
if (!order_panel_ || !order_panel_visible_)
return;
const int panel_w = order_panel_->width();
// Anchor below command bar + stats ribbon; stop above status bar.
const int top = command_bar_->height() + (stats_ribbon_->isVisible() ? stats_ribbon_->height() : 0);
const int bottom = status_bar_->isVisible() ? status_bar_->height() : 0;
const int h = height() - top - bottom;
order_panel_->setGeometry(width() - panel_w, top, panel_w, h);
order_panel_->raise();
}
void PortfolioScreen::animate_order_panel_in() {
if (!order_panel_)
return;
const int panel_w = order_panel_->width();
const int top = command_bar_->height() + (stats_ribbon_->isVisible() ? stats_ribbon_->height() : 0);
const int bottom = status_bar_->isVisible() ? status_bar_->height() : 0;
const int h = height() - top - bottom;
if (!order_panel_->isVisible()) {
// Start fully off-screen to the right, then slide into place.
order_panel_->setGeometry(width(), top, panel_w, h);
order_panel_->setVisible(true);
}
order_panel_->raise();
order_panel_anim_->stop();
order_panel_anim_->setStartValue(order_panel_->geometry());
order_panel_anim_->setEndValue(QRect(width() - panel_w, top, panel_w, h));
order_panel_anim_->start();
}
void PortfolioScreen::load_demo_portfolio() {
auto& svc = services::PortfolioService::instance();
// Connect BEFORE create_portfolio() — create_portfolio() emits portfolio_created
// synchronously, so the lambda must be connected first or it will never fire.
// shared_ptr: the handle is also needed after the call (below), and the raw
// new/delete pair leaked whenever the create failed.
auto conn = std::make_shared<QMetaObject::Connection>();
*conn = connect(&svc, &services::PortfolioService::portfolio_created, this, [this, conn](portfolio::Portfolio p) {
disconnect(*conn);
auto& svc = services::PortfolioService::instance();
// Demo holdings: diversified mix of major stocks
struct DemoHolding {
const char* symbol;
double qty;
double price;
};
static const DemoHolding demo[] = {
{"AAPL", 15, 178.50}, {"MSFT", 12, 375.20}, {"GOOGL", 8, 141.80}, {"NVDA", 10, 480.00},
{"AMZN", 6, 178.25}, {"TSLA", 5, 245.00}, {"JPM", 20, 195.50}, {"JNJ", 15, 155.75},
{"XOM", 25, 105.30}, {"V", 10, 280.00}, {"UNH", 4, 525.60}, {"PG", 12, 158.90},
};
// Dated a year back (like the downloadable template) so the history
// replay gives the charts and realised metrics a year to work with —
// stamped "today", the demo never had any performance history.
const QString buy_date = QDate::currentDate().addYears(-1).toString(Qt::ISODate);
for (const auto& h : demo) {
svc.add_asset(p.id, h.symbol, h.qty, h.price, buy_date);
}
// portfolios_ may not yet contain the new portfolio since load_portfolios()
// is async. Add it directly so on_portfolio_selected() can find it.
bool already_present = std::any_of(portfolios_.begin(), portfolios_.end(),
[&p](const portfolio::Portfolio& x) { return x.id == p.id; });
if (!already_present) {
portfolios_.append(p);
}
on_portfolio_selected(p.id);
});
// Create the demo portfolio (emits portfolio_created synchronously)
svc.create_portfolio(tr("Demo Portfolio"), tr("Fincept User"), "USD", tr("Sample portfolio for demonstration"));
// If creation failed nothing was emitted and the one-shot is still armed -
// it would then fire for the NEXT portfolio the user creates and stuff twelve
// demo holdings into it. Disarm it.
if (*conn)
disconnect(*conn);
}
} // namespace fincept::screens