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/dashboard/widgets/MarginUsageWidget.h"
#include "datahub/DataHub.h"
#include "datahub/DataHubMetaTypes.h"
#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
#include "trading/BrokerTopic.h"
#include "trading/DataStreamManager.h"
#include "ui/theme/Theme.h"
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QGridLayout>
#include <QJsonObject>
#include <QLabel>
#include <QProgressBar>
#include <algorithm>
#include <cmath>
namespace fincept::screens::widgets {
namespace {
// Lakh / crore only reads right for rupee accounts. Applying it to a USD/EUR/GBP
// broker (Alpaca, IBKR, Tradier, Saxo) printed 150,000 as "1.50L".
QString fmt_money(double v, bool inr) {
QString s;
if (inr && std::abs(v) >= 1.0e7)
s = QString::number(v / 1.0e7, 'f', 2) + "Cr";
else if (inr && std::abs(v) >= 1.0e5)
s = QString::number(v / 1.0e5, 'f', 2) + "L";
else if (!inr && std::abs(v) >= 1.0e9)
s = QString::number(v / 1.0e9, 'f', 2) + "B";
else if (!inr && std::abs(v) >= 1.0e6)
s = QString::number(v / 1.0e6, 'f', 2) + "M";
else
s = QString::number(v, 'f', 2);
return s;
}
} // namespace
MarginUsageWidget::MarginUsageWidget(const QJsonObject& cfg, QWidget* parent) : BaseWidget(tr("MARGIN USAGE"), parent) {
auto* vl = content_layout();
vl->setContentsMargins(10, 8, 10, 8);
vl->setSpacing(6);
header_hint_ = new QLabel("—");
vl->addWidget(header_hint_);
auto* grid = new QGridLayout();
grid->setContentsMargins(0, 0, 0, 0);
grid->setHorizontalSpacing(12);
grid->setVerticalSpacing(4);
auto make_row = [this, grid](int row, const QString& label_text, QLabel*& value_out) {
auto* lbl = new QLabel(label_text);
lbl->setObjectName("marginUsageRowLabel");
row_labels_.append(lbl);
value_out = new QLabel("—");
value_out->setObjectName("marginUsageRowValue");
value_out->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
grid->addWidget(lbl, row, 0);
grid->addWidget(value_out, row, 1);
};
make_row(0, tr("Available"), available_val_);
make_row(1, tr("Used"), used_val_);
make_row(2, tr("Total"), total_val_);
make_row(3, tr("Collateral"), collateral_val_);
vl->addLayout(grid);
vl->addSpacing(4);
usage_pct_label_ = new QLabel(tr("Usage: —"));
usage_pct_label_->setObjectName("marginUsagePctLabel");
vl->addWidget(usage_pct_label_);
usage_bar_ = new QProgressBar(this);
usage_bar_->setRange(0, 100);
usage_bar_->setValue(0);
usage_bar_->setTextVisible(false);
usage_bar_->setFixedHeight(6);
vl->addWidget(usage_bar_);
vl->addStretch(1);
// Title-bar refresh = "retry". It used to be wired to nothing, so the 20 s
// "No data yet - click refresh to retry" prompt pointed at a dead button.
// The account stream polls on its own cadence, so the only thing a retry can
// do is (re)start that stream, show the loading state again, and ask the hub.
connect(this, &BaseWidget::refresh_requested, this, [this]() {
if (broker_id_.isEmpty() || account_id_.isEmpty())
return;
ensure_stream_running();
if (last_usage_pct_ < 0)
set_loading(true);
datahub::DataHub::instance().request(
trading::broker_topic(broker_id_, account_id_, QStringLiteral("balance")), /*force=*/true);
});
set_configurable(true);
apply_styles();
apply_config(cfg);
}
QJsonObject MarginUsageWidget::config() const {
QJsonObject o;
if (!account_id_.isEmpty())
o.insert("account_id", account_id_);
return o;
}
void MarginUsageWidget::refresh_header_hint() {
if (!header_hint_)
return;
if (account_id_.isEmpty()) {
header_hint_->setText(tr("No active account — click gear to configure"));
return;
}
const auto acct = trading::AccountManager::instance().get_account(account_id_);
header_hint_->setText(acct.display_name.isEmpty() ? account_id_ : acct.display_name);
}
void MarginUsageWidget::apply_config(const QJsonObject& cfg) {
account_id_ = cfg.value("account_id").toString();
if (account_id_.isEmpty())
account_id_ = resolve_account_id();
broker_id_.clear();
if (!account_id_.isEmpty())
broker_id_ = trading::AccountManager::instance().get_account(account_id_).broker_id;
refresh_header_hint();
if (isVisible() && !broker_id_.isEmpty() && !account_id_.isEmpty()) {
ensure_stream_running();
hub_resubscribe();
}
}
QString MarginUsageWidget::resolve_account_id() const {
const auto active = trading::AccountManager::instance().active_accounts();
return active.isEmpty() ? QString() : active.first().account_id;
}
void MarginUsageWidget::ensure_stream_running() {
auto& mgr = trading::DataStreamManager::instance();
if (!mgr.has_stream(account_id_))
mgr.start_stream(account_id_);
}
void MarginUsageWidget::hub_resubscribe() {
auto& hub = datahub::DataHub::instance();
hub.unsubscribe(this);
if (broker_id_.isEmpty() || account_id_.isEmpty())
return;
const QString topic = trading::broker_topic(broker_id_, account_id_, QStringLiteral("balance"));
if (last_usage_pct_ < 0)
set_loading(true); // nothing shown yet — see OpenPositionsWidget::hub_resubscribe
hub.subscribe(this, topic, [this](const QVariant& v) {
if (!v.canConvert<trading::BrokerFunds>())
return;
populate(v.value<trading::BrokerFunds>());
});
hub_active_ = true;
}
void MarginUsageWidget::hub_unsubscribe_all() {
datahub::DataHub::instance().unsubscribe(this);
hub_active_ = false;
}
void MarginUsageWidget::showEvent(QShowEvent* e) {
BaseWidget::showEvent(e);
if (!broker_id_.isEmpty() && !account_id_.isEmpty()) {
ensure_stream_running();
if (!hub_active_)
hub_resubscribe();
}
}
void MarginUsageWidget::hideEvent(QHideEvent* e) {
BaseWidget::hideEvent(e);
if (hub_active_)
hub_unsubscribe_all();
}
void MarginUsageWidget::populate(const trading::BrokerFunds& funds) {
// Unknown broker -> keep the historical (rupee) notation.
const auto* broker = trading::BrokerRegistry::instance().get(broker_id_);
const bool inr = !broker || broker->profile().currency == QLatin1String("INR");
available_val_->setText(fmt_money(funds.available_balance, inr));
used_val_->setText(fmt_money(funds.used_margin, inr));
total_val_->setText(fmt_money(funds.total_balance, inr));
collateral_val_->setText(fmt_money(funds.collateral, inr));
const double denom = funds.total_balance > 0 ? funds.total_balance : (funds.available_balance + funds.used_margin);
// The label shows the real ratio — an account past 100% (margin shortfall)
// used to read a reassuring "Usage: 100%". Only the bar is clamped.
int pct = 0;
if (denom > 0)
pct = std::max(0, static_cast<int>(std::lround((funds.used_margin / denom) * 100.0)));
usage_bar_->setValue(std::min(pct, 100));
last_usage_pct_ = pct;
usage_pct_label_->setText(tr("Usage: %1%").arg(pct));
usage_pct_label_->setToolTip(pct > 100 ? tr("Used margin exceeds the account balance") : QString());
QColor bar_color = ui::colors::POSITIVE();
if (pct >= 80)
bar_color = ui::colors::NEGATIVE();
else if (pct >= 50)
bar_color = ui::colors::WARNING();
set_css_cached(usage_bar_, QString("QProgressBar{background:%1;border:none;border-radius:2px;}"
"QProgressBar::chunk{background:%2;border-radius:2px;}")
.arg(ui::colors::BG_RAISED(), bar_color.name()));
set_loading(false);
}
QDialog* MarginUsageWidget::make_config_dialog(QWidget* parent) {
auto* dlg = new QDialog(parent);
dlg->setWindowTitle(tr("Configure — Margin Usage"));
auto* form = new QFormLayout(dlg);
auto* combo = new QComboBox(dlg);
const auto accts = trading::AccountManager::instance().list_accounts();
for (const auto& a : accts) {
const QString label = a.display_name.isEmpty() ? (a.broker_id + " — " + a.account_id) : a.display_name;
combo->addItem(label, a.account_id);
if (a.account_id == account_id_)
combo->setCurrentIndex(combo->count() - 1);
}
form->addRow(tr("Broker account"), combo);
auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dlg);
form->addRow(buttons);
connect(buttons, &QDialogButtonBox::accepted, dlg, [this, dlg, combo]() {
const QString picked = combo->currentData().toString();
if (!picked.isEmpty() && picked != account_id_) {
QJsonObject cfg;
cfg.insert("account_id", picked);
apply_config(cfg);
emit config_changed(cfg);
}
dlg->accept();
});
connect(buttons, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
return dlg;
}
void MarginUsageWidget::on_theme_changed() {
apply_styles();
}
void MarginUsageWidget::apply_styles() {
header_hint_->setStyleSheet(
QString("color:%1;font-size:9px;background:transparent;padding:2px 0;").arg(ui::colors::TEXT_TERTIARY()));
const QString row_label_css =
QString("color:%1;font-size:10px;background:transparent;").arg(ui::colors::TEXT_TERTIARY());
const QString row_value_css =
QString("color:%1;font-size:12px;font-weight:600;background:transparent;").arg(ui::colors::TEXT_PRIMARY());
for (QLabel* l : {available_val_, used_val_, total_val_, collateral_val_}) {
if (l)
l->setStyleSheet(row_value_css);
}
if (auto* parent = available_val_ ? available_val_->parentWidget() : nullptr) {
parent->setStyleSheet(
QString("QLabel#marginUsageRowLabel{%1} QLabel#marginUsageRowValue{%2}").arg(row_label_css, row_value_css));
}
if (usage_pct_label_)
usage_pct_label_->setStyleSheet(
QString("color:%1;font-size:10px;font-weight:600;background:transparent;padding-top:4px;")
.arg(ui::colors::TEXT_SECONDARY()));
if (usage_bar_)
set_css_cached(usage_bar_, QString("QProgressBar{background:%1;border:none;border-radius:2px;}"
"QProgressBar::chunk{background:%2;border-radius:2px;}")
.arg(ui::colors::BG_RAISED(), ui::colors::POSITIVE()));
}
void MarginUsageWidget::retranslateUi() {
BaseWidget::retranslateUi();
set_title(tr("MARGIN USAGE"));
// Actually re-translate the kept labels. The previous implementation
// called hub_resubscribe(), which tears down and rebuilds every hub
// subscription and does not touch a single string.
const QStringList captions = {tr("Available"), tr("Used"), tr("Total"), tr("Collateral")};
for (int i = 0; i < row_labels_.size() && i < captions.size(); ++i)
row_labels_[i]->setText(captions[i]);
if (usage_pct_label_)
usage_pct_label_->setText(last_usage_pct_ >= 0 ? tr("Usage: %1%").arg(last_usage_pct_)
: tr("Usage: —"));
refresh_header_hint();
}
} // namespace fincept::screens::widgets