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
#include "screens/markets/MarketsScreen.h"
#include "core/symbol/SymbolContext.h"
#include "core/symbol/SymbolGroupRegistry.h"
#include "screens/markets/MarketPanelEditor.h"
#include "screens/markets/MarketPanelStore.h"
#include "services/markets/MarketDataService.h"
#include "storage/repositories/SettingsRepository.h"
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
#include <QAbstractItemModel>
#include <QBrush>
#include <QComboBox>
#include <QDateTime>
#include <QEvent>
#include <QFrame>
#include <QHBoxLayout>
#include <QHideEvent>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QShortcut>
#include <QShowEvent>
#include <QSplitter>
#include <QTableWidget>
#include <QTimeZone>
#include <QTimer>
#include <QVBoxLayout>
#include <QtConcurrent/QtConcurrent>
namespace fincept::screens {
// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------
static QString lbl_ss(const QString& color, bool bold = false, int px = -1) {
const int sz = (px > 0) ? px : ui::fonts::font_px(-2);
return QString("color:%1;background:transparent;font-size:%2px;font-family:'%3';%4")
.arg(color)
.arg(sz)
.arg(ui::fonts::DATA_FAMILY())
.arg(bold ? "font-weight:bold;" : "");
}
/// Raw ticker of a MarketPanel row: column 0 shows the display name and carries the ticker in
/// Qt::UserRole (the contract MarketPanel's own context menu uses); falls back to the cell text.
static QString markets_ticker_at(QTableWidget* table, int row) {
auto* item = (table && row >= 0) ? table->item(row, 0) : nullptr;
if (!item)
return {};
const QString t = item->data(Qt::UserRole).toString().trimmed();
return t.isEmpty() ? item->text().trimmed() : t;
}
/// SymbolRef asset class for a yfinance-style Markets ticker, so receivers can tell an index or a
/// futures/FX/crypto quote from an equity.
static QString markets_link_asset_class(const QString& ticker) {
if (ticker.startsWith(QLatin1Char('^')))
return QStringLiteral("index");
if (ticker.endsWith(QLatin1String("=X")))
return QStringLiteral("fx");
if (ticker.endsWith(QLatin1String("=F")))
return QStringLiteral("future");
if (ticker.endsWith(QLatin1String("-USD")) || ticker.endsWith(QLatin1String("-USDT")))
return QStringLiteral("crypto");
return QStringLiteral("equity");
}
// ---------------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------------
MarketsScreen::MarketsScreen(QWidget* parent) : QWidget(parent) {
// Restore the AUTO toggle and refresh interval. Both were session-only: every launch
// went back to ON / 10M no matter what the user had chosen (they are saved by the header
// controls below). Must run before build_header_bar(), which reads them.
{
auto& settings = SettingsRepository::instance();
const auto auto_res = settings.get("markets_auto_update");
if (auto_res.is_ok() && !auto_res.value().isEmpty())
auto_update_ = auto_res.value() != QLatin1String("0");
const auto interval_res = settings.get("markets_update_interval_ms");
if (interval_res.is_ok()) {
bool ok = false;
const int ms = interval_res.value().toInt(&ok);
if (ok && ms >= 60000 && ms <= 86400000)
update_interval_ms_ = ms;
}
}
auto* root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
header_bar_ = build_header_bar();
root->addWidget(header_bar_);
configs_ = MarketPanelStore::instance().load();
build_splitter_layout();
root->addWidget(h_splitter_, 1);
restore_splitter_state();
auto_refresh_timer_ = new QTimer(this);
auto_refresh_timer_->setInterval(update_interval_ms_);
connect(auto_refresh_timer_, &QTimer::timeout, this, &MarketsScreen::refresh_all);
refresh_timeout_ = new QTimer(this);
refresh_timeout_->setSingleShot(true);
refresh_timeout_->setInterval(kRefreshTimeoutMs);
connect(refresh_timeout_, &QTimer::timeout, this, [this]() {
if (!refresh_in_progress_)
return;
// Tear the cycle's connections down. Without this, a late
// refresh_finished() from the timed-out cycle still decremented
// pending_refreshes_ — which by then belonged to the NEXT cycle — and
// flipped the badge to READY before that cycle's data had arrived.
abort_refresh_cycle();
status_state_ = StatusState::Timeout;
if (status_label_) {
status_label_->setText(tr("● TIMEOUT"));
status_label_->setStyleSheet(lbl_ss(ui::colors::NEGATIVE(), true));
}
});
// F5 / F9 — the header buttons are literally labelled "[F5] REFRESH" and
// "[F9] AUTO", but no shortcut was ever registered for either.
auto* f5 = new QShortcut(QKeySequence(Qt::Key_F5), this);
f5->setContext(Qt::WindowShortcut);
connect(f5, &QShortcut::activated, this, &MarketsScreen::refresh_all);
auto* f9 = new QShortcut(QKeySequence(Qt::Key_F9), this);
f9->setContext(Qt::WindowShortcut);
connect(f9, &QShortcut::activated, this, [this]() {
if (auto_btn_)
auto_btn_->click();
});
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { refresh_theme(); });
refresh_theme();
}
// ---------------------------------------------------------------------------
// Splitter layout
// ---------------------------------------------------------------------------
void MarketsScreen::build_splitter_layout() {
h_splitter_ = new QSplitter(Qt::Horizontal, this);
h_splitter_->setHandleWidth(3);
h_splitter_->setChildrenCollapsible(false);
col_splitters_.clear();
panels_.clear();
for (int col = 0; col < kNumColumns; ++col) {
auto* vs = new QSplitter(Qt::Vertical);
vs->setHandleWidth(3);
vs->setChildrenCollapsible(false);
col_splitters_.append(vs);
h_splitter_->addWidget(vs);
}
// Place panels into their designated columns
for (const auto& cfg : configs_) {
int col = qBound(0, cfg.column_index, kNumColumns - 1);
auto* p = new MarketPanel(cfg, col_splitters_[col]);
panels_.append(p);
col_splitters_[col]->addWidget(p);
wire_panel(p);
}
// Ensure empty columns have a placeholder so they don't collapse
for (int col = 0; col < kNumColumns; ++col) {
bool has_panel = false;
for (int j = 0; j < col_splitters_[col]->count(); ++j) {
if (qobject_cast<MarketPanel*>(col_splitters_[col]->widget(j))) {
has_panel = true;
break;
}
}
if (!has_panel) {
auto* placeholder = new QWidget;
placeholder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// Empty state: with every panel deleted the screen was three blank
// columns and no hint about how to get anything back.
if (panels_.isEmpty() && col == 0) {
auto* pl = new QVBoxLayout(placeholder);
pl->setAlignment(Qt::AlignCenter);
auto* hint = new QLabel(tr("No market panels.\nUse [+] PANEL to add one, or RESET for the defaults."));
hint->setAlignment(Qt::AlignCenter);
hint->setWordWrap(true);
hint->setStyleSheet(lbl_ss(ui::colors::TEXT_DIM(), false, 12));
pl->addWidget(hint);
}
col_splitters_[col]->addWidget(placeholder);
}
}
// Distribute equal height to every panel in each column so no single row
// grabs disproportionate space. (Restored saved state may override this.)
for (auto* vs : col_splitters_) {
const int n = vs->count();
if (n > 1) {
const int equal = 1000; // arbitrary equal weight
QList<int> sizes;
sizes.reserve(n);
for (int i = 0; i < n; ++i)
sizes.append(equal);
vs->setSizes(sizes);
}
}
refresh_theme();
}
void MarketsScreen::wire_panel(MarketPanel* p) {
connect(p, &MarketPanel::edit_requested, this, &MarketsScreen::open_editor);
connect(p, &MarketPanel::delete_requested, this, &MarketsScreen::on_panel_delete);
connect(p, &MarketPanel::config_changed, this, &MarketsScreen::on_panel_config_changed);
// Symbol-group link through the panel's table (see MarketsScreen.h).
if (auto* table = p->findChild<QTableWidget*>()) {
connect(table, &QTableWidget::cellClicked, this, [this, table](int row, int) {
const QString ticker = markets_ticker_at(table, row);
if (ticker.isEmpty())
return;
clicked_symbol_ = ticker;
linked_symbol_ = ticker; // mark the selection like a received symbol
apply_link_highlight();
publish_row_symbol(ticker);
});
// The panel rebuilds its row items on every quote delivery, which drops the highlight:
// re-apply it once the burst of updates has been processed.
connect(table->model(), &QAbstractItemModel::dataChanged, this, [this]() {
if (!applying_link_highlight_ && !linked_symbol_.isEmpty())
schedule_link_highlight();
});
}
}
// ---------------------------------------------------------------------------
// Symbol-group link (IGroupLinked)
// ---------------------------------------------------------------------------
void MarketsScreen::set_group(fincept::SymbolGroup g) {
link_group_ = g;
apply_link_highlight(); // highlight colour follows the group
}
void MarketsScreen::on_group_symbol_changed(const fincept::SymbolRef& ref) {
if (!ref.is_valid())
return;
linked_symbol_ = ref.symbol.trimmed();
apply_link_highlight(); // panels without the ticker simply show no highlight
}
fincept::SymbolRef MarketsScreen::current_symbol() const {
const QString sym = !clicked_symbol_.isEmpty() ? clicked_symbol_ : linked_symbol_;
// Same rule as publish_row_symbol(): only an equity may seed a link group.
if (sym.isEmpty() || markets_link_asset_class(sym) != QLatin1String("equity"))
return {};
fincept::SymbolRef ref;
ref.symbol = sym;
ref.asset_class = QStringLiteral("equity");
return ref;
}
void MarketsScreen::publish_row_symbol(const QString& ticker) {
if (link_group_ == fincept::SymbolGroup::None)
return;
// Only equities drive the group: the linked screens (Equity Trading's order ticket, News'
// headline search, the Watchlist) take stock tickers, and an index / future / FX / crypto quote
// (^GSPC, GC=F, EURUSD=X, BTC-USD) would switch them to something they cannot use. Those rows
// still reach Equity Research through the panel's own double-click / "Open in" menu.
const QString asset_class = markets_link_asset_class(ticker);
if (asset_class != QLatin1String("equity"))
return;
fincept::SymbolRef ref;
ref.symbol = ticker;
ref.asset_class = asset_class;
fincept::SymbolContext::instance().set_group_symbol(link_group_, ref, this);
}
void MarketsScreen::schedule_link_highlight() {
if (link_highlight_pending_)
return;
link_highlight_pending_ = true;
QTimer::singleShot(0, this, [this]() { apply_link_highlight(); });
}
void MarketsScreen::apply_link_highlight() {
link_highlight_pending_ = false;
QColor hl = link_group_ != fincept::SymbolGroup::None ? fincept::SymbolGroupRegistry::instance().color(link_group_)
: QColor(ui::colors::AMBER());
hl.setAlpha(70);
const QBrush brush(hl);
applying_link_highlight_ = true; // our own setData() calls must not re-schedule
for (MarketPanel* p : std::as_const(panels_)) {
auto* table = p ? p->findChild<QTableWidget*>() : nullptr;
if (!table)
continue;
for (int r = 0; r < table->rowCount(); ++r) {
const bool match = !linked_symbol_.isEmpty() &&
markets_ticker_at(table, r).compare(linked_symbol_, Qt::CaseInsensitive) == 0;
for (int c = 0; c < table->columnCount(); ++c) {
auto* item = table->item(r, c);
if (!item)
continue;
if (match)
item->setBackground(brush);
else if (item->data(Qt::BackgroundRole).isValid())
item->setData(Qt::BackgroundRole, QVariant());
}
}
}
applying_link_highlight_ = false;
}
void MarketsScreen::rebuild_splitter_layout() {
if (h_splitter_) {
h_splitter_->setParent(nullptr);
h_splitter_->deleteLater();
h_splitter_ = nullptr;
}
panels_.clear();
col_splitters_.clear();
build_splitter_layout();
auto* root = qobject_cast<QVBoxLayout*>(layout());
root->insertWidget(1, h_splitter_, 1);
restore_splitter_state();
}
int MarketsScreen::column_with_fewest_panels() const {
int best = 0, count = INT_MAX;
for (int i = 0; i < kNumColumns; ++i) {
int c = 0;
for (int j = 0; j < col_splitters_[i]->count(); ++j) {
if (qobject_cast<MarketPanel*>(col_splitters_[i]->widget(j)))
++c;
}
if (c < count) {
count = c;
best = i;
}
}
return best;
}
void MarketsScreen::save_splitter_state() {
if (!h_splitter_)
return;
// Save only horizontal splitter state (column widths).
// Vertical row heights are always equal-distributed on build.
const QString state = QString::fromLatin1(h_splitter_->saveState().toBase64());
// hideEvent() runs on every tab switch — keep the sqlite write off the UI
// thread so leaving the Markets tab never stalls the frame (P1).
(void)QtConcurrent::run([state]() { SettingsRepository::instance().set("markets_splitter_state", state); });
}
void MarketsScreen::restore_splitter_state() {
if (!h_splitter_)
return;
auto res = SettingsRepository::instance().get("markets_splitter_state");
if (!res.is_ok() || res.value().isEmpty())
return;
const QString saved = res.value();
int sep = saved.indexOf('|');
// Restore only the horizontal splitter (column widths).
// Vertical (row heights) are set to equal in build_splitter_layout()
// and must not be overridden by stale saved state.
if (sep < 0) {
h_splitter_->restoreState(QByteArray::fromBase64(saved.toLatin1()));
return;
}
h_splitter_->restoreState(QByteArray::fromBase64(saved.left(sep).toLatin1()));
}
// ---------------------------------------------------------------------------
// Panel management
// ---------------------------------------------------------------------------
void MarketsScreen::open_editor(const QString& panel_id) {
MarketPanelConfig cfg;
int target_col = column_with_fewest_panels();
if (!panel_id.isEmpty()) {
for (const auto& c : configs_) {
if (c.id == panel_id) {
cfg = c;
target_col = c.column_index;
break;
}
}
}
auto* dlg = new MarketPanelEditor(cfg, this);
if (dlg->exec() != QDialog::Accepted) {
dlg->deleteLater();
return;
}
MarketPanelConfig updated = dlg->result_config();
dlg->deleteLater();
updated.column_index = target_col;
if (panel_id.isEmpty()) {
configs_.append(updated);
} else {
for (auto& c : configs_) {
if (c.id == panel_id) {
c = updated;
break;
}
}
}
MarketPanelStore::instance().save(configs_);
rebuild_splitter_layout();
refresh_all();
}
void MarketsScreen::open_editor_for_new_panel(int col_index) {
MarketPanelConfig cfg;
auto* dlg = new MarketPanelEditor(cfg, this);
if (dlg->exec() != QDialog::Accepted) {
dlg->deleteLater();
return;
}
MarketPanelConfig updated = dlg->result_config();
dlg->deleteLater();
updated.column_index = col_index;
configs_.append(updated);
MarketPanelStore::instance().save(configs_);
rebuild_splitter_layout();
refresh_all();
}
void MarketsScreen::on_panel_delete(const QString& panel_id) {
QMessageBox mb(this);
mb.setWindowTitle(tr("Remove Panel"));
mb.setText(tr("Remove this panel?"));
mb.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
mb.setDefaultButton(QMessageBox::Cancel);
mb.setStyleSheet(QString("background:%1;color:%2;").arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
if (mb.exec() != QMessageBox::Yes)
return;
configs_.erase(
std::remove_if(configs_.begin(), configs_.end(), [&](const MarketPanelConfig& c) { return c.id == panel_id; }),
configs_.end());
MarketPanelStore::instance().save(configs_);
rebuild_splitter_layout();
}
void MarketsScreen::on_panel_config_changed(const MarketPanelConfig& cfg) {
for (auto& c : configs_) {
if (c.id == cfg.id) {
c = cfg;
break;
}
}
MarketPanelStore::instance().save(configs_);
}
// ---------------------------------------------------------------------------
// Header bar (single 36px strip)
// ---------------------------------------------------------------------------
QWidget* MarketsScreen::build_header_bar() {
auto* w = new QWidget(this);
w->setFixedHeight(36);
auto* h = new QHBoxLayout(w);
h->setContentsMargins(12, 0, 12, 0);
h->setSpacing(0);
auto add_sep = [&]() {
auto* s = new QLabel("|");
s->setStyleSheet(lbl_ss(ui::colors::BORDER_DIM()));
s->setContentsMargins(10, 0, 10, 0);
h->addWidget(s);
};
// Branding
brand_label_ = new QLabel(tr("FINCEPT MARKETS"));
brand_label_->setStyleSheet(lbl_ss(ui::colors::TEXT_PRIMARY(), true));
h->addWidget(brand_label_);
add_sep();
// Session status
session_label_ = new QLabel;
session_label_->setStyleSheet(lbl_ss(ui::colors::TEXT_DIM(), true, 11));
h->addWidget(session_label_);
update_session_status();
session_timer_ = new QTimer(this);
session_timer_->setInterval(60000);
connect(session_timer_, &QTimer::timeout, this, &MarketsScreen::update_session_status);
add_sep();
// Clocks
ny_label_ = new QLabel;
lon_label_ = new QLabel;
tok_label_ = new QLabel;
for (auto* lbl : {ny_label_, lon_label_, tok_label_})
lbl->setStyleSheet(lbl_ss(ui::colors::TEXT_SECONDARY(), false, 11));
h->addWidget(ny_label_);
h->addWidget(new QLabel(" "));
h->addWidget(lon_label_);
h->addWidget(new QLabel(" "));
h->addWidget(tok_label_);
update_clocks();
clock_timer_ = new QTimer(this);
clock_timer_->setInterval(1000);
connect(clock_timer_, &QTimer::timeout, this, &MarketsScreen::update_clocks);
add_sep();
// Controls — all uniform dim style
auto make_ctrl_btn = [&](const QString& label) -> QPushButton* {
auto* b = new QPushButton(label);
b->setFixedHeight(24);
b->setCursor(Qt::PointingHandCursor);
b->setFlat(true);
b->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;"
"font-size:%2px;font-family:'%3';padding:0 6px;}"
"QPushButton:hover{color:%4;}")
.arg(ui::colors::TEXT_DIM())
.arg(ui::fonts::font_px(-3))
.arg(ui::fonts::DATA_FAMILY())
.arg(ui::colors::TEXT_PRIMARY()));
return b;
};
refresh_btn_ = make_ctrl_btn(tr("[F5] REFRESH"));
connect(refresh_btn_, &QPushButton::clicked, this, &MarketsScreen::refresh_all);
h->addWidget(refresh_btn_);
// AUTO toggle — amber when ON
auto_btn_ = make_ctrl_btn(auto_update_ ? tr("[F9] AUTO: ON") : tr("[F9] AUTO: OFF"));
update_auto_style();
connect(auto_btn_, &QPushButton::clicked, this, [this]() {
auto_update_ = !auto_update_;
update_auto_style();
SettingsRepository::instance().set("markets_auto_update", auto_update_ ? "1" : "0", "market_data");
if (!isVisible())
return;
if (auto_update_)
auto_refresh_timer_->start();
else
auto_refresh_timer_->stop();
});
h->addWidget(auto_btn_);
// Interval combo
auto* iv = new QComboBox;
iv->setFixedHeight(24);
iv->setFixedWidth(56);
iv->addItem(tr("5M"), 300000);
iv->addItem(tr("10M"), 600000);
iv->addItem(tr("15M"), 900000);
iv->addItem(tr("30M"), 1800000);
iv->addItem(tr("1H"), 3600000);
iv->addItem(tr("4H"), 14400000);
iv->addItem(tr("1D"), 86400000);
// Select the saved interval (10M when nothing valid was saved). Done before the
// currentIndexChanged connection below, so it doesn't write the setting back.
{
const int saved_idx = iv->findData(update_interval_ms_);
iv->setCurrentIndex(saved_idx >= 0 ? saved_idx : 1);
update_interval_ms_ = iv->itemData(iv->currentIndex()).toInt();
}
interval_combo_ = iv;
iv->setStyleSheet(QString("QComboBox{background:transparent;color:%1;border:none;"
"font-size:%6px;font-family:'%7';padding:0 4px;}"
"QComboBox::drop-down{border:none;width:12px;}"
"QComboBox QAbstractItemView{background:%2;color:%3;border:1px solid %4;"
"selection-background-color:%5;font-size:%6px;font-family:'%7';}")
.arg(ui::colors::TEXT_DIM(), ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),
ui::colors::BORDER_MED(), ui::colors::BG_HOVER())
.arg(ui::fonts::font_px(-3))
.arg(ui::fonts::DATA_FAMILY()));
connect(iv, &QComboBox::currentIndexChanged, this, [this, iv](int i) {
update_interval_ms_ = iv->itemData(i).toInt();
auto_refresh_timer_->setInterval(update_interval_ms_);
SettingsRepository::instance().set("markets_update_interval_ms", QString::number(update_interval_ms_),
"market_data");
});
h->addWidget(iv);
// [+] PANEL — column picker menu
add_panel_btn_ = make_ctrl_btn(tr("[+] PANEL"));
auto* add_btn = add_panel_btn_;
connect(add_btn, &QPushButton::clicked, this, [this, add_btn]() {
auto* menu = new QMenu(this);
menu->setStyleSheet(QString("QMenu{background:%1;border:1px solid %2;color:%3;"
"font-size:%5px;font-family:'%6';}"
"QMenu::item{padding:4px 16px;}"
"QMenu::item:selected{background:%4;}")
.arg(ui::colors::BG_RAISED(), ui::colors::BORDER_MED(), ui::colors::TEXT_PRIMARY(),
ui::colors::BG_HOVER())
.arg(ui::fonts::font_px(-3))
.arg(ui::fonts::DATA_FAMILY()));
for (int i = 0; i < kNumColumns; ++i) {
auto* act = menu->addAction(tr("ADD TO COL %1").arg(i + 1));
connect(act, &QAction::triggered, this, [this, i]() { open_editor_for_new_panel(i); });
}
menu->exec(add_btn->mapToGlobal(QPoint(0, add_btn->height())));
menu->deleteLater();
});
h->addWidget(add_btn);
// RESET
reset_btn_ = make_ctrl_btn(tr("RESET"));
connect(reset_btn_, &QPushButton::clicked, this, [this]() {
QMessageBox mb(this);
mb.setWindowTitle(tr("Reset Panels"));
mb.setText(tr("Reset all panels to defaults?"));
mb.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
mb.setStyleSheet(QString("background:%1;color:%2;").arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
if (mb.exec() != QMessageBox::Yes)
return;
MarketPanelStore::instance().reset_to_defaults();
configs_ = MarketPanelStore::instance().load();
rebuild_splitter_layout();
refresh_all();
});
h->addWidget(reset_btn_);
h->addStretch();
last_upd_label_ = new QLabel(tr("LAST UPDATE --:--:--"));
last_upd_label_->setStyleSheet(lbl_ss(ui::colors::TEXT_DIM(), false, 11));
h->addWidget(last_upd_label_);
h->addWidget(new QLabel(" "));
status_label_ = new QLabel(tr("● READY"));
status_label_->setStyleSheet(lbl_ss(ui::colors::POSITIVE(), true));
h->addWidget(status_label_);
// ── Accessibility ──
// The terminal shipped with no accessible names anywhere; screen readers
// announced every one of these as an unnamed button.
refresh_btn_->setAccessibleName(tr("Refresh all market panels"));
refresh_btn_->setToolTip(tr("Refresh all market panels (F5)"));
auto_btn_->setAccessibleName(tr("Toggle auto-refresh"));
auto_btn_->setToolTip(tr("Toggle auto-refresh (F9)"));
interval_combo_->setAccessibleName(tr("Auto-refresh interval"));
interval_combo_->setToolTip(tr("Auto-refresh interval"));
add_panel_btn_->setAccessibleName(tr("Add a market panel"));
reset_btn_->setAccessibleName(tr("Reset all panels to defaults"));
status_label_->setAccessibleName(tr("Refresh status"));
last_upd_label_->setAccessibleName(tr("Last update time"));
session_label_->setAccessibleName(tr("US market session"));
QWidget* chain[] = {refresh_btn_, auto_btn_, interval_combo_, add_panel_btn_, reset_btn_};
for (int i = 1; i < 5; ++i)
setTabOrder(chain[i - 1], chain[i]);
return w;
}
// Re-applies the AUTO button label + amber/dim styling from auto_update_.
// Pulled into a member so retranslateUi() can refresh the localized label.
void MarketsScreen::update_auto_style() {
if (!auto_btn_)
return;
auto_btn_->setText(auto_update_ ? tr("[F9] AUTO: ON") : tr("[F9] AUTO: OFF"));
auto_btn_->setStyleSheet(
QString("QPushButton{background:transparent;color:%1;border:none;"
"font-size:%3px;font-family:'%4';padding:0 6px;}"
"QPushButton:hover{color:%2;}")
.arg(auto_update_ ? ui::colors::AMBER() : ui::colors::TEXT_DIM(), ui::colors::TEXT_PRIMARY())
.arg(ui::fonts::font_px(-3))
.arg(ui::fonts::DATA_FAMILY()));
}
// ---------------------------------------------------------------------------
// Session status & clocks — DST-correct via QTimeZone
// ---------------------------------------------------------------------------
void MarketsScreen::update_session_status() {
QDateTime utc = QDateTime::currentDateTimeUtc();
QTimeZone ny_tz("America/New_York");
QDateTime et = utc.toTimeZone(ny_tz);
int day = et.date().dayOfWeek();
int hhmm = et.time().hour() * 100 + et.time().minute();
bool weekday = (day >= 1 && day <= 5);
QString label, color;
if (!weekday || hhmm < 400 || hhmm >= 2000) {
label = tr("NYSE: CLOSED");
color = ui::colors::TEXT_DIM();
} else if (hhmm < 930) {
label = tr("NYSE: PRE-MKT");
color = ui::colors::AMBER();
} else if (hhmm < 1600) {
label = tr("NYSE: OPEN");
color = ui::colors::POSITIVE();
} else {
label = tr("NYSE: AFTER-HRS");
color = ui::colors::AMBER();
}
if (session_label_) {
session_label_->setText(label);
session_label_->setStyleSheet(lbl_ss(color, true, 11));
}
}
void MarketsScreen::update_clocks() {
QDateTime utc = QDateTime::currentDateTimeUtc();
if (ny_label_)
ny_label_->setText(tr("NY %1").arg(utc.toTimeZone(QTimeZone("America/New_York")).toString("HH:mm:ss")));
if (lon_label_)
lon_label_->setText(tr("LON %1").arg(utc.toTimeZone(QTimeZone("Europe/London")).toString("HH:mm:ss")));
if (tok_label_)
tok_label_->setText(tr("TOK %1").arg(utc.toTimeZone(QTimeZone("Asia/Tokyo")).toString("HH:mm:ss")));
}
// ---------------------------------------------------------------------------
// Show / hide — timer lifecycle (P3)
// ---------------------------------------------------------------------------
void MarketsScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
// Horizontal (column widths): apply ONCE, now that geometry is valid —
// restore the user's saved widths if any, else fall back to equal columns.
// Doing an unconditional equalize on EVERY show wiped the saved/manually
// adjusted widths that restore_splitter_state() had applied.
if (!h_splitter_initialized_ && h_splitter_ && h_splitter_->count() > 1) {
h_splitter_initialized_ = true;
auto res = SettingsRepository::instance().get("markets_splitter_state");
if (res.is_ok() && !res.value().isEmpty()) {
restore_splitter_state();
} else {
QList<int> hsizes;
for (int i = 0; i < h_splitter_->count(); ++i)
hsizes.append(1000);
h_splitter_->setSizes(hsizes);
}
}
// Vertical: equal panel heights within each column (always, by design).
for (auto* vs : col_splitters_) {
if (vs->count() > 1) {
QList<int> vsizes;
for (int i = 0; i < vs->count(); ++i)
vsizes.append(1000);
vs->setSizes(vsizes);
}
}
if (auto_update_ && auto_refresh_timer_)
auto_refresh_timer_->start();
if (session_timer_)
session_timer_->start();
if (clock_timer_)
clock_timer_->start();
bool needs_refresh = !last_refresh_time_.isValid() ||
last_refresh_time_.secsTo(QDateTime::currentDateTime()) >= kMinRefreshIntervalSec;
if (needs_refresh)
refresh_all();
}
void MarketsScreen::hideEvent(QHideEvent* event) {
QWidget::hideEvent(event);
if (auto_refresh_timer_)
auto_refresh_timer_->stop();
if (session_timer_)
session_timer_->stop();
if (clock_timer_)
clock_timer_->stop();
save_splitter_state();
}
// ---------------------------------------------------------------------------
// Refresh
// ---------------------------------------------------------------------------
void MarketsScreen::abort_refresh_cycle() {
refresh_in_progress_ = false;
pending_refreshes_ = 0;
refresh_timeout_->stop();
if (refresh_counter_) {
// Dropping the context object retires this cycle. The
// `counter != refresh_counter_` guard in the slot makes any callback
// that lands before deleteLater() runs a no-op (P13: never `delete`
// a QObject from inside signal delivery).
refresh_counter_->deleteLater();
refresh_counter_ = nullptr;
}
}
void MarketsScreen::refresh_all() {
if (refresh_in_progress_)
return;
if (panels_.isEmpty())
return;
abort_refresh_cycle(); // clear any leftovers from a previous cycle
refresh_in_progress_ = true;
pending_refreshes_ = static_cast<int>(panels_.size());
status_state_ = StatusState::Loading;
if (status_label_) {
status_label_->setText(tr("● LOADING"));
status_label_->setStyleSheet(lbl_ss(ui::colors::AMBER(), true));
}
refresh_timeout_->start();
refresh_counter_ = new QObject(this);
QObject* counter = refresh_counter_;
// Wire every panel BEFORE kicking any of them: MarketPanel::refresh()
// emits refresh_finished() synchronously for a symbol-less panel, and
// with connect-after-refresh that signal was missed — the counter then
// never drained and the badge sat on LOADING until the 10 s timeout.
for (auto* p : panels_) {
connect(
p, &MarketPanel::refresh_finished, counter,
[this, counter]() {
if (counter != refresh_counter_)
return; // stale cycle
if (--pending_refreshes_ > 0)
return;
refresh_timeout_->stop();
refresh_in_progress_ = false;
last_refresh_time_ = QDateTime::currentDateTime();
refresh_counter_ = nullptr;
counter->deleteLater();
status_state_ = StatusState::Ready;
if (status_label_) {
status_label_->setText(tr("● READY"));
status_label_->setStyleSheet(lbl_ss(ui::colors::POSITIVE(), true));
}
if (last_upd_label_) {
last_upd_label_->setText(
tr("LAST UPDATE %1").arg(QDateTime::currentDateTime().toString("HH:mm:ss")));
last_upd_label_->setStyleSheet(lbl_ss(ui::colors::TEXT_SECONDARY(), false, 11));
}
},
Qt::SingleShotConnection);
}
for (auto* p : panels_)
p->refresh();
}
// ---------------------------------------------------------------------------
// Theme
// ---------------------------------------------------------------------------
void MarketsScreen::refresh_theme() {
setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
const QString handle_ss = QString("QSplitter::handle{background:%1;}").arg(ui::colors::BORDER_DIM());
if (header_bar_)
header_bar_->setStyleSheet(QString("background:%1;border-bottom:1px solid %2;")
.arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
if (h_splitter_)
h_splitter_->setStyleSheet(handle_ss);
for (auto* vs : col_splitters_)
vs->setStyleSheet(handle_ss);
}
// ---------------------------------------------------------------------------
// i18n — live language switch
// ---------------------------------------------------------------------------
void MarketsScreen::changeEvent(QEvent* event) {
if (event->type() == QEvent::LanguageChange)
retranslateUi();
QWidget::changeEvent(event);
}
void MarketsScreen::retranslateUi() {
if (brand_label_)
brand_label_->setText(tr("FINCEPT MARKETS"));
if (refresh_btn_)
refresh_btn_->setText(tr("[F5] REFRESH"));
update_auto_style(); // re-applies localized AUTO: ON/OFF label
if (add_panel_btn_)
add_panel_btn_->setText(tr("[+] PANEL"));
if (reset_btn_)
reset_btn_->setText(tr("RESET"));
// Interval combo — fixed UI labels, preserve current selection & item data.
if (interval_combo_) {
const int cur = interval_combo_->currentIndex();
const QStringList labels = {tr("5M"), tr("10M"), tr("15M"), tr("30M"), tr("1H"), tr("4H"), tr("1D")};
for (int i = 0; i < interval_combo_->count() && i < labels.size(); ++i)
interval_combo_->setItemText(i, labels[i]);
interval_combo_->setCurrentIndex(cur);
}
// Dynamic header labels — re-derive from current state so the new language
// takes effect immediately rather than on the next timer tick.
update_session_status();
update_clocks();
if (status_label_) {
switch (status_state_) {
case StatusState::Ready:
status_label_->setText(tr("● READY"));
break;
case StatusState::Loading:
status_label_->setText(tr("● LOADING"));
break;
case StatusState::Timeout:
status_label_->setText(tr("● TIMEOUT"));
break;
}
}
// "LAST UPDATE …" — only the never-refreshed placeholder is re-translated;
// once a real timestamp is shown it stays as data.
if (last_upd_label_ && !last_refresh_time_.isValid())
last_upd_label_->setText(tr("LAST UPDATE --:--:--"));
}
} // namespace fincept::screens