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.

mt5 broker fixed

tilakpatel2225d41a7be159
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 94072e161..7d5e84ae8 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1212,6 +1212,7 @@ set(TRADING_SOURCES
src/trading/brokers/tradier/TradierBroker.cpp
src/trading/brokers/saxo/SaxoBankBroker.cpp
src/trading/brokers/metaapi/MetaApiBroker.cpp
+ src/trading/brokers/tickerall/TickerAllBroker.cpp
# Instrument system (Phase 1)
src/trading/instruments/InstrumentNormalize.cpp
@@ -2606,6 +2607,7 @@ set_source_files_properties(
src/trading/brokers/tradier/TradierBroker.cpp
src/trading/brokers/saxo/SaxoBankBroker.cpp
src/trading/brokers/metaapi/MetaApiBroker.cpp
+ src/trading/brokers/tickerall/TickerAllBroker.cpp
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
)
diff --git a/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py b/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py
index 9308911f9..f6515fc44 100644
--- a/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py
+++ b/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py
@@ -21,6 +21,7 @@ sys.path.insert(0, str(STRATEGIES_DIR))
from fincept_engine import QCAlgorithm, Symbol, TradeBar, Slice
from fincept_engine.enums import Resolution, SecurityType
from _registry import STRATEGY_REGISTRY
+from _loader import resolve_strategy_path
class FinceptStrategyRunner:
@@ -43,16 +44,10 @@ class FinceptStrategyRunner:
if not info:
raise ValueError(f"Strategy {strategy_id} not found in registry")
- # Containment check. `Path / value` silently ESCAPES the root when
- # `value` is absolute ("C:/x", "/etc/x") or walks up ("../../x"), and
- # the code below exec()s whatever it reads. Resolve first, then assert
- # the result is still under strategies_dir.
- root = self.strategies_dir.resolve()
- strategy_path = (root / info['path']).resolve()
- if not strategy_path.is_relative_to(root):
- raise ValueError(
- f"Strategy path escapes the strategies directory: {info['path']}"
- )
+ # Containment check - the code below exec()s whatever it reads, so the
+ # resolved path must stay under strategies_dir. Shared with live_runner.py
+ # via _loader; raises StrategyPathError (a ValueError) if it escapes.
+ strategy_path = resolve_strategy_path(self.strategies_dir, info['path'])
if not strategy_path.exists():
raise FileNotFoundError(f"Strategy file not found: {strategy_path}")
diff --git a/fincept-qt/scripts/strategies/_loader.py b/fincept-qt/scripts/strategies/_loader.py
new file mode 100644
index 000000000..802d2a1d0
--- /dev/null
+++ b/fincept-qt/scripts/strategies/_loader.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+"""
+Fincept Terminal - Shared Strategy Loading Helpers
+
+Two places read a path out of the strategy registry and exec() the file it
+points at:
+
+ - Analytics/backtesting/base/fincept_strategy_runner.py (backtest)
+ - strategies/live_runner.py (paper/live deploy)
+
+They each implemented path resolution independently and drifted apart - one had
+a containment check and the other did not (issue #369). The check lives here now
+so both loaders share one contract and cannot diverge again.
+"""
+
+from pathlib import Path
+from typing import Union
+
+
+class StrategyPathError(ValueError):
+ """A registry path resolved outside the strategies directory.
+
+ Subclasses ValueError so callers with an existing `except ValueError`
+ handler keep catching it.
+ """
+
+
+def resolve_strategy_path(strategies_dir: Union[str, Path], path: Union[str, Path]) -> Path:
+ """Resolve a registry `path` against `strategies_dir`, asserting containment.
+
+ `Path / value` (and `os.path.join`) silently ESCAPE the root when `value` is
+ absolute ("C:/x", "/etc/x") or walks up ("../../x"), and both callers exec()
+ whatever they read. Resolve first, then assert the result is still under the
+ root. `.resolve()` follows symlinks, so a link pointing out of the tree is
+ rejected too.
+
+ Returns the resolved absolute path. Existence is deliberately NOT checked -
+ the two callers report a missing file in different ways.
+
+ Raises StrategyPathError if the path escapes the strategies directory.
+ """
+ root = Path(strategies_dir).resolve()
+ resolved = (root / Path(path)).resolve()
+ if not resolved.is_relative_to(root):
+ raise StrategyPathError(
+ f"Strategy path escapes the strategies directory: {path}"
+ )
+ return resolved
diff --git a/fincept-qt/scripts/strategies/live_runner.py b/fincept-qt/scripts/strategies/live_runner.py
index 74f39f126..4837b2674 100644
--- a/fincept-qt/scripts/strategies/live_runner.py
+++ b/fincept-qt/scripts/strategies/live_runner.py
@@ -24,6 +24,14 @@ import time
import signal
from datetime import datetime, timezone
+# _loader lives next to this file; guarantee it is importable whether we are run
+# as a script (sys.path[0] is already this dir) or imported from elsewhere.
+_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+if _SCRIPT_DIR not in sys.path:
+ sys.path.insert(0, _SCRIPT_DIR)
+
+from _loader import resolve_strategy_path, StrategyPathError
+
# ============================================================================
# SQLite Schema & DB Helpers
# ============================================================================
@@ -143,8 +151,17 @@ def cmd_deploy(deploy_id: str, strategy_id: str, params_json: str, db_path: str,
conn.close()
return
- full_path = os.path.join(strategies_dir, strategy_path)
- if not os.path.exists(full_path):
+ # Containment check - the exec() below runs whatever this path points at,
+ # and the registry value may be absolute or contain "..". Shared with
+ # fincept_strategy_runner.py via _loader so the two cannot diverge.
+ try:
+ full_path = resolve_strategy_path(strategies_dir, strategy_path)
+ except StrategyPathError as e:
+ _update_status(conn, deploy_id, "error", str(e))
+ conn.close()
+ return
+
+ if not full_path.exists():
_update_status(conn, deploy_id, "error", f"Strategy file not found: {strategy_path}")
conn.close()
return
@@ -154,7 +171,7 @@ def cmd_deploy(deploy_id: str, strategy_id: str, params_json: str, db_path: str,
source = f.read()
module_globals = {}
- exec(compile(source, full_path, "exec"), module_globals)
+ exec(compile(source, str(full_path), "exec"), module_globals)
# Find the QCAlgorithm subclass
algo_class = None
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
index 6e40a18d4..5ee62f060 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
@@ -141,6 +141,15 @@ static QVector<CredSubField> custom_cred_fields(const QString& broker_id) {
{"password", QObject::tr("PASSWORD"), true},
{"dob", QObject::tr("DATE OF BIRTH (DD/MM/YYYY)"), false},
{"totp", QObject::tr("TOTP (current 6-digit code, if enabled)"), true}};
+ // MT5 via the TickerAll hosted bridge. Not a delimiter-packing broker: it
+ // needs the MT5 SERVER name, which has no CredentialField of its own, so the
+ // plain profile form cannot render it. MT4 solved the same problem with a
+ // whole dedicated page (build_mt4_form); four labelled boxes do it here.
+ if (broker_id == QLatin1String("metatrader5"))
+ return {{"api_key", QObject::tr("TICKERALL API KEY"), true},
+ {"server", QObject::tr("MT5 SERVER (e.g. Exness-MT5Trial7)"), false},
+ {"login", QObject::tr("MT5 LOGIN"), false},
+ {"password", QObject::tr("MT5 PASSWORD"), true}};
return {};
}
@@ -173,6 +182,17 @@ static ExchangeArgs pack_custom_credentials(const QString& broker_id, const QMap
a.api_key = v.value("userid");
a.api_secret = v.value("password");
a.auth_code = v.value("dob") + S + v.value("totp");
+ } else if (broker_id == QLatin1String("metatrader5")) {
+ // TickerAllBroker::exchange_token() parses auth_code as JSON
+ // {"login","password","server"} — same contract as MetaApiBroker's MT4
+ // flow, so the MT5 password never touches api_key/api_secret.
+ a.api_key = v.value("api_key");
+ a.auth_code = QString::fromUtf8(QJsonDocument(QJsonObject{
+ {"login", v.value("login")},
+ {"password", v.value("password")},
+ {"server", v.value("server")},
+ })
+ .toJson(QJsonDocument::Compact));
}
return a;
}
@@ -682,6 +702,27 @@ void AccountManagementDialog::load_saved_credentials(const QString& account_id)
return;
}
+ // MT5 (TickerAll) uses the custom-sub-field form but, unlike the delimiter
+ // brokers below, its parts are stored unpacked and are NOT daily-expiring: the
+ // API key, server and login all round-trip cleanly. Repopulate them by key
+ // (not by index, so field order stays free to change) and leave only the
+ // password blank — it is never persisted, and once the session exists it is
+ // not needed again.
+ if (creds.broker_id == QStringLiteral("metatrader5") && !cred_form_keys_.isEmpty()) {
+ const auto extra = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();
+ const QMap<QString, QString> values = {
+ {QStringLiteral("api_key"), creds.api_key},
+ {QStringLiteral("server"), extra.value("server").toString()},
+ {QStringLiteral("login"), creds.user_id},
+ };
+ for (int i = 0; i < cred_form_keys_.size() && i < cred_fields_.size(); ++i) {
+ const auto it = values.constFind(cred_form_keys_[i]);
+ if (it != values.constEnd())
+ cred_fields_[i]->setText(*it);
+ }
+ return;
+ }
+
// Custom multi-sub-field forms (delimiter brokers) can't be cleanly unpacked
// back into individual boxes — and they're daily-expiring TOTP logins anyway —
// so leave them blank for re-entry rather than mis-populate from packed creds.
diff --git a/fincept-qt/src/services/options/FiiDiiService.h b/fincept-qt/src/services/options/FiiDiiService.h
index 0bde1dbfd..771d866c4 100644
--- a/fincept-qt/src/services/options/FiiDiiService.h
+++ b/fincept-qt/src/services/options/FiiDiiService.h
@@ -2,9 +2,8 @@
// FiiDiiService — DataHub Producer for `fno:fii_dii:daily`.
//
// On `refresh()` (called by the hub scheduler when a subscriber wants fresh
-// data), the service runs scripts/fii_dii_scraper.py via PythonRunner,
-// upserts the result into `fii_dii_daily`, then publishes the last
-// `kPublishWindow` days as `QVector<FiiDiiDay>` on the topic.
+// data), the service upserts the result into `fii_dii_daily`, then publishes
+// the last `kPublishWindow` days as `QVector<FiiDiiDay>` on the topic.
//
// Cadence
// ───────
diff --git a/fincept-qt/src/services/options/FiiDiiTypes.h b/fincept-qt/src/services/options/FiiDiiTypes.h
index 9c7134f8c..5ba6481a7 100644
--- a/fincept-qt/src/services/options/FiiDiiTypes.h
+++ b/fincept-qt/src/services/options/FiiDiiTypes.h
@@ -2,8 +2,7 @@
// FiiDiiTypes — daily institutional flows.
//
// One row per trading day. Source: NSE cash-market FII/DII end-of-day
-// publication (scripts/fii_dii_scraper.py). All values in Indian Rupees,
-// Crore units (1 Crore = 10⁷ ₹).
+// publication. All values in Indian Rupees, Crore units (1 Crore = 10⁷ ₹).
#include <QMetaType>
#include <QString>
diff --git a/fincept-qt/src/trading/BrokerRegistry.cpp b/fincept-qt/src/trading/BrokerRegistry.cpp
index 441383787..2494c4c05 100644
--- a/fincept-qt/src/trading/BrokerRegistry.cpp
+++ b/fincept-qt/src/trading/BrokerRegistry.cpp
@@ -18,6 +18,7 @@
#include "trading/brokers/iifl/IIFLBroker.h"
#include "trading/brokers/kotak/KotakBroker.h"
#include "trading/brokers/metaapi/MetaApiBroker.h"
+#include "trading/brokers/tickerall/TickerAllBroker.h"
#include "trading/brokers/motilal/MotilalBroker.h"
#include "trading/brokers/paytm/PaytmBroker.h"
#include "trading/brokers/samco/SamcoBroker.h"
@@ -141,8 +142,9 @@ void BrokerRegistry::register_all() {
// EU brokers
brokers_["saxobank"] = std::make_unique<SaxoBankBroker>();
- // MetaAPI-bridged
- brokers_["metatrader4"] = std::make_unique<MetaApiBroker>();
+ // Hosted MetaTrader bridges — no local terminal required
+ brokers_["metatrader4"] = std::make_unique<MetaApiBroker>(); // via metaapi.cloud
+ brokers_["metatrader5"] = std::make_unique<TickerAllBroker>(); // via tickerall.com
LOG_INFO("BrokerRegistry", QString("Registered %1 brokers").arg(brokers_.size()));
}
diff --git a/fincept-qt/src/trading/RateLimiter.cpp b/fincept-qt/src/trading/RateLimiter.cpp
index fb9e16272..24133c459 100644
--- a/fincept-qt/src/trading/RateLimiter.cpp
+++ b/fincept-qt/src/trading/RateLimiter.cpp
@@ -25,6 +25,10 @@ OrderRateLimiter::OrderRateLimiter() {
set_limit(BrokerId::Tradier, 10);
set_limit(BrokerId::SaxoBank, 10);
set_limit(BrokerId::MetaTrader4, 10);
+ // TickerAll publishes no REST rate limit (only a WebSocket RATE_LIMIT error
+ // code), so stay deliberately below the MT4 bridge until a documented figure
+ // exists. Raise it once tickerall.com states one.
+ set_limit(BrokerId::MetaTrader5, 5);
}
OrderRateLimiter::BrokerLimit& OrderRateLimiter::get_or_create(BrokerId broker) {
diff --git a/fincept-qt/src/trading/TradingTypes.h b/fincept-qt/src/trading/TradingTypes.h
index 220423dda..88535b37c 100644
--- a/fincept-qt/src/trading/TradingTypes.h
+++ b/fincept-qt/src/trading/TradingTypes.h
@@ -541,7 +541,8 @@ enum class BrokerId {
IBKR,
Tradier,
SaxoBank,
- MetaTrader4
+ MetaTrader4,
+ MetaTrader5
};
inline const char* broker_id_str(BrokerId id) {
@@ -590,6 +591,8 @@ inline const char* broker_id_str(BrokerId id) {
return "saxobank";
case BrokerId::MetaTrader4:
return "metatrader4";
+ case BrokerId::MetaTrader5:
+ return "metatrader5";
}
return "unknown";
}
@@ -639,6 +642,8 @@ inline std::optional<BrokerId> parse_broker_id(const QString& s) {
return BrokerId::SaxoBank;
if (s == "metatrader4")
return BrokerId::MetaTrader4;
+ if (s == "metatrader5")
+ return BrokerId::MetaTrader5;
return std::nullopt;
}
diff --git a/fincept-qt/src/trading/brokers/tickerall/TickerAllBroker.cpp b/fincept-qt/src/trading/brokers/tickerall/TickerAllBroker.cpp
new file mode 100644
index 000000000..18f02b3d8
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/tickerall/TickerAllBroker.cpp
@@ -0,0 +1,754 @@
+#include "trading/brokers/tickerall/TickerAllBroker.h"
+
+#include "trading/brokers/BrokerHttp.h"
+#include "trading/brokers/BrokerModifyFields.h"
+
+#include <QDate>
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QTimeZone>
+#include <QUrlQuery>
+
+#include <algorithm>
+#include <cmath>
+
+namespace fincept::trading {
+
+// Named inner namespace, not an anonymous one: with unity builds ON for every
+// release/CI preset (CLAUDE.md), ~20 .cpp files are concatenated into one TU and
+// their anonymous namespaces merge — two files defining a file-scope `now_ts`
+// would then be a hard redefinition error that only appears on CI.
+namespace tickerall_detail {
+
+inline int64_t now_ts() {
+ return QDateTime::currentSecsSinceEpoch();
+}
+
+// Parse a flexible date string (ISO / yyyy-MM-dd / yyyy-MM-dd HH:mm) into UTC.
+// Returns an invalid QDateTime when none of the forms match.
+inline QDateTime parse_dt(const QString& s) {
+ if (s.isEmpty())
+ return {};
+ QDateTime dt = QDateTime::fromString(s, Qt::ISODate);
+ if (!dt.isValid()) {
+ const QDate d = QDate::fromString(s, QStringLiteral("yyyy-MM-dd"));
+ if (d.isValid())
+ dt = QDateTime(d, QTime(0, 0), QTimeZone::utc());
+ }
+ if (!dt.isValid()) {
+ dt = QDateTime::fromString(s, QStringLiteral("yyyy-MM-dd HH:mm"));
+ if (dt.isValid())
+ dt.setTimeZone(QTimeZone::utc());
+ }
+ return dt.isValid() ? dt.toUTC() : QDateTime();
+}
+
+// Ticket identity is a string in PendingOrder but a number in PlaceOrderResult,
+// so read either shape rather than trusting one.
+inline QString ticket_str(const QJsonValue& v) {
+ if (v.isString())
+ return v.toString();
+ if (v.isDouble())
+ return QString::number(static_cast<qint64>(v.toDouble()));
+ return {};
+}
+
+} // namespace tickerall_detail
+
+using tickerall_detail::now_ts;
+using tickerall_detail::parse_dt;
+using tickerall_detail::ticket_str;
+
+// ── Auth headers ─────────────────────────────────────────────────────────────
+
+QMap<QString, QString> TickerAllBroker::auth_headers(const BrokerCredentials& creds) const {
+ return {
+ {"Authorization", QStringLiteral("Bearer %1").arg(creds.api_key)},
+ {"Content-Type", "application/json"},
+ {"Accept", "application/json"},
+ };
+}
+
+// ── Error helpers ────────────────────────────────────────────────────────────
+
+QString TickerAllBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
+ // The [TOKEN_EXPIRED] marker is the contract IBroker::validate_session
+ // classifies on (BrokerInterface.h). Without it the account reads "Connected"
+ // forever while every request 401s and the user is never prompted to reconnect.
+ if (resp.status_code == 401)
+ return QStringLiteral("[TOKEN_EXPIRED] TickerAll API key is invalid or expired. "
+ "Check your key at tickerall.com.");
+ if (resp.status_code == 403)
+ return QStringLiteral("TickerAll: plan limit reached or resource reserved. "
+ "Live accounts require a paid plan.");
+ if (resp.status_code == 404)
+ return QStringLiteral("TickerAll account or ticket not found. The MT5 session may have ended — reconnect.");
+ if (resp.status_code == 400 || resp.status_code == 422)
+ return QStringLiteral("TickerAll: invalid request. Check symbol, volume and price.");
+ if (resp.status_code == 429)
+ return QStringLiteral("TickerAll rate limit reached. Please wait and retry.");
+ if (resp.status_code == 503)
+ return QStringLiteral("TickerAll is momentarily unreachable. Safe to retry.");
+
+ // TickerAll error envelope: {"error":{"code":…,"message":…}} or a flat message.
+ if (!resp.json.isEmpty()) {
+ const QJsonObject err = resp.json.value("error").toObject();
+ const QString nested = err.value("message").toString();
+ if (!nested.isEmpty())
+ return nested;
+ const QString msg = resp.json.value("message").toString();
+ if (!msg.isEmpty())
+ return msg;
+ const QString flat = resp.json.value("error").toString();
+ if (!flat.isEmpty())
+ return flat;
+ }
+ if (!resp.error.isEmpty())
+ return resp.error;
+ return fallback;
+}
+
+// ── Mapping helpers ──────────────────────────────────────────────────────────
+
+// TickerAll's order type union is 'market' | 'limit' | 'stop'. It has no
+// stop-limit, so StopLossLimit degrades to a stop order triggered at the same
+// price — the closest behaviour the venue actually offers.
+QString TickerAllBroker::order_type_for(OrderType type) {
+ switch (type) {
+ case OrderType::Market:
+ return QStringLiteral("market");
+ case OrderType::Limit:
+ return QStringLiteral("limit");
+ case OrderType::StopLoss:
+ case OrderType::StopLossLimit:
+ return QStringLiteral("stop");
+ }
+ return QStringLiteral("market");
+}
+
+// Timeframe union: M1 | M5 | M15 | M30 | H1 | H4 | D1 | W1 | MN1.
+QString TickerAllBroker::map_timeframe(const QString& resolution) {
+ const QString r = resolution.trimmed();
+ if (r == "1" || r.compare("1m", Qt::CaseInsensitive) == 0 || r.compare("M1", Qt::CaseSensitive) == 0)
+ return QStringLiteral("M1");
+ if (r == "5" || r.compare("5m", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("M5");
+ if (r == "15" || r.compare("15m", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("M15");
+ if (r == "30" || r.compare("30m", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("M30");
+ if (r == "60" || r.compare("1h", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("H1");
+ // 2h/3h/4h/8h all fold to H4 — the coarsest intraday bar TickerAll serves.
+ if (r == "120" || r == "180" || r == "240" || r == "480" || r.compare("2h", Qt::CaseInsensitive) == 0 ||
+ r.compare("3h", Qt::CaseInsensitive) == 0 || r.compare("4h", Qt::CaseInsensitive) == 0 ||
+ r.compare("8h", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("H4");
+ if (r == "D" || r.compare("1d", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("D1");
+ if (r == "W" || r.compare("1w", Qt::CaseInsensitive) == 0)
+ return QStringLiteral("W1");
+ if (r == "M" || r.compare("1mn", Qt::CaseInsensitive) == 0 || r.compare("1M", Qt::CaseSensitive) == 0)
+ return QStringLiteral("MN1");
+ return QStringLiteral("H1");
+}
+
+// ── Account snapshot (funds + positions + live prices in one call) ───────────
+
+ApiResponse<QJsonObject> TickerAllBroker::account_snapshot(const BrokerCredentials& creds, int max_age_s) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ if (max_age_s > 0) {
+ QMutexLocker lock(&snapshot_mutex_);
+ const auto it = snapshot_cache_.constFind(account_id);
+ if (it != snapshot_cache_.constEnd() && now_ts() - it->fetched_at < max_age_s)
+ return {true, it->payload, ""};
+ }
+
+ const QString url = QStringLiteral("%1/v1/accounts/%2").arg(base_url(), account_id);
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+ if (!resp.success)
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch account snapshot.")};
+
+ // An account that is provisioned but not currently logged in answers
+ // status:"offline" with no `account` block. Surface that as a real error
+ // instead of reporting a zero balance as though it were the truth.
+ const QString status = resp.json.value("status").toString();
+ if (status == QLatin1String("offline"))
+ return {false, std::nullopt,
+ QStringLiteral("MT5 account is offline on TickerAll. Reconnect it to resume trading.")};
+
+ {
+ QMutexLocker lock(&snapshot_mutex_);
+ snapshot_cache_[account_id] = Snapshot{resp.json, now_ts()};
+ }
+ return {true, resp.json, ""};
+}
+
+// ── Authentication (TickerAll session start) ─────────────────────────────────
+
+TokenExchangeResponse TickerAllBroker::exchange_token(const QString& api_key, const QString& /*api_secret*/,
+ const QString& auth_code) {
+ TokenExchangeResponse result;
+
+ const auto payload = QJsonDocument::fromJson(auth_code.toUtf8()).object();
+ const QString login = payload.value("login").toString();
+ const QString password = payload.value("password").toString();
+ const QString server = payload.value("server").toString();
+ const QString account_type = payload.value("account_type").toString(QStringLiteral("demo"));
+
+ if (api_key.isEmpty()) {
+ result.error = "TickerAll API key is required.";
+ return result;
+ }
+ if (login.isEmpty() || password.isEmpty() || server.isEmpty()) {
+ result.error = "MT5 login, password, and server name are required.";
+ return result;
+ }
+
+ const QMap<QString, QString> headers = {
+ {"Authorization", QStringLiteral("Bearer %1").arg(api_key)},
+ {"Content-Type", "application/json"},
+ {"Accept", "application/json"},
+ };
+
+ QJsonObject body;
+ body["broker"] = QStringLiteral("mt5");
+ body["server"] = server;
+ body["password"] = password;
+ // `account` is number|string upstream. MT5 logins are numeric, so send a
+ // number when it parses cleanly and fall back to the raw string otherwise.
+ bool numeric = false;
+ const qlonglong login_num = login.toLongLong(&numeric);
+ if (numeric)
+ body["account"] = login_num;
+ else
+ body["account"] = login;
+
+ const QString url = QStringLiteral("%1/v1/sessions").arg(base_url());
+ auto resp = BrokerHttp::instance().post_json(url, body, headers);
+ if (!resp.success) {
+ result.error = checked_error(resp, "Failed to start the TickerAll MT5 session.");
+ return result;
+ }
+
+ const QString account_id = resp.json.value("accountId").toString();
+ if (account_id.isEmpty()) {
+ result.error = "TickerAll did not return an accountId.";
+ return result;
+ }
+
+ // Verify the session actually reached the broker before we report success —
+ // a started session that never logs in would otherwise look connected.
+ const QString verify_url = QStringLiteral("%1/v1/accounts/%2").arg(base_url(), account_id);
+ auto verify = BrokerHttp::instance().get(verify_url, headers);
+ if (!verify.success) {
+ result.error = checked_error(verify, "MT5 session started but verification failed.");
+ return result;
+ }
+ if (verify.json.value("status").toString() == QLatin1String("offline")) {
+ result.error = "MT5 session started but the broker connection is offline. Check server name and password.";
+ return result;
+ }
+
+ // Trust the server's own demo/live classification over the user's dropdown.
+ const bool is_demo = resp.json.value("isDemo").toBool(account_type == QLatin1String("demo"));
+
+ result.success = true;
+ result.access_token = account_id;
+ result.user_id = login;
+ result.additional_data = QString::fromUtf8(QJsonDocument(QJsonObject{
+ {"server", server},
+ {"platform", "mt5"},
+ {"account_type", is_demo ? "demo" : "live"},
+ })
+ .toJson(QJsonDocument::Compact));
+ return result;
+}
+
+// ── Order placement ──────────────────────────────────────────────────────────
+
+OrderPlaceResponse TickerAllBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {
+ OrderPlaceResponse result;
+
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty()) {
+ result.error = "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first.";
+ return result;
+ }
+
+ const QString url = QStringLiteral("%1/v1/accounts/%2/orders").arg(base_url(), account_id);
+
+ QJsonObject body;
+ body["type"] = order_type_for(order.order_type);
+ body["symbol"] = order.symbol;
+ body["side"] = (order.side == OrderSide::Buy) ? QStringLiteral("BUY") : QStringLiteral("SELL");
+ body["volume"] = order.quantity;
+
+ // `price` is the trigger level for limit/stop; a market order must not carry one.
+ if (order.order_type != OrderType::Market && order.price > 0)
+ body["price"] = order.price;
+ if (order.stop_loss > 0)
+ body["stopLoss"] = order.stop_loss;
+ if (order.take_profit > 0)
+ body["takeProfit"] = order.take_profit;
+
+ auto headers = auth_headers(creds);
+ // TickerAll deduplicates state-changing calls on Idempotency-Key. UnifiedOrder
+ // mints client_order_id ONCE per order intent (UnifiedTrading::place_order), so
+ // a resubmit after BrokerHttp's 8 s client-side timeout is rejected as a
+ // duplicate instead of opening a second live position.
+ if (!order.client_order_id.isEmpty())
+ headers.insert(QStringLiteral("Idempotency-Key"), order.client_order_id);
+
+ auto resp = BrokerHttp::instance().post_json(url, body, headers);
+ if (!resp.success) {
+ result.error = checked_error(resp, "Failed to place order.");
+ return result;
+ }
+
+ const QString ticket = ticket_str(resp.json.value("ticket"));
+ if (ticket.isEmpty()) {
+ result.error = QStringLiteral("MT5 accepted the request but returned no ticket.");
+ return result;
+ }
+
+ result.success = true;
+ result.order_id = ticket;
+
+ // A fill changes balance and positions; drop the snapshot so the next
+ // portfolio read reflects it rather than serving a stale cached one.
+ {
+ QMutexLocker lock(&snapshot_mutex_);
+ snapshot_cache_.remove(account_id);
+ }
+ return result;
+}
+
+// ── Order modification (pending orders) ──────────────────────────────────────
+
+ApiResponse<QJsonObject> TickerAllBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,
+ const QJsonObject& mods) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ const QString url =
+ QStringLiteral("%1/v1/accounts/%2/orders/%3").arg(base_url(), account_id, order_id);
+
+ // Read through modify_fields so every caller spelling of a concept is
+ // accepted — a missed spelling silently transmits 0 (BrokerModifyFields.h).
+ QJsonObject body;
+ if (modify_fields::has_any(mods, modify_fields::kPrice))
+ body["price"] = modify_fields::number(mods, modify_fields::kPrice);
+ if (modify_fields::has_any(mods, modify_fields::kTrigger))
+ body["stopLoss"] = modify_fields::number(mods, modify_fields::kTrigger);
+ if (mods.contains(QStringLiteral("take_profit")))
+ body["takeProfit"] = mods.value(QStringLiteral("take_profit")).toVariant().toDouble();
+ else if (mods.contains(QStringLiteral("takeProfit")))
+ body["takeProfit"] = mods.value(QStringLiteral("takeProfit")).toVariant().toDouble();
+
+ if (body.isEmpty())
+ return {false, std::nullopt, "Nothing to modify — supply price, stop loss or take profit."};
+
+ auto resp = BrokerHttp::instance().patch_json(url, body, auth_headers(creds));
+ if (!resp.success)
+ return {false, std::nullopt, checked_error(resp, "Failed to modify order.")};
+
+ return {true, resp.json, ""};
+}
+
+// ── Order cancellation (pending orders) ──────────────────────────────────────
+
+ApiResponse<QJsonObject> TickerAllBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ const QString url =
+ QStringLiteral("%1/v1/accounts/%2/orders/%3").arg(base_url(), account_id, order_id);
+
+ auto resp = BrokerHttp::instance().del(url, auth_headers(creds));
+ if (!resp.success)
+ return {false, std::nullopt, checked_error(resp, "Failed to cancel order.")};
+
+ return {true, resp.json, ""};
+}
+
+// ── Pending orders ───────────────────────────────────────────────────────────
+
+ApiResponse<QVector<BrokerOrderInfo>> TickerAllBroker::get_orders(const BrokerCredentials& creds) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ // waitMs=0: this is a poller, so don't let the server block waiting for a
+ // just-warmed connection's snapshot to settle.
+ const QString url =
+ QStringLiteral("%1/v1/accounts/%2/orders/pending?waitMs=0").arg(base_url(), account_id);
+
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+ if (!resp.success)
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch pending orders.")};
+
+ const auto arr = resp.json.value("orders").toArray();
+
+ QVector<BrokerOrderInfo> orders;
+ orders.reserve(arr.size());
+
+ for (const auto& item : arr) {
+ const auto o = item.toObject();
+ BrokerOrderInfo info;
+ info.order_id = ticket_str(o.value("ticket"));
+ info.symbol = o.value("symbol").toString();
+ info.exchange = QStringLiteral("FOREX");
+ info.side = (o.value("side").toString().compare("BUY", Qt::CaseInsensitive) == 0) ? "buy" : "sell";
+
+ const QString ot = o.value("orderType").toString().toUpper();
+ if (ot == QLatin1String("LIMIT"))
+ info.order_type = "limit";
+ else if (ot == QLatin1String("STOP_LIMIT"))
+ info.order_type = "stop_limit";
+ else if (ot == QLatin1String("STOP"))
+ info.order_type = "stop";
+ else
+ info.order_type = "market";
+
+ info.product_type = QStringLiteral("MARGIN");
+ info.quantity = o.value("volume").toDouble();
+ // `price` is the trigger level; `limitPrice` (nullable) is the limit leg
+ // of a stop-limit. Report the limit leg as price when present.
+ const QJsonValue limit_px = o.value("limitPrice");
+ info.price = (limit_px.isDouble()) ? limit_px.toDouble() : o.value("price").toDouble();
+ info.trigger_price = o.value("price").toDouble();
+ info.stop_price = o.value("stopLoss").toDouble();
+ info.filled_qty = 0;
+ info.avg_price = 0;
+ // Everything this endpoint returns is by definition still working.
+ info.status = "open";
+ info.timestamp = o.value("setTime").toString();
+
+ orders.append(info);
+ }
+
+ return {true, orders, ""};
+}
+
+// ── Trade book (closed round-trips) ──────────────────────────────────────────
+
+ApiResponse<QJsonObject> TickerAllBroker::get_trade_book(const BrokerCredentials& creds) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ const auto now = QDateTime::currentDateTimeUtc();
+ const auto start = now.addDays(-30);
+
+ QUrlQuery q;
+ q.addQueryItem(QStringLiteral("from"), start.toString(Qt::ISODate));
+ q.addQueryItem(QStringLiteral("to"), now.toString(Qt::ISODate));
+ q.addQueryItem(QStringLiteral("limit"), QStringLiteral("500"));
+ q.addQueryItem(QStringLiteral("waitMs"), QStringLiteral("0"));
+
+ const QString url = QStringLiteral("%1/v1/accounts/%2/history?%3").arg(base_url(), account_id, q.toString());
+
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+ if (!resp.success)
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch trade history.")};
+
+ return {true, resp.json, ""};
+}
+
+// ── Positions ────────────────────────────────────────────────────────────────
+
+ApiResponse<QVector<BrokerPosition>> TickerAllBroker::get_positions(const BrokerCredentials& creds) {
+ auto snap = account_snapshot(creds, /*max_age_s=*/2);
+ if (!snap.success)
+ return {false, std::nullopt, snap.error};
+
+ const auto arr = snap.data->value("positions").toArray();
+
+ QVector<BrokerPosition> positions;
+ positions.reserve(arr.size());
+
+ for (const auto& item : arr) {
+ const auto p = item.toObject();
+ BrokerPosition pos;
+ pos.symbol = p.value("symbol").toString();
+ pos.exchange = QStringLiteral("FOREX");
+ pos.product_type = QStringLiteral("MARGIN");
+ pos.side = (p.value("side").toString().compare("BUY", Qt::CaseInsensitive) == 0) ? "long" : "short";
+ pos.quantity = p.value("volume").toDouble();
+ pos.avg_price = p.value("entryPrice").toDouble();
+ pos.ltp = p.value("currentPrice").toDouble();
+ pos.pnl = p.value("profit").toDouble();
+
+ if (pos.avg_price > 0 && pos.quantity != 0) {
+ const double invested = std::abs(pos.avg_price * pos.quantity);
+ pos.pnl_pct = (invested != 0) ? (pos.pnl / invested) * 100.0 : 0.0;
+ }
+
+ positions.append(pos);
+ }
+
+ return {true, positions, ""};
+}
+
+// ── Holdings (MT5 has no separate holdings concept — mirror positions) ───────
+
+ApiResponse<QVector<BrokerHolding>> TickerAllBroker::get_holdings(const BrokerCredentials& creds) {
+ auto pos_result = get_positions(creds);
+ if (!pos_result.success)
+ return {false, std::nullopt, pos_result.error};
+
+ QVector<BrokerHolding> holdings;
+ holdings.reserve(pos_result.data->size());
+
+ for (const auto& p : *pos_result.data) {
+ BrokerHolding h;
+ h.symbol = p.symbol;
+ h.exchange = p.exchange;
+ h.quantity = p.quantity;
+ h.avg_price = p.avg_price;
+ h.ltp = p.ltp;
+ h.pnl = p.pnl;
+ h.pnl_pct = p.pnl_pct;
+ // invested/current ignore contract (lot) size: quantity is lots (e.g. 0.10),
+ // not units, so price*lots is off by contractSize. The position payload
+ // carries no contract size, and `profit` from the API is authoritative for
+ // P&L, so these two are display-only approximations — same caveat as
+ // MetaApiBroker::get_holdings.
+ h.invested_value = p.avg_price * p.quantity;
+ h.current_value = p.ltp * p.quantity;
+ holdings.append(h);
+ }
+
+ return {true, holdings, ""};
+}
+
+// ── Funds / account information ──────────────────────────────────────────────
+
+ApiResponse<BrokerFunds> TickerAllBroker::get_funds(const BrokerCredentials& creds) {
+ auto snap = account_snapshot(creds, /*max_age_s=*/2);
+ if (!snap.success)
+ return {false, std::nullopt, snap.error};
+
+ const QJsonObject acct = snap.data->value("account").toObject();
+ if (acct.isEmpty())
+ return {false, std::nullopt, "TickerAll returned no account block — the MT5 session may still be warming up."};
+
+ BrokerFunds funds;
+ funds.total_balance = acct.value("balance").toDouble();
+ funds.available_balance = acct.value("freeMargin").toDouble();
+ funds.used_margin = acct.value("margin").toDouble();
+ funds.collateral = 0;
+
+ funds.raw_data = acct;
+ funds.raw_data["equity"] = acct.value("equity").toDouble();
+ funds.raw_data["leverage"] = acct.value("leverage").toInt();
+ // marginLevel is null when no margin is in use — normalise to 0.
+ funds.raw_data["marginLevel"] = acct.value("marginLevel").toDouble(0.0);
+ funds.raw_data["currency"] = acct.value("currency").toString();
+
+ return {true, funds, ""};
+}
+
+// ── Quotes ───────────────────────────────────────────────────────────────────
+
+ApiResponse<QVector<BrokerQuote>> TickerAllBroker::get_quotes(const BrokerCredentials& creds,
+ const QVector<QString>& symbols) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ // TickerAll serves live ticks over WebSocket only — there is no REST quote
+ // endpoint — but get_quotes() is a synchronous IBroker call. Two REST sources
+ // cover it without a socket:
+ // 1. the account snapshot, whose open positions carry a live currentPrice
+ // (free: one call, already cached, and exact for everything we hold);
+ // 2. for anything not held, one M1 candle, whose `bid` and `spread` fields
+ // give a true bid/ask pair rather than a synthetic mid.
+ // A future WS-backed tick cache (IBroker::ws_adapter_name) would supersede
+ // step 2 and drop the per-symbol call entirely.
+ QHash<QString, QJsonObject> live_positions;
+ auto snap = account_snapshot(creds, /*max_age_s=*/2);
+ if (snap.success) {
+ for (const auto& item : snap.data->value("positions").toArray()) {
+ const auto p = item.toObject();
+ const double px = p.value("currentPrice").toDouble();
+ if (px > 0)
+ live_positions.insert(p.value("symbol").toString(), p);
+ }
+ }
+
+ QVector<BrokerQuote> quotes;
+ quotes.reserve(symbols.size());
+
+ for (const auto& sym : symbols) {
+ BrokerQuote q;
+ q.symbol = sym;
+
+ const auto held = live_positions.constFind(sym);
+ if (held != live_positions.constEnd()) {
+ const double px = held->value("currentPrice").toDouble();
+ q.ltp = px;
+ q.close = px;
+ // A position quotes at its own close side; no bid/ask split is exposed.
+ q.bid = px;
+ q.ask = px;
+ const auto dt = QDateTime::fromString(held->value("lastUpdate").toString(), Qt::ISODate);
+ q.timestamp = dt.isValid() ? dt.toSecsSinceEpoch() : now_ts();
+ quotes.append(q);
+ continue;
+ }
+
+ QUrlQuery cq;
+ cq.addQueryItem(QStringLiteral("symbol"), sym);
+ cq.addQueryItem(QStringLiteral("count"), QStringLiteral("1"));
+ cq.addQueryItem(QStringLiteral("timeframe"), QStringLiteral("M1"));
+ const QString url =
+ QStringLiteral("%1/v1/accounts/%2/candles?%3").arg(base_url(), account_id, cq.toString());
+
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+ if (!resp.success)
+ continue; // one bad symbol must not fail the whole batch
+
+ const auto arr = resp.json.value("candles").toArray();
+ if (arr.isEmpty())
+ continue;
+
+ const auto c = arr.last().toObject();
+ const double close = c.value("close").toDouble();
+ // `bid` mirrors close; `spread` is (ask - bid) in price units, 0 when no
+ // ask tick landed in the bar — in which case ask degrades to bid.
+ const double bid = c.value("bid").toDouble(close);
+ const double spread = c.value("spread").toDouble(0.0);
+
+ q.ltp = close;
+ q.open = c.value("open").toDouble();
+ q.high = c.value("high").toDouble();
+ q.low = c.value("low").toDouble();
+ q.close = close;
+ q.bid = bid;
+ q.ask = (spread > 0.0) ? bid + spread : bid;
+ q.volume = c.value("tickVolume").toDouble(0.0);
+ if (q.open > 0) {
+ q.change = close - q.open;
+ q.change_pct = (q.change / q.open) * 100.0;
+ }
+ // Candle.timestamp is the bar OPEN time in Unix SECONDS; BrokerQuote's
+ // contract is seconds too, so it passes through unscaled.
+ q.timestamp = static_cast<int64_t>(c.value("timestamp").toDouble(static_cast<double>(now_ts())));
+
+ quotes.append(q);
+ }
+
+ return {true, quotes, ""};
+}
+
+// ── Historical candles ───────────────────────────────────────────────────────
+
+ApiResponse<QVector<BrokerCandle>> TickerAllBroker::get_history(const BrokerCredentials& creds, const QString& symbol,
+ const QString& resolution, const QString& from_date,
+ const QString& to_date) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {false, std::nullopt, "[TOKEN_EXPIRED] No TickerAll session. Connect the MT5 account first."};
+
+ const QString tf = map_timeframe(resolution);
+
+ QUrlQuery q;
+ q.addQueryItem(QStringLiteral("symbol"), symbol);
+ q.addQueryItem(QStringLiteral("timeframe"), tf);
+
+ // The endpoint takes exactly one of: hours, count, or a from+to pair. Prefer
+ // the explicit range when both bounds parse; otherwise fall back to a 24 h
+ // look-back so a caller that passes nothing still gets a usable series.
+ const QDateTime from_dt = parse_dt(from_date);
+ const QDateTime to_dt = parse_dt(to_date);
+ const bool ranged = from_dt.isValid() && to_dt.isValid() && from_dt < to_dt;
+
+ if (ranged) {
+ q.addQueryItem(QStringLiteral("from"), from_dt.toString(Qt::ISODate));
+ q.addQueryItem(QStringLiteral("to"), to_dt.toString(Qt::ISODate));
+ } else if (from_dt.isValid()) {
+ const qint64 hours = std::max<qint64>(1, from_dt.secsTo(QDateTime::currentDateTimeUtc()) / 3600);
+ q.addQueryItem(QStringLiteral("hours"), QString::number(hours));
+ } else {
+ q.addQueryItem(QStringLiteral("hours"), QStringLiteral("24"));
+ }
+
+ const QString url = QStringLiteral("%1/v1/accounts/%2/candles?%3").arg(base_url(), account_id, q.toString());
+
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+ if (!resp.success)
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch candles.")};
+
+ const auto arr = resp.json.value("candles").toArray();
+
+ QVector<BrokerCandle> candles;
+ candles.reserve(arr.size());
+
+ for (const auto& item : arr) {
+ const auto c = item.toObject();
+ BrokerCandle candle;
+ // Candle.timestamp is the bar OPEN time in Unix SECONDS; BrokerCandle's
+ // contract is MILLISECONDS (see AlpacaBroker/SaxoBankBroker), so scale.
+ candle.timestamp = static_cast<int64_t>(c.value("timestamp").toDouble()) * 1000LL;
+ candle.open = c.value("open").toDouble();
+ candle.high = c.value("high").toDouble();
+ candle.low = c.value("low").toDouble();
+ candle.close = c.value("close").toDouble();
+ candle.volume = c.value("tickVolume").toDouble(0.0);
+ candles.append(candle);
+ }
+
+ // The API documents "oldest first", but sort anyway: chart code assumes
+ // ascending order and a silently reversed series draws a mirrored chart.
+ std::sort(candles.begin(), candles.end(),
+ [](const BrokerCandle& a, const BrokerCandle& b) { return a.timestamp < b.timestamp; });
+ candles.erase(std::unique(candles.begin(), candles.end(),
+ [](const BrokerCandle& a, const BrokerCandle& b) { return a.timestamp == b.timestamp; }),
+ candles.end());
+
+ return {true, candles, ""};
+}
+
+// ── Symbol list (cached for an hour) ─────────────────────────────────────────
+
+QStringList TickerAllBroker::fetch_symbols(const BrokerCredentials& creds) {
+ const QString account_id = creds.access_token;
+ if (account_id.isEmpty())
+ return {};
+
+ {
+ QMutexLocker lock(&symbol_mutex_);
+ if (symbol_cache_.contains(account_id)) {
+ const int64_t cached_at = symbol_cache_time_.value(account_id, 0);
+ if (now_ts() - cached_at < 3600)
+ return symbol_cache_.value(account_id);
+ }
+ }
+
+ const QString url = QStringLiteral("%1/v1/accounts/%2/symbols").arg(base_url(), account_id);
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+ if (!resp.success)
+ return {};
+
+ QStringList symbols;
+ for (const auto& item : resp.json.value("symbols").toArray())
+ symbols.append(item.toString());
+
+ {
+ QMutexLocker lock(&symbol_mutex_);
+ symbol_cache_[account_id] = symbols;
+ symbol_cache_time_[account_id] = now_ts();
+ }
+
+ return symbols;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/tickerall/TickerAllBroker.h b/fincept-qt/src/trading/brokers/tickerall/TickerAllBroker.h
new file mode 100644
index 000000000..bf8538ca8
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/tickerall/TickerAllBroker.h
@@ -0,0 +1,125 @@
+#pragma once
+#include "trading/BrokerInterface.h"
+#include "trading/brokers/BrokerHttp.h"
+
+#include <QHash>
+#include <QJsonObject>
+#include <QMutex>
+
+namespace fincept::trading {
+
+// MetaTrader 5 integration via the TickerAll hosted REST bridge (tickerall.com).
+//
+// Why a hosted bridge: the official MetaTrader5 package is Windows-only, drives a
+// local terminal over single-threaded IPC, and pins one running terminal per
+// account. TickerAll holds the broker connection server-side and exposes it over
+// REST, so an MT5 account is reachable from Linux/macOS/containers with no local
+// terminal. Same shape as MetaApiBroker (MT4 via metaapi.cloud), one platform over.
+//
+// Credential packing — deliberately identical in shape to MetaApiBroker so
+// AccountManager, the credential dialog and the session-validation sweep treat
+// both bridges alike:
+// api_key = TickerAll API key ("cf_live_…" / "cf_test_…")
+// access_token = TickerAll accountId returned by POST /v1/sessions
+// user_id = MT5 login number
+// additional_data = JSON {"server","platform":"mt5","account_type":"demo|live"}
+//
+// Quotes: TickerAll exposes no REST tick endpoint — live bid/ask arrive on its
+// WebSocket. get_quotes() is a synchronous IBroker call, so it reads what REST
+// does offer: the account snapshot (open positions carry currentPrice) and, for
+// symbols not held, a single M1 candle whose `bid` + `spread` fields yield a real
+// bid/ask pair rather than a synthetic mid. See get_quotes() for the detail.
+class TickerAllBroker : public IBroker {
+ public:
+ BrokerId id() const override { return BrokerId::MetaTrader5; }
+ const char* name() const override { return "MetaTrader 5"; }
+ const char* base_url() const override { return "https://api.tickerall.com"; }
+
+ BrokerProfile profile() const override {
+ return BrokerProfile{
+ .id = "metatrader5",
+ .display_name = "MetaTrader 5",
+ .region = "Global",
+ .currency = "USD",
+ // Rendered by AccountManagementDialog's custom multi-sub-field form
+ // (custom_cred_fields("metatrader5")) because the MT5 server name has
+ // no CredentialField of its own. Kept here so the profile still
+ // describes what this broker needs.
+ .credential_fields =
+ {
+ {CredentialField::ApiKey, "TICKERALL API KEY", "cf_live_… from tickerall.com", true},
+ {CredentialField::UserId, "MT5 LOGIN", "Account number e.g. 12345678", false},
+ {CredentialField::Password, "MT5 PASSWORD", "Trading password", true},
+ },
+ .exchanges = {"FOREX"},
+ .product_types =
+ {
+ {"Margin Trade", ProductType::Margin},
+ },
+ .supports_intraday = true,
+ .supports_bracket_order = false,
+ .supports_cover_order = false,
+ .has_native_paper = true,
+ .default_paper_balance = 10000.0,
+ .default_watchlist = {"EURUSD", "GBPUSD", "USDJPY", "XAUUSD", "US30", "NAS100", "SPX500"},
+ .default_symbol = "EURUSD",
+ .default_exchange = "FOREX",
+ .brokerage_info = "Spread-based (varies by MT5 broker)",
+ };
+ }
+
+ TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,
+ const QString& auth_code) override;
+ OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;
+ ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,
+ const QJsonObject& mods) override;
+ ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;
+ ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;
+ ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;
+ ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;
+ ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;
+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;
+ ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,
+ const QVector<QString>& symbols) override;
+ ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,
+ const QString& resolution, const QString& from_date,
+ const QString& to_date) override;
+
+ // Streaming deferred, same as IciciDirectBroker. TickerAll does expose a
+ // WebSocket (wss://api.tickerall.com/v1/stream: ticks, positions, orders),
+ // and wiring an adapter here is the natural follow-up — it would also let
+ // get_quotes() serve real streamed bid/ask instead of the per-symbol M1
+ // candle fallback it uses today.
+ const char* ws_adapter_name() const override { return ""; }
+
+ // Tradeable symbol list for this account, cached for an hour. Mirrors
+ // MetaApiBroker::fetch_symbols so the order-form symbol picker can share a path.
+ QStringList fetch_symbols(const BrokerCredentials& creds);
+
+ protected:
+ QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;
+
+ private:
+ // GET /v1/accounts/{id} answers funds AND positions AND live prices in one
+ // payload, and get_funds/get_positions/get_holdings/get_quotes each want a
+ // slice of it. A short TTL collapses that burst (the portfolio view calls all
+ // four back-to-back) into one request instead of four.
+ struct Snapshot {
+ QJsonObject payload;
+ int64_t fetched_at = 0;
+ };
+ ApiResponse<QJsonObject> account_snapshot(const BrokerCredentials& creds, int max_age_s);
+
+ static QString order_type_for(OrderType type);
+ static QString map_timeframe(const QString& resolution);
+ static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);
+
+ QHash<QString, Snapshot> snapshot_cache_;
+ mutable QMutex snapshot_mutex_;
+
+ QHash<QString, QStringList> symbol_cache_;
+ QHash<QString, int64_t> symbol_cache_time_;
+ mutable QMutex symbol_mutex_;
+};
+
+} // namespace fincept::trading