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
perf: add InstrumentService::load_from_db_async() for background instrument loading
tilakpatel223d20ac268408
diff --git a/fincept-qt/src/storage/sqlite/Database.h b/fincept-qt/src/storage/sqlite/Database.hindex ece35da6f..2fd81e152 100644--- a/fincept-qt/src/storage/sqlite/Database.h+++ b/fincept-qt/src/storage/sqlite/Database.h@@ -28,6 +28,9 @@ class Database {QSqlDatabase& raw_db() { return db_; }+ /// Returns the file path of the open database (empty if not open).+ QString path() const { return db_.databaseName(); }+private:Database() = default;Result<void> apply_pragmas();diff --git a/fincept-qt/src/trading/instruments/InstrumentRepository.cpp b/fincept-qt/src/trading/instruments/InstrumentRepository.cppindex a61f7bc3f..7ec280ac1 100644--- a/fincept-qt/src/trading/instruments/InstrumentRepository.cpp+++ b/fincept-qt/src/trading/instruments/InstrumentRepository.cpp@@ -31,6 +31,10 @@ Instrument InstrumentRepository::map_row(QSqlQuery& q) {return i;}+Instrument InstrumentRepository::map_row_static(QSqlQuery& q) {+ return map_row(q);+}+// ── Write ─────────────────────────────────────────────────────────────────────fincept::Result<void> InstrumentRepository::replace_all(const QString& broker_id,diff --git a/fincept-qt/src/trading/instruments/InstrumentRepository.h b/fincept-qt/src/trading/instruments/InstrumentRepository.hindex 02c3700b3..8db1daac0 100644--- a/fincept-qt/src/trading/instruments/InstrumentRepository.h+++ b/fincept-qt/src/trading/instruments/InstrumentRepository.h@@ -43,6 +43,9 @@ class InstrumentRepository : public fincept::BaseRepository<Instrument> {/// Count rows for a broker (quick freshness check).int count(const QString& broker_id) const;+ /// Map a positioned QSqlQuery row to an Instrument. Public for use by async loaders.+ static Instrument map_row_static(QSqlQuery& q);+private:InstrumentRepository() = default;static Instrument map_row(QSqlQuery& q);diff --git a/fincept-qt/src/trading/instruments/InstrumentService.cpp b/fincept-qt/src/trading/instruments/InstrumentService.cppindex abdab925e..79e0a997e 100644--- a/fincept-qt/src/trading/instruments/InstrumentService.cpp+++ b/fincept-qt/src/trading/instruments/InstrumentService.cpp@@ -1,6 +1,7 @@#include "trading/instruments/InstrumentService.h"#include "core/logging/Logger.h"+#include "storage/sqlite/Database.h"#include "trading/brokers/BrokerHttp.h"#include "trading/instruments/InstrumentRepository.h"#include "trading/instruments/ZerodhaInstrumentParser.h"@@ -17,8 +18,12 @@#include <QNetworkRequest>#include <QPointer>#include <QRegularExpression>+#include <QSqlDatabase>+#include <QSqlError>+#include <QSqlQuery>#include <QTimer>#include <QUrl>+#include <QUuid>#include <QtConcurrent/QtConcurrent>namespace fincept::trading {@@ -250,6 +255,84 @@ void InstrumentService::load_from_db(const QString& broker_id) {LOG_INFO("InstrumentService", QString("Loaded %1 instruments from DB for %2").arg(all.size()).arg(broker_id));}+void InstrumentService::load_from_db_async(const QString& broker_id,+ std::function<void(int)> callback) {+ // Fast path: if already loaded, fire callback immediately on UI thread.+ if (is_loaded(broker_id)) {+ int n = cached_count(broker_id);+ LOG_INFO("InstrumentService",+ QString("load_from_db_async: %1 already loaded (%2 instruments)").arg(broker_id).arg(n));+ if (callback)+ callback(n);+ return;+ }++ LOG_INFO("InstrumentService", QString("load_from_db_async: starting background load for %1").arg(broker_id));++ QPointer<InstrumentService> self = this;+ QString db_path = fincept::Database::instance().path(); // read path on UI thread before going async++ QtConcurrent::run([self, broker_id, db_path, callback]() {+ // Each worker thread needs its own named QSqlDatabase connection.+ const QString conn_name =+ "inst_async_" + broker_id + "_" + QUuid::createUuid().toString(QUuid::WithoutBraces);+ QVector<Instrument> all;++ {+ QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", conn_name);+ db.setDatabaseName(db_path);+ if (!db.open()) {+ LOG_ERROR("InstrumentService",+ QString("load_from_db_async: failed to open DB for %1: %2")+ .arg(broker_id, db.lastError().text()));+ } else {+ // Single query for all exchanges — faster than 9 per-exchange queries.+ QSqlQuery q(db);+ q.prepare("SELECT instrument_token, exchange_token, symbol, brsymbol, name, "+ "exchange, brexchange, expiry, strike, lot_size, instrument_type, "+ "tick_size, broker_id "+ "FROM instruments WHERE broker_id = ?");+ q.addBindValue(broker_id);+ if (q.exec()) {+ while (q.next())+ all.append(InstrumentRepository::map_row_static(q));+ } else {+ LOG_ERROR("InstrumentService",+ QString("load_from_db_async: query failed for %1: %2")+ .arg(broker_id, q.lastError().text()));+ }+ db.close();+ }+ }+ QSqlDatabase::removeDatabase(conn_name);++ if (!self)+ return;++ const int count = all.size();+ QVector<Instrument> instruments = std::move(all);++ QMetaObject::invokeMethod(+ self,+ [self, broker_id, instruments = std::move(instruments), count, callback]() mutable {+ if (!self)+ return;+ if (!instruments.isEmpty()) {+ self->build_cache(broker_id, instruments);+ LOG_INFO("InstrumentService",+ QString("load_from_db_async: loaded %1 instruments for %2").arg(count).arg(broker_id));+ } else {+ LOG_WARN("InstrumentService",+ QString("load_from_db_async: no instruments found in DB for %1 — run refresh")+ .arg(broker_id));+ }+ if (callback)+ callback(count);+ },+ Qt::QueuedConnection);+ });+}+// ── Lookups ───────────────────────────────────────────────────────────────────std::optional<qint64> InstrumentService::instrument_token(const QString& symbol, const QString& exchange,diff --git a/fincept-qt/src/trading/instruments/InstrumentService.h b/fincept-qt/src/trading/instruments/InstrumentService.hindex 0391cba99..18eb24d09 100644--- a/fincept-qt/src/trading/instruments/InstrumentService.h+++ b/fincept-qt/src/trading/instruments/InstrumentService.h@@ -9,6 +9,7 @@#include <QString>#include <QVector>+#include <functional>#include <optional>namespace fincept::trading {@@ -46,6 +47,12 @@ class InstrumentService : public QObject {/// Call this on startup after DB opens.void load_from_db(const QString& broker_id);+ /// Load instruments from DB on a worker thread. Non-blocking.+ /// On completion, invokes callback(count) on the UI thread.+ /// If broker already loaded, callback fires immediately with cached count.+ void load_from_db_async(const QString& broker_id,+ std::function<void(int)> callback = nullptr);+// ── Lookups (synchronous, in-memory) ─────────────────────────────────────/// symbol + exchange → numeric instrument_token (for get_history)