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 "trading/brokers/saxo/SaxoBankBroker.h"
#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include <QDateTime>
#include <QJsonArray>
#include <QJsonDocument>
#include <QTimeZone>
#include <QUrlQuery>
#include <algorithm>
#include <limits>
namespace fincept::trading {
// Live and SIM token endpoints
static constexpr const char* TOKEN_URL_LIVE = "https://live.logonvalidation.net/token";
static constexpr const char* TOKEN_URL_SIM = "https://sim.logonvalidation.net/token";
static constexpr const char* BASE_LIVE = "https://gateway.saxobank.com/openapi";
static constexpr const char* BASE_SIM = "https://gateway.saxobank.com/sim/openapi";
static int64_t now_ts() {
return QDateTime::currentSecsSinceEpoch();
}
// exchange_token() records which gateway minted the token under additional_data
// {"environment":"sim"|"live"}. A SIM token is rejected by the live gateway (and vice versa), so
// every REST call must follow it; before this, only the profile lookup inside exchange_token()
// honoured "sim:::" and every later call hit the live host. Anything unmarked stays live.
static QString saxo_base_url(const BrokerCredentials& creds) {
if (!creds.additional_data.isEmpty()) {
const auto ad = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();
if (ad.value("environment").toString() == QLatin1String("sim"))
return QString::fromLatin1(BASE_SIM);
}
return QString::fromLatin1(BASE_LIVE);
}
// ---------- Static helpers ----------
QString SaxoBankBroker::extract_uic(const QString& symbol) {
// Format: "NYSE:AAPL:211" — Uic is 3rd part
QStringList parts = symbol.split(":");
if (parts.size() >= 3)
return parts[2];
return {};
}
QString SaxoBankBroker::extract_asset_type(const QString& symbol) {
// Optional 4th part: "FXCM:EURUSD:21:FxSpot" — AssetType is 4th part; default "Stock".
QStringList parts = symbol.split(":");
if (parts.size() >= 4 && !parts[3].trimmed().isEmpty())
return parts[3].trimmed();
return QStringLiteral("Stock");
}
const BrokerEnumMap<QString>& SaxoBankBroker::saxo_enum_map() {
static const auto m = [] {
BrokerEnumMap<QString> x;
x.set(OrderType::Market, "Market");
x.set(OrderType::Limit, "Limit");
x.set(OrderType::StopLoss, "StopIfTraded");
x.set(OrderType::StopLossLimit, "StopLimit");
// Duration: Delivery → GoodTillCancel; everything else falls back to "DayOrder" at callsite.
x.set(ProductType::Delivery, "GoodTillCancel");
return x;
}();
return m;
}
int SaxoBankBroker::saxo_horizon(const QString& resolution) {
if (resolution == "1" || resolution == "1m")
return 1;
if (resolution == "5" || resolution == "5m")
return 5;
if (resolution == "10" || resolution == "10m")
return 10;
if (resolution == "15" || resolution == "15m")
return 15;
if (resolution == "30" || resolution == "30m")
return 30;
if (resolution == "60" || resolution == "1h")
return 60;
if (resolution == "240" || resolution == "4h")
return 240;
if (resolution == "D" || resolution == "1D")
return 1440;
if (resolution == "W")
return 10080;
if (resolution == "M")
return 43200;
return 1440; // default daily
}
bool SaxoBankBroker::is_token_expired(const BrokerHttpResponse& resp) {
if (resp.status_code == 401)
return true;
if (!resp.success)
return false;
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return false;
QString code = doc.object().value("ErrorCode").toString();
return (code == "InvalidToken" || code == "TokenExpired");
}
QString SaxoBankBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
if (is_token_expired(resp))
return "[TOKEN_EXPIRED] Access token expired, please re-authenticate";
if (!resp.success)
return resp.error.isEmpty() ? fallback : resp.error;
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (doc.isObject()) {
QString msg = doc.object().value("Message").toString();
if (!msg.isEmpty())
return msg;
msg = doc.object().value("ErrorCode").toString();
if (!msg.isEmpty())
return msg;
}
return fallback;
}
// ---------- Auth headers ----------
QMap<QString, QString> SaxoBankBroker::auth_headers(const BrokerCredentials& creds) const {
return {{"Authorization", "Bearer " + creds.access_token},
{"Content-Type", "application/json"},
{"Accept", "application/json"}};
}
// ---------- exchange_token ----------
// Saxo OAuth2 authorization code flow
// ApiKey = App Key (client_id)
// ApiSecret = App Secret (client_secret)
// AuthCode = authorization code from OAuth redirect
// Stores: access_token, refresh_token (in additional), account_key (as user_id)
TokenExchangeResponse SaxoBankBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& auth_code) {
if (auth_code.trimmed().isEmpty())
return {.success = false, .error = "Authorization code is required"};
// Try live token endpoint first; fall back to SIM if it fails
// In practice user should specify sim vs live via auth_code prefix "sim:::code"
bool use_sim = auth_code.startsWith("sim:::");
QString code = use_sim ? auth_code.mid(6) : auth_code;
QString token_url = use_sim ? TOKEN_URL_SIM : TOKEN_URL_LIVE;
QUrlQuery form;
form.addQueryItem("grant_type", "authorization_code");
form.addQueryItem("code", code);
form.addQueryItem("redirect_uri", "http://localhost");
form.addQueryItem("client_id", api_key);
form.addQueryItem("client_secret", api_secret);
auto& http = BrokerHttp::instance();
auto resp = http.post_raw(token_url, form.toString(QUrl::FullyEncoded).toUtf8(),
{{"Content-Type", "application/x-www-form-urlencoded"}, {"Accept", "application/json"}});
if (!resp.success)
return {.success = false, .error = "Token exchange failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {.success = false, .error = "Token exchange: invalid response"};
QJsonObject obj = doc.object();
QString access_token = obj.value("access_token").toString();
QString refresh_token = obj.value("refresh_token").toString();
if (access_token.isEmpty())
return {.success = false, .error = obj.value("error_description").toString("Token exchange failed")};
// Fetch AccountKey from /port/v1/clients/me
QString base = use_sim ? BASE_SIM : BASE_LIVE;
auto profile_resp = http.get(base + "/port/v1/clients/me",
{{"Authorization", "Bearer " + access_token}, {"Accept", "application/json"}});
QString account_key;
if (profile_resp.success) {
QJsonDocument pdoc = QJsonDocument::fromJson(profile_resp.raw_body.toUtf8());
if (pdoc.isObject()) {
account_key = pdoc.object().value("DefaultAccountKey").toString();
if (account_key.isEmpty())
account_key = pdoc.object().value("ClientKey").toString();
}
}
// Record which gateway minted the token (REST calls must follow it — see saxo_base_url) and
// the access token's real lifetime (`expires_in`, ~20 min) so the session sweep can refresh
// it before it lapses.
double expires_in = obj.value("expires_in").toVariant().toDouble();
if (expires_in <= 0.0)
expires_in = 1200.0;
const QString extra = with_token_expiry(
QString::fromUtf8(QJsonDocument(QJsonObject{{"environment", use_sim ? "sim" : "live"}})
.toJson(QJsonDocument::Compact)),
rolling_expiry_epoch(expires_in / 3600.0));
return {.success = true,
.access_token = access_token,
.refresh_token = refresh_token,
.user_id = account_key,
.additional_data = extra};
}
// Saxo access tokens live ~20 minutes and the user cannot re-run the OAuth code flow that often.
// The (rolling) refresh token minted alongside re-issues one with no interaction:
// POST {token endpoint} grant_type=refresh_token + client_id/client_secret.
TokenExchangeResponse SaxoBankBroker::refresh_session(const BrokerCredentials& creds) {
if (creds.refresh_token.isEmpty() || creds.api_key.isEmpty() || creds.api_secret.isEmpty())
return {.success = false, .error = "Saxo silent refresh requires a stored refresh token and app key/secret"};
bool use_sim = false;
if (!creds.additional_data.isEmpty())
use_sim = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object().value("environment").toString() ==
QLatin1String("sim");
QUrlQuery form;
form.addQueryItem("grant_type", "refresh_token");
form.addQueryItem("refresh_token", creds.refresh_token);
form.addQueryItem("client_id", creds.api_key);
form.addQueryItem("client_secret", creds.api_secret);
auto resp = BrokerHttp::instance().post_raw(
use_sim ? TOKEN_URL_SIM : TOKEN_URL_LIVE, form.toString(QUrl::FullyEncoded).toUtf8(),
{{"Content-Type", "application/x-www-form-urlencoded"}, {"Accept", "application/json"}});
const QString access_token = resp.json.value("access_token").toString();
if (!resp.success || access_token.isEmpty())
return {.success = false,
.error = resp.json.value("error_description").toString(resp.error.isEmpty() ? "Token refresh failed"
: resp.error)};
double expires_in = resp.json.value("expires_in").toVariant().toDouble();
if (expires_in <= 0.0)
expires_in = 1200.0;
// Saxo rotates the refresh token on every use; keep the old one only if the reply omits it.
const QString new_refresh = resp.json.value("refresh_token").toString();
const QString extra = with_token_expiry(
QString::fromUtf8(QJsonDocument(QJsonObject{{"environment", use_sim ? "sim" : "live"}})
.toJson(QJsonDocument::Compact)),
rolling_expiry_epoch(expires_in / 3600.0));
return {.success = true,
.access_token = access_token,
.refresh_token = new_refresh.isEmpty() ? creds.refresh_token : new_refresh,
.user_id = creds.user_id,
.additional_data = extra};
}
// ---------- place_order ----------
OrderPlaceResponse SaxoBankBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {
QString uic_str = order.instrument_token;
if (uic_str.isEmpty())
uic_str = extract_uic(order.symbol);
if (uic_str.isEmpty())
return {false, "", "Saxo place_order: Uic required (symbol format: EXCHANGE:SYMBOL:UIC)"};
QString account_key = creds.user_id;
QJsonObject order_obj;
order_obj["AccountKey"] = account_key;
order_obj["Uic"] = uic_str.toLongLong();
// AssetType from the optional 4th symbol segment (EXCH:SYM:UIC:ASSETTYPE);
// defaults to "Stock" so existing 3-part equity symbols are unchanged.
order_obj["AssetType"] = extract_asset_type(order.symbol);
order_obj["BuySell"] = (order.side == OrderSide::Buy) ? "Buy" : "Sell";
order_obj["Amount"] = order.quantity;
order_obj["OrderType"] = saxo_enum_map().order_type_or(order.order_type, "Market");
order_obj["ManualOrder"] = false;
// Stable per order intent (UnifiedOrder::client_order_id) so a retry after an 8s
// client-side timeout carries the same reference (see BrokerClientOrderId.h).
order_obj["ExternalReference"] = client_order_ref_for(order, 50);
if (order.order_type != OrderType::Market)
order_obj["OrderPrice"] = order.price;
if (order.stop_price > 0)
order_obj["StopLimitPrice"] = order.stop_price;
QJsonObject duration;
duration["DurationType"] = saxo_enum_map().product_or(order.product_type, "DayOrder");
order_obj["OrderDuration"] = duration;
auto& http = BrokerHttp::instance();
auto resp = http.post_json(QString("%1/trade/v2/orders").arg(saxo_base_url(creds)), order_obj, auth_headers(creds));
if (!resp.success)
return {false, "", checked_error(resp, "place_order failed")};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, "", "place_order: invalid response"};
QJsonObject obj = doc.object();
QString order_id = obj.value("OrderId").toString();
if (order_id.isEmpty())
return {false, "", checked_error(resp, obj.value("Message").toString("place_order failed"))};
return {true, order_id, ""};
}
// ---------- modify_order ----------
ApiResponse<QJsonObject> SaxoBankBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,
const QJsonObject& mods) {
int64_t ts = now_ts();
QJsonObject body;
body["AccountKey"] = creds.user_id;
body["OrderId"] = order_id;
// modify_order has no symbol; let the caller pass "assetType" in mods for
// FX/CFD/futures, defaulting to "Stock" to preserve existing equity behavior.
body["AssetType"] = mods.value("assetType").toString("Stock");
body["ManualOrder"] = false;
if (mods.contains("quantity"))
body["Amount"] = mods.value("quantity").toDouble();
if (mods.contains("price"))
body["OrderPrice"] = mods.value("price").toDouble();
if (mods.contains("orderType"))
body["OrderType"] = mods.value("orderType").toString();
if (mods.contains("duration")) {
QJsonObject dur;
dur["DurationType"] = mods.value("duration").toString("DayOrder");
body["OrderDuration"] = dur;
}
auto& http = BrokerHttp::instance();
auto resp = http.patch_json(QString("%1/trade/v2/orders").arg(saxo_base_url(creds)), body, auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "modify_order: invalid response", ts};
return {true, doc.object(), "", ts};
}
// ---------- cancel_order ----------
ApiResponse<QJsonObject> SaxoBankBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {
int64_t ts = now_ts();
auto& http = BrokerHttp::instance();
auto resp = http.del(
QString("%1/trade/v2/orders/%2?AccountKey=%3").arg(saxo_base_url(creds), order_id, creds.user_id),
auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "cancel_order: invalid response", ts};
return {true, doc.object(), "", ts};
}
// ---------- get_orders ----------
ApiResponse<QVector<BrokerOrderInfo>> SaxoBankBroker::get_orders(const BrokerCredentials& creds) {
int64_t ts = now_ts();
auto& http = BrokerHttp::instance();
auto resp = http.get(QString("%1/port/v1/orders/me?FieldGroups=DisplayAndFormat").arg(saxo_base_url(creds)),
auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "get_orders: invalid response", ts};
QJsonArray arr = doc.object().value("Data").toArray();
QVector<BrokerOrderInfo> orders;
orders.reserve(arr.size());
auto parse_status = [](const QString& s) -> QString {
if (s == "FinalFill")
return "filled";
if (s == "Cancelled" || s == "Expired")
return "cancelled";
if (s == "Working" || s == "Placed")
return "open";
if (s == "PartiallyFilled")
return "open";
return "open";
};
for (const QJsonValue& v : arr) {
QJsonObject o = v.toObject();
BrokerOrderInfo info;
info.order_id = o.value("OrderId").toString();
info.symbol = o.value("DisplayAndFormat").toObject().value("Symbol").toString();
info.exchange = o.value("Exchange").toObject().value("ExchangeId").toString();
info.quantity = o.value("Amount").toDouble();
info.price = o.value("Price").toDouble();
info.status = parse_status(o.value("Status").toString());
info.side = (o.value("BuySell").toString() == "Buy") ? "buy" : "sell";
info.order_type = o.value("OpenOrderType").toString();
info.product_type = o.value("Duration").toObject().value("DurationType").toString();
info.timestamp = o.value("OrderTime").toString();
orders.append(info);
}
return {true, orders, "", ts};
}
// ---------- get_trade_book ----------
ApiResponse<QJsonObject> SaxoBankBroker::get_trade_book(const BrokerCredentials& creds) {
int64_t ts = now_ts();
auto& http = BrokerHttp::instance();
auto resp = http.get(QString("%1/port/v1/orders/me").arg(saxo_base_url(creds)), auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "get_trade_book failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "get_trade_book: invalid response", ts};
return {true, doc.object(), "", ts};
}
// ---------- get_positions ----------
ApiResponse<QVector<BrokerPosition>> SaxoBankBroker::get_positions(const BrokerCredentials& creds) {
int64_t ts = now_ts();
auto& http = BrokerHttp::instance();
auto resp = http.get(QString("%1/port/v1/positions/me?FieldGroups=DisplayAndFormat,PositionBase,PositionView")
.arg(saxo_base_url(creds)),
auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "get_positions: invalid response", ts};
QJsonArray arr = doc.object().value("Data").toArray();
QVector<BrokerPosition> positions;
for (const QJsonValue& v : arr) {
QJsonObject o = v.toObject();
QJsonObject base = o.value("PositionBase").toObject();
QJsonObject view = o.value("PositionView").toObject();
QJsonObject disp = o.value("DisplayAndFormat").toObject();
double qty = base.value("Amount").toDouble();
if (qty == 0.0)
continue;
BrokerPosition pos;
pos.symbol = disp.value("Symbol").toString();
pos.exchange = base.value("AssetType").toString();
pos.quantity = qty;
pos.avg_price = base.value("OpenPrice").toDouble();
pos.ltp = view.value("CurrentPrice").toDouble();
pos.pnl = view.value("ProfitLossOnTrade").toDouble();
pos.side = qty > 0 ? "LONG" : "SHORT";
if (pos.avg_price > 0)
pos.pnl_pct = pos.pnl / (pos.avg_price * qAbs(qty)) * 100.0;
positions.append(pos);
}
return {true, positions, "", ts};
}
// ---------- get_holdings ----------
ApiResponse<QVector<BrokerHolding>> SaxoBankBroker::get_holdings(const BrokerCredentials& creds) {
int64_t ts = now_ts();
auto& http = BrokerHttp::instance();
auto resp =
http.get(QString("%1/port/v1/netpositions/me?FieldGroups=DisplayAndFormat,NetPositionBase,NetPositionView")
.arg(saxo_base_url(creds)),
auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "get_holdings: invalid response", ts};
QJsonArray arr = doc.object().value("Data").toArray();
QVector<BrokerHolding> holdings;
for (const QJsonValue& v : arr) {
QJsonObject o = v.toObject();
QJsonObject base = o.value("NetPositionBase").toObject();
QJsonObject view = o.value("NetPositionView").toObject();
QJsonObject disp = o.value("DisplayAndFormat").toObject();
double qty = base.value("Amount").toDouble();
if (qty <= 0.0)
continue; // holdings = long positions only
BrokerHolding h;
h.symbol = disp.value("Symbol").toString();
h.exchange = base.value("AssetType").toString();
h.quantity = qty;
h.avg_price = view.value("AverageOpenPrice").toDouble();
h.ltp = view.value("CurrentPrice").toDouble();
h.pnl = view.value("ProfitLossOnTrade").toDouble();
h.invested_value = h.avg_price * qty;
h.current_value = h.ltp * qty;
if (h.invested_value > 0)
h.pnl_pct = h.pnl / h.invested_value * 100.0;
holdings.append(h);
}
return {true, holdings, "", ts};
}
// ---------- get_funds ----------
ApiResponse<BrokerFunds> SaxoBankBroker::get_funds(const BrokerCredentials& creds) {
int64_t ts = now_ts();
auto& http = BrokerHttp::instance();
auto resp = http.get(QString("%1/port/v1/balances/me").arg(saxo_base_url(creds)), auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "get_funds: invalid response", ts};
QJsonObject obj = doc.object();
BrokerFunds funds;
funds.total_balance = obj.value("TotalValue").toDouble();
funds.available_balance = obj.value("MarginAvailableForTrading").toDouble();
funds.used_margin = qAbs(obj.value("MarginUsedByCurrentPositions").toDouble());
funds.collateral = obj.value("CollateralCreditValue").toObject().value("Line").toDouble();
return {true, funds, "", ts};
}
// ---------- get_quotes ----------
// Symbol format: "NYSE:AAPL:211" — Uic is 3rd part
// Uses /trade/v1/infoprices/list for multiple symbols (same AssetType per call)
ApiResponse<QVector<BrokerQuote>> SaxoBankBroker::get_quotes(const BrokerCredentials& creds,
const QVector<QString>& symbols) {
int64_t ts = now_ts();
if (symbols.isEmpty())
return {true, QVector<BrokerQuote>{}, "", ts};
// Collect Uics and reverse map
QStringList uics;
QMap<QString, QString> uic_to_name;
for (const QString& sym : symbols) {
QString uic = extract_uic(sym);
if (uic.isEmpty())
continue;
QString name = sym.contains(':') ? sym.section(':', 1, 1) : sym;
uics.append(uic);
uic_to_name[uic] = name;
}
if (uics.isEmpty())
return {false, std::nullopt, "get_quotes: Uic required (symbol format EXCHANGE:SYMBOL:UIC)", ts};
// infoprices/list takes a single AssetType per call — derive it from the first
// symbol's optional 4th segment (EXCH:SYM:UIC:ASSETTYPE); defaults to "Stock".
const QString asset_type = extract_asset_type(symbols.first());
QString url = QString("%1/trade/v1/infoprices/list?Uics=%2&AssetType=%3"
"&FieldGroups=DisplayAndFormat,PriceInfo,PriceInfoDetails,Quote")
.arg(saxo_base_url(creds), uics.join(","), asset_type);
auto& http = BrokerHttp::instance();
auto resp = http.get(url, auth_headers(creds));
if (!resp.success)
return {false, std::nullopt, checked_error(resp, "get_quotes failed"), ts};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
return {false, std::nullopt, "get_quotes: invalid response", ts};
QJsonArray arr = doc.object().value("Data").toArray();
QVector<BrokerQuote> quotes;
quotes.reserve(arr.size());
for (const QJsonValue& v : arr) {
QJsonObject o = v.toObject();
QString uic_key = QString::number(o.value("Uic").toVariant().toLongLong());
QJsonObject quote_obj = o.value("Quote").toObject();
QJsonObject price_info = o.value("PriceInfo").toObject();
QJsonObject details = o.value("PriceInfoDetails").toObject();
BrokerQuote q;
q.symbol = uic_to_name.value(uic_key, o.value("DisplayAndFormat").toObject().value("Symbol").toString());
// Use Mid price for LTP; fall back to LastTraded
q.ltp = quote_obj.value("Mid").toDouble();
if (q.ltp == 0.0)
q.ltp = details.value("LastTraded").toDouble();
q.open = details.value("Open").toDouble();
q.high = price_info.value("High").toDouble();
q.low = price_info.value("Low").toDouble();
q.close = details.value("LastClose").toDouble();
q.volume = static_cast<int64_t>(details.value("Volume").toDouble());
q.change = price_info.value("NetChange").toDouble();
q.change_pct = price_info.value("PercentChange").toDouble();
q.timestamp = ts;
quotes.append(q);
}
return {true, quotes, "", ts};
}
// ---------- get_history ----------
// GET /openapi/chart/v1/charts?Uic=211&AssetType=Stock&Horizon=1440&Count=365&Mode=From&Time=...
ApiResponse<QVector<BrokerCandle>> SaxoBankBroker::get_history(const BrokerCredentials& creds, const QString& symbol,
const QString& resolution, const QString& from_date,
const QString& to_date) {
int64_t ts = now_ts();
QString uic = extract_uic(symbol);
if (uic.isEmpty())
return {false, std::nullopt, "get_history: Uic required (symbol format EXCHANGE:SYMBOL:UIC[:ASSETTYPE])", ts};
// Optional 4th symbol segment carries AssetType (e.g. FxSpot/CfdOnFutures); defaults to "Stock".
QString asset_type = extract_asset_type(symbol);
int horizon = saxo_horizon(resolution);
// Build time range: Saxo uses Mode=UpTo with Time=end for historical data
// Count derived from date range
QDate from = QDate::fromString(from_date, "yyyy-MM-dd");
QDate to = QDate::fromString(to_date, "yyyy-MM-dd");
if (!from.isValid())
from = QDate::currentDate().addYears(-1);
if (!to.isValid())
to = QDate::currentDate();
int days = from.daysTo(to);
int desired_count = 500; // default
if (horizon >= 1440) {
desired_count = days + 1;
} else if (horizon >= 60) {
desired_count = qMin(days * 8, 500); // ~8 bars/day for 1h
} else {
desired_count = days * (390 / qMax(horizon, 1));
}
desired_count = qMax(1, desired_count);
// Saxo returns at most SAXO_MAX_COUNT samples per request (Mode=UpTo ends at Time, going
// backward). The first-page count preserves the historical single-request behavior.
static constexpr int SAXO_MAX_COUNT = 1200;
static constexpr int SAXO_MAX_PAGES = 30; // safety cap on backward paging iterations
// Fx*/Cfd* instruments report Ask/Bid OHLC (use mid); Stock/Etf/Bond/Future report plain
// OHLC + Volume. Decide off the AssetType, falling back to the open==0.0 heuristic for "Stock".
const bool ask_bid_asset =
asset_type.startsWith("Fx", Qt::CaseInsensitive) || asset_type.startsWith("Cfd", Qt::CaseInsensitive);
auto& http = BrokerHttp::instance();
// Single-request fetch+parse parameterized by Time (Mode=UpTo) and Count. Reuses the existing
// URL build and the asset-type-aware OHLC parser. ok=false signals a transport/parse failure.
struct PageResult {
bool ok = false;
QString error;
QVector<BrokerCandle> candles;
};
auto fetch_page = [&](const QString& time_str, int page_count) -> PageResult {
PageResult page;
QString url = QString("%1/chart/v1/charts?Uic=%2&AssetType=%3&Horizon=%4&Count=%5"
"&Mode=UpTo&Time=%6")
.arg(saxo_base_url(creds), uic, QString(QUrl::toPercentEncoding(asset_type)),
QString::number(horizon), QString::number(page_count),
QString(QUrl::toPercentEncoding(time_str)));
auto resp = http.get(url, auth_headers(creds));
if (!resp.success) {
page.error = checked_error(resp, "get_history failed");
return page;
}
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject()) {
page.error = "get_history: invalid response";
return page;
}
QJsonArray arr = doc.object().value("Data").toArray();
page.candles.reserve(arr.size());
for (const QJsonValue& v : arr) {
QJsonObject o = v.toObject();
// Time is ISO8601 string: "2024-01-15T00:00:00.000000Z"
QDateTime dt = QDateTime::fromString(o.value("Time").toString(), Qt::ISODate);
BrokerCandle c;
c.timestamp = dt.isValid() ? dt.toMSecsSinceEpoch() : 0LL;
// Stocks/Etf/Bond/Future use Open/High/Low/Close/Volume directly
c.open = o.value("Open").toDouble();
c.high = o.value("High").toDouble();
c.low = o.value("Low").toDouble();
c.close = o.value("Close").toDouble();
c.volume = static_cast<int64_t>(o.value("Volume").toDouble());
// Fx*/Cfd* (ask/bid split) — use mid. Fallback heuristic: plain Open absent (==0.0).
if (ask_bid_asset || c.open == 0.0) {
c.open = (o.value("OpenAsk").toDouble() + o.value("OpenBid").toDouble()) / 2.0;
c.high = (o.value("HighAsk").toDouble() + o.value("HighBid").toDouble()) / 2.0;
c.low = (o.value("LowAsk").toDouble() + o.value("LowBid").toDouble()) / 2.0;
c.close = (o.value("CloseAsk").toDouble() + o.value("CloseBid").toDouble()) / 2.0;
}
page.candles.append(c);
}
page.ok = true;
return page;
};
const QString to_time_str = QDateTime(to, QTime(23, 59, 59), QTimeZone::UTC).toString(Qt::ISODate);
// Single-request path (count fits in one page): identical to the historical behavior.
if (desired_count <= SAXO_MAX_COUNT) {
PageResult page = fetch_page(to_time_str, desired_count);
if (!page.ok)
return {false, std::nullopt, page.error, ts};
return {true, page.candles, "", ts};
}
// Backward paging: repeatedly request SAXO_MAX_COUNT samples ending at Time, walking Time back
// to (oldest returned sample - 1s) until we reach from_date, get a short/empty page, or hit
// the safety cap. First-page failure returns an error; later-page failure stops and returns
// what was collected so far.
const int64_t from_ms = QDateTime(from, QTime(0, 0, 0), QTimeZone::UTC).toMSecsSinceEpoch();
QVector<BrokerCandle> candles;
QString time_str = to_time_str;
for (int iter = 0; iter < SAXO_MAX_PAGES; ++iter) {
PageResult page = fetch_page(time_str, SAXO_MAX_COUNT);
if (!page.ok) {
if (iter == 0)
return {false, std::nullopt, page.error, ts};
break; // later-page failure: stop and return collected
}
if (page.candles.isEmpty())
break;
candles += page.candles;
// Determine the oldest sample time in this page (Saxo returns ascending, but don't assume).
int64_t oldest_ms = page.candles.first().timestamp;
for (const BrokerCandle& c : page.candles)
if (c.timestamp > 0 && c.timestamp < oldest_ms)
oldest_ms = c.timestamp;
// Reached or passed the start of the requested range, or got a short page (no more data).
if (oldest_ms <= from_ms || page.candles.size() < SAXO_MAX_COUNT)
break;
// Next page ends just before the oldest sample we already have.
QDateTime next = QDateTime::fromMSecsSinceEpoch(oldest_ms - 1000, QTimeZone::UTC);
time_str = next.toString(Qt::ISODate);
}
// Merge: sort ascending by time, dedupe by timestamp, drop samples older than from_date.
std::sort(candles.begin(), candles.end(),
[](const BrokerCandle& a, const BrokerCandle& b) { return a.timestamp < b.timestamp; });
QVector<BrokerCandle> merged;
merged.reserve(candles.size());
int64_t last_ts = std::numeric_limits<int64_t>::min();
for (const BrokerCandle& c : candles) {
if (c.timestamp < from_ms)
continue;
if (c.timestamp == last_ts)
continue; // dedupe overlapping page boundaries
merged.append(c);
last_ts = c.timestamp;
}
return {true, merged, "", ts};
}
} // namespace fincept::trading