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.

general updates and bug fixes

tilakpatel2293ab2927f91d
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index 92415757d..bd5496948 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -274,6 +274,55 @@ jobs:
fi
echo "Binary verified: $BINARY ($(du -sh "$BINARY" | cut -f1))"
+ # ---- Run headless self-tests ----
+ # Exercise each of the freshly built binary's --selftest-* checks under Qt's
+ # offscreen platform (no display / GPU needed). A non-zero exit fails the
+ # job. Runs the build-tree binary (not the packaged AppImage / .app) so it
+ # needs no FUSE mount or codesigning. Skipped on cross-compiled targets
+ # (Windows arm64, macOS x64) whose binaries can't execute on the host
+ # runner's architecture. timeout-minutes bounds any unexpected hang.
+ - name: Run self-tests (headless)
+ if: "!(matrix.platform == 'Windows' && matrix.arch == 'arm64') && !(matrix.platform == 'macOS' && matrix.arch == 'x64')"
+ shell: bash
+ working-directory: fincept-qt
+ timeout-minutes: 10
+ env:
+ QT_QPA_PLATFORM: offscreen
+ run: |
+ set -euo pipefail
+ if [ "${{ runner.os }}" == "Windows" ]; then
+ BINARY="build/Release/${{ matrix.exe }}"
+ elif [ "${{ runner.os }}" == "macOS" ]; then
+ if [ -f "build/${{ matrix.exe }}" ]; then
+ BINARY="build/${{ matrix.exe }}"
+ elif [ -f "build/${{ matrix.exe }}.app/Contents/MacOS/${{ matrix.exe }}" ]; then
+ BINARY="build/${{ matrix.exe }}.app/Contents/MacOS/${{ matrix.exe }}"
+ else
+ BINARY="build/${{ matrix.exe }}"
+ fi
+ else
+ BINARY="build/${{ matrix.exe }}"
+ fi
+ # No umbrella --selftest exists; run each registered self-test in its
+ # own process (shared DB/state would cross-contaminate one process).
+ for f in \
+ --selftest-tools \
+ --selftest-feeds \
+ --selftest-dock-layout \
+ --selftest-fno-algo \
+ --selftest-universe-scan \
+ --selftest-paper \
+ --selftest-portfolio-monitor \
+ --selftest-portfolio-replication \
+ --selftest-arena; do
+ echo "::group::self-test $f"
+ # --profile ci isolates each run in a fresh, migrated DB so a
+ # cached/drifted default profile can't cause false failures.
+ echo "Running: $BINARY --profile ci $f (QT_QPA_PLATFORM=$QT_QPA_PLATFORM)"
+ "$BINARY" --profile ci "$f"
+ echo "::endgroup::"
+ done
+
# ---- Package: Windows (windeployqt + manual DLL sweep) ----
- name: Package (Windows)
if: runner.os == 'Windows'
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 3888e4dda..f168a2422 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1089,7 +1089,6 @@ set(TRADING_SOURCES
src/trading/ActionCenter.cpp
src/trading/OptionsStrategyBuilder.cpp
src/trading/StrategyPortfolio.cpp
- src/trading/WebhookListener.cpp
src/trading/OrderValidator.cpp
src/trading/LatencyTracker.cpp
src/trading/TradingNotificationBridge.cpp
@@ -2690,7 +2689,6 @@ set_source_files_properties(
src/trading/ActionCenter.cpp
src/trading/StrategyPortfolio.cpp
src/trading/OptionsStrategyBuilder.cpp
- src/trading/WebhookListener.cpp
# Phase 3 storage/core — file-scope kLog / anonymous-namespace helpers
src/storage/HistoricalDataStore.cpp
src/core/HealthMonitor.cpp
diff --git a/fincept-qt/scripts/exchange/exchange_daemon.py b/fincept-qt/scripts/exchange/exchange_daemon.py
index 4fe3eee6e..0261e9b9f 100644
--- a/fincept-qt/scripts/exchange/exchange_daemon.py
+++ b/fincept-qt/scripts/exchange/exchange_daemon.py
@@ -329,10 +329,50 @@ def _handle_fetch_balance(req_id, exchange_id, args):
_respond(req_id, True, {"balances": non_zero})
+def _resolve_market_symbol(ex, symbol, exchange_id):
+ """Map the app's display symbol to a valid ccxt market symbol for this exchange.
+
+ Most venues use the same unified symbol the app sends, so an exact market match
+ is returned unchanged (zero behaviour change for exchanges that already work).
+ Only when there is no exact market — e.g. Hyperliquid, where the app sends
+ "BTC/USDT" but the tradable market is the perp "BTC/USDC:USDC" — do we resolve by
+ base currency, preferring the exchange's default market type. If nothing matches
+ we return the original symbol so ccxt raises a clear BadSymbol (now surfaced to
+ the user instead of being silently swallowed).
+ """
+ markets = getattr(ex, "markets", None) or {}
+ if symbol in markets:
+ return symbol
+ base = symbol.split("/")[0].split(":")[0].strip().upper()
+ if not base:
+ return symbol
+ want_swap = get_default_type(exchange_id) in ("swap", "future")
+ candidates = [
+ m for m in markets.values()
+ if (m.get("base") or "").upper() == base and m.get("active", True)
+ ]
+ if not candidates:
+ return symbol
+ # Prefer markets whose contract type matches the exchange default (swap for a
+ # perps DEX, spot otherwise), then linear (stablecoin-settled) over inverse.
+ candidates.sort(
+ key=lambda m: (bool(m.get("swap")) == want_swap, bool(m.get("linear", True))),
+ reverse=True,
+ )
+ return candidates[0].get("symbol", symbol)
+
+
def _handle_place_order(req_id, exchange_id, args):
ex = _get_exchange(exchange_id, need_auth=True)
_ensure_markets(ex, exchange_id)
+ symbol = _resolve_market_symbol(ex, args["symbol"], exchange_id)
+ if symbol != args["symbol"]:
+ sys.stderr.write(
+ f"[exchange_daemon] order symbol {args['symbol']} -> {symbol} ({exchange_id})\n"
+ )
+ sys.stderr.flush()
+
otype = args["type"]
price = args.get("price")
params = {}
@@ -360,7 +400,7 @@ def _handle_place_order(req_id, exchange_id, args):
params["takeProfit"] = {"triggerPrice": args["tp"]}
order = ex.create_order(
- args["symbol"], otype, args["side"],
+ symbol, otype, args["side"],
args["amount"], price, params,
)
_respond(req_id, True, {
diff --git a/fincept-qt/scripts/prediction_polymarket.py b/fincept-qt/scripts/prediction_polymarket.py
index e5e52718f..c109e1126 100644
--- a/fincept-qt/scripts/prediction_polymarket.py
+++ b/fincept-qt/scripts/prediction_polymarket.py
@@ -181,8 +181,8 @@ def cmd_open_orders(payload: dict) -> None:
"side": o.get("side"),
"order_type": o.get("order_type", "GTC"),
"price": float(o.get("price", 0)),
- "size": float(o.get("original_size", 0)) / 1_000_000.0,
- "filled": float(o.get("size_matched", 0)) / 1_000_000.0,
+ "size": float(o.get("original_size", 0)),
+ "filled": float(o.get("size_matched", 0)),
"status": o.get("status", ""),
"created_ms": int(o.get("created_at", 0)) * 1000,
"expires_ms": int(o.get("expiration") or 0) * 1000,
@@ -206,7 +206,7 @@ def cmd_activity(payload: dict) -> None:
def cmd_place_order(payload: dict) -> None:
- from py_clob_client.clob_types import OrderArgs, OrderType
+ from py_clob_client.clob_types import OrderArgs, OrderType, PartialCreateOrderOptions
client = _build_client(payload)
@@ -227,12 +227,17 @@ def cmd_place_order(payload: dict) -> None:
if payload.get("expiration"):
args.expiration = int(payload["expiration"])
- options = {
- "tick_size": str(payload.get("tick_size", "0.01")),
- "neg_risk": bool(payload.get("neg_risk", False)),
- }
+ # py_clob_client expects a PartialCreateOrderOptions (attribute access), not a
+ # plain dict, and create_and_post_order() accepts no order_type kwarg (it always
+ # posts GTC). Sign with create_order(), then publish with post_order() so the
+ # caller's FOK/FAK/GTD/GTC time-in-force is actually honored.
+ options = PartialCreateOrderOptions(
+ tick_size=str(payload.get("tick_size", "0.01")),
+ neg_risk=bool(payload.get("neg_risk", False)),
+ )
- result = client.create_and_post_order(args, options, order_type=order_type)
+ signed = client.create_order(args, options)
+ result = client.post_order(signed, order_type)
_emit({
"ok": bool(result.get("success", False)),
"order_id": result.get("orderID") or result.get("order_id") or "",
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 8015b0451..4f8153c63 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -686,7 +686,7 @@ int main(int argc, char* argv[]) {
log.set_tag_level(tag, lvl_map.value(level));
}
}
- LOG_INFO("App", "Fincept Terminal v4.1.0 starting...");
+ LOG_INFO("App", "Fincept Terminal v" FINCEPT_VERSION_STRING " starting...");
LOG_INFO("App", QString("TLS backend: %1 (available: %2)")
.arg(QSslSocket::activeBackend(),
QSslSocket::availableBackends().join(", ")));
diff --git a/fincept-qt/src/mcp/McpClient.cpp b/fincept-qt/src/mcp/McpClient.cpp
index 3ce42052d..938a4bde2 100644
--- a/fincept-qt/src/mcp/McpClient.cpp
+++ b/fincept-qt/src/mcp/McpClient.cpp
@@ -48,8 +48,15 @@ Result<void> McpClient::start() {
connect(
process_, &QProcess::readyReadStandardError, this,
[this]() {
- while (process_ && process_->canReadLine()) {
- const QString line = QString::fromUtf8(process_->readLine()).trimmed();
+ // Read the STDERR channel explicitly. canReadLine()/readLine() operate on
+ // the *current* read channel (stdout by default), so the old code drained
+ // stdout — dropping server error logs and, worse, stealing buffered
+ // JSON-RPC response lines (which then hung the request for the full timeout).
+ if (!process_)
+ return;
+ const QByteArray chunk = process_->readAllStandardError();
+ for (const QByteArray& raw : chunk.split('\n')) {
+ const QString line = QString::fromUtf8(raw).trimmed();
if (!line.isEmpty())
append_log("[stderr] " + line);
}
@@ -168,13 +175,36 @@ Result<QJsonObject> McpClient::initialize() {
QJsonObject client_info;
client_info["name"] = "FinceptTerminal";
- client_info["version"] = "4.1.0";
+ client_info["version"] = FINCEPT_VERSION_STRING;
params["clientInfo"] = client_info;
QJsonObject capabilities;
params["capabilities"] = capabilities;
- return send_request("initialize", params, 120000); // 120s for slow servers
+ auto result = send_request("initialize", params, 120000); // 120s for slow servers
+ if (result.is_ok()) {
+ // Per the MCP spec the client MUST send an `initialized` notification after the
+ // initialize response. Spec-compliant servers (e.g. the official Python SDK)
+ // reject `tools/list` with "Received request before initialization was complete"
+ // and expose zero tools until they receive it.
+ send_notification("notifications/initialized", {});
+ }
+ return result;
+}
+
+void McpClient::send_notification(const QString& method, const QJsonObject& params) {
+ if (!is_running())
+ return;
+ // JSON-RPC 2.0 notification: same frame as a request but with NO "id" and no reply.
+ QJsonObject note;
+ note["jsonrpc"] = "2.0";
+ note["method"] = method;
+ if (!params.isEmpty())
+ note["params"] = params;
+ const QByteArray line = QJsonDocument(note).toJson(QJsonDocument::Compact) + "\n";
+ QMetaObject::invokeMethod(
+ process_, [this, line]() { if (process_) process_->write(line); }, Qt::QueuedConnection);
+ LOG_INFO(TAG, "RPC → " + method + " (notification)");
}
Result<std::vector<ExternalTool>> McpClient::list_tools() {
diff --git a/fincept-qt/src/mcp/McpClient.h b/fincept-qt/src/mcp/McpClient.h
index 1256ef36e..322826323 100644
--- a/fincept-qt/src/mcp/McpClient.h
+++ b/fincept-qt/src/mcp/McpClient.h
@@ -76,6 +76,8 @@ class McpClient : public QObject {
int next_id_ = 1;
Result<QJsonObject> send_request(const QString& method, const QJsonObject& params, int timeout_ms = 30000);
+ // Fire-and-forget JSON-RPC notification (no id, no response) — e.g. notifications/initialized.
+ void send_notification(const QString& method, const QJsonObject& params = {});
void handle_line(const QByteArray& line);
void append_log(const QString& line);
void cleanup_process(); // deletes process_ safely (call only after thread is stopped/not started)
diff --git a/fincept-qt/src/mcp/McpMarketplace.h b/fincept-qt/src/mcp/McpMarketplace.h
index ee311047f..cd26413b6 100644
--- a/fincept-qt/src/mcp/McpMarketplace.h
+++ b/fincept-qt/src/mcp/McpMarketplace.h
@@ -50,9 +50,9 @@ inline const QList<MarketplaceEntry>& marketplace_catalog() {
{},
"database"},
{"PostgreSQL",
- "Query and explore a PostgreSQL database schema and data.",
+ "Query and explore a PostgreSQL database schema and data (read-only restricted mode).",
"uvx",
- {"postgres-mcp", "--access-mode=unrestricted"},
+ {"postgres-mcp", "--access-mode=restricted"},
{"DATABASE_URI"},
{"postgresql://user:password@localhost:5432/mydb"},
"database"},
diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cpp
index 74b0942d7..a84178879 100644
--- a/fincept-qt/src/mcp/McpProvider.cpp
+++ b/fincept-qt/src/mcp/McpProvider.cpp
@@ -224,52 +224,16 @@ QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJso
return fail_now("Tool '" + resolved + "' has no handler");
}
- // Phase 6.3: authorization gate. We don't import AuthManager here to
- // avoid pulling auth headers into McpTypes.h consumers — instead we
- // expose a hook that the app installs at startup.
- //
- // No-checker semantics:
- // • AuthLevel <= Authenticated and is_destructive flag → log + pass
- // (the flag is a hint for the Phase 6.12 modal; not a hard gate
- // until that UI lands)
- // • AuthLevel >= Verified → fail closed (genuine privilege escalation
- // that must not happen unauthenticated)
- if (auth_required != AuthLevel::None || is_destructive) {
- AuthChecker checker;
- {
- QMutexLocker lock(&mutex_);
- checker = auth_checker_;
- }
- if (checker) {
- if (!checker(auth_required, is_destructive)) {
- LOG_WARN(TAG, QString("Tool '%1' blocked: auth_required=%2 is_destructive=%3")
- .arg(name, auth_level_str(auth_required))
- .arg(is_destructive ? "true" : "false"));
- QPromise<ToolResult> p;
- p.start();
- p.addResult(ToolResult::fail(QString("Tool '%1' requires %2 auth")
- .arg(name, auth_level_str(auth_required))));
- p.finish();
- return p.future();
- }
- } else if (auth_required >= AuthLevel::Verified) {
- // Fail-closed: Verified/Subscribed/ExplicitConfirm cannot be
- // safely evaluated without a checker. Refuse the call.
- LOG_WARN(TAG, QString("Tool '%1' blocked: no AuthChecker registered (required=%2)")
- .arg(name, auth_level_str(auth_required)));
- QPromise<ToolResult> p;
- p.start();
- p.addResult(ToolResult::fail("Tool requires user confirmation but no authorisation hook is installed"));
- p.finish();
- return p.future();
- } else if (is_destructive) {
- // Advisory log only — the modal that prompts on this flag is
- // Phase 6.12 work. Tools tagged Authenticated+destructive still
- // run today; once the modal ships, install the checker and the
- // upper branch starts gating them.
- LOG_INFO(TAG, QString("Tool '%1' is destructive (flag is advisory; install McpProvider::set_auth_checker to gate)")
- .arg(name));
- }
+ // Phase 6.3: authorization gate — shared with McpService's external-tool
+ // dispatch via check_authorization() so internal and external calls apply
+ // identical auth/destructive rules. See that method for the no-checker
+ // semantics.
+ if (auto denied = check_authorization(name, auth_required, is_destructive)) {
+ QPromise<ToolResult> p;
+ p.start();
+ p.addResult(*denied);
+ p.finish();
+ return p.future();
}
// Phase 3: validate + inject defaults before invoking the handler.
@@ -469,6 +433,51 @@ void McpProvider::set_auth_checker(AuthChecker checker) {
auth_checker_ = std::move(checker);
}
+std::optional<ToolResult> McpProvider::check_authorization(const QString& name, AuthLevel auth_required,
+ bool is_destructive) const {
+ // We don't import AuthManager here to avoid pulling auth headers into
+ // McpTypes.h consumers — instead we expose a hook that the app installs
+ // at startup.
+ //
+ // No-checker semantics:
+ // • AuthLevel <= Authenticated and is_destructive flag → log + pass
+ // (the flag is a hint for the Phase 6.12 modal; not a hard gate
+ // until that UI lands)
+ // • AuthLevel >= Verified → fail closed (genuine privilege escalation
+ // that must not happen unauthenticated)
+ if (auth_required == AuthLevel::None && !is_destructive)
+ return std::nullopt;
+
+ AuthChecker checker;
+ {
+ QMutexLocker lock(&mutex_);
+ checker = auth_checker_;
+ }
+ if (checker) {
+ if (!checker(auth_required, is_destructive)) {
+ LOG_WARN(TAG, QString("Tool '%1' blocked: auth_required=%2 is_destructive=%3")
+ .arg(name, auth_level_str(auth_required))
+ .arg(is_destructive ? "true" : "false"));
+ return ToolResult::fail(QString("Tool '%1' requires %2 auth")
+ .arg(name, auth_level_str(auth_required)));
+ }
+ } else if (auth_required >= AuthLevel::Verified) {
+ // Fail-closed: Verified/Subscribed/ExplicitConfirm cannot be
+ // safely evaluated without a checker. Refuse the call.
+ LOG_WARN(TAG, QString("Tool '%1' blocked: no AuthChecker registered (required=%2)")
+ .arg(name, auth_level_str(auth_required)));
+ return ToolResult::fail("Tool requires user confirmation but no authorisation hook is installed");
+ } else if (is_destructive) {
+ // Advisory log only — the modal that prompts on this flag is
+ // Phase 6.12 work. Tools tagged Authenticated+destructive still
+ // run today; once the modal ships, install the checker and the
+ // upper branch starts gating them.
+ LOG_INFO(TAG, QString("Tool '%1' is destructive (flag is advisory; install McpProvider::set_auth_checker to gate)")
+ .arg(name));
+ }
+ return std::nullopt;
+}
+
// ============================================================================
// Generation Counter
// ============================================================================
diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.h
index c5ff5b46d..efb4e436a 100644
--- a/fincept-qt/src/mcp/McpProvider.h
+++ b/fincept-qt/src/mcp/McpProvider.h
@@ -103,6 +103,16 @@ class McpProvider {
using AuthChecker = std::function<bool(AuthLevel required, bool is_destructive)>;
void set_auth_checker(AuthChecker checker);
+ /// Run the Phase 6.3 authorization gate for one call WITHOUT executing
+ /// anything. Returns std::nullopt when the call may proceed, or a
+ /// ready-to-return failure ToolResult when blocked. Shared by
+ /// call_tool_async (internal tools) and McpService::execute_tool
+ /// (external tools, gated destructive-by-default) so both paths apply
+ /// identical auth/destructive-confirmation rules. `name` is used for
+ /// logging and error messages only.
+ std::optional<ToolResult> check_authorization(const QString& name, AuthLevel auth_required,
+ bool is_destructive) const;
+
// ── LLM Integration ────────────────────────────────────────────────────
/// Format all enabled tools for OpenAI function calling
diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cpp
index 412c8cc47..e368bc95e 100644
--- a/fincept-qt/src/mcp/McpService.cpp
+++ b/fincept-qt/src/mcp/McpService.cpp
@@ -6,7 +6,9 @@
#include "core/logging/Logger.h"
#include "mcp/McpManager.h"
#include "mcp/McpProvider.h"
+#include "mcp/ToolRetriever.h"
+#include <QCoreApplication>
#include <QJsonDocument>
#include <QPromise>
#include <QRegularExpression>
@@ -36,6 +38,14 @@ void McpService::initialize() {
QObject::connect(&McpManager::instance(), &McpManager::servers_changed, [this]() {
QMutexLocker lock(&mutex_);
cache_time_ = QDateTime(); // force refresh on next get_all_tools()
+ // The Tool RAG index covers external tools too (ToolRetriever builds
+ // over get_all_tools()), so it must follow this cache. Queued, never
+ // inline: servers_changed can fire while McpManager's mutex is held
+ // (error paths), and the retriever rebuild takes ToolRetriever →
+ // McpService → McpManager locks — invalidating inline here would
+ // invert that order.
+ QMetaObject::invokeMethod(qApp, []() { ToolRetriever::instance().invalidate(); },
+ Qt::QueuedConnection);
LOG_INFO(TAG, "Tool cache invalidated — external servers changed");
});
@@ -371,7 +381,16 @@ ToolResult McpService::execute_tool(const QString& server_id, const QString& too
if (server_id == INTERNAL_SERVER_ID)
return McpProvider::instance().call_tool(tool_name, args);
- // Route to external server
+ // Route to external server — through the same Phase 6.3 auth/destructive
+ // gate internal tools get inside call_tool_async (previously this path
+ // bypassed it entirely). The MCP wire carries no auth/destructiveness
+ // metadata, so external tools are gated destructive-by-default: the
+ // installed checker must approve them exactly like a destructive internal
+ // tool (agent-originated calls are denied unless the agent opts in).
+ if (auto denied = McpProvider::instance().check_authorization(
+ server_id + "__" + tool_name, AuthLevel::None, /*is_destructive=*/true))
+ return *denied;
+
auto result = McpManager::instance().call_external_tool(server_id, tool_name, args);
if (result.is_err())
return ToolResult::fail(QString::fromStdString(result.error()));
@@ -483,11 +502,12 @@ void McpService::refresh_cache() {
auto external = McpManager::instance().get_all_external_tools();
for (auto& ext : external) {
// External tools default category="" (their server doesn't tag) and
- // is_destructive=false (we have no signal for it from the wire — the
- // MCP spec doesn't carry it). Treat external tools as non-destructive
- // until they tell us otherwise.
+ // is_destructive=true — the MCP spec carries no destructiveness
+ // signal on the wire, so treat external tools as destructive-by-
+ // default. Keeps tool_list / Tool RAG surfacing honest and matches
+ // execute_tool(), which gates them like destructive internal tools.
cached_tools_.push_back({ext.server_id, ext.server_name, ext.name, ext.description,
- ext.input_schema, false, QString{}, false});
+ ext.input_schema, false, QString{}, true});
}
// Invalidate filter-derived caches — they were computed against the
diff --git a/fincept-qt/src/mcp/ToolRetriever.cpp b/fincept-qt/src/mcp/ToolRetriever.cpp
index 4291cdfcd..d4d05ba75 100644
--- a/fincept-qt/src/mcp/ToolRetriever.cpp
+++ b/fincept-qt/src/mcp/ToolRetriever.cpp
@@ -4,6 +4,7 @@
#include "core/logging/Logger.h"
#include "mcp/McpProvider.h"
+#include "mcp/McpService.h"
#include <QJsonObject>
#include <QRegularExpression>
@@ -295,10 +296,14 @@ void ToolRetriever::rebuild_index_locked() {
vocabulary_.clear();
avg_doc_length_ = 0.0;
- // list_all_tools() returns disabled tools too — we want them in the
- // index so we can mark them "disabled" if needed, but for v1 we exclude
- // them at search time so they never surface to the LLM.
- const auto tool_list = McpProvider::instance().list_all_tools();
+ // Index the unified catalog — internal registry tools PLUS tools
+ // discovered from running external MCP servers (McpService merges the
+ // two, cached 5 s). Building only over McpProvider::list_all_tools()
+ // left external tools invisible to Tool RAG's tool_list. Disabled
+ // internal tools are excluded upstream by list_tools(); the
+ // is_tool_enabled() check at search time still guards against tools
+ // disabled after the index was built (external names always pass it).
+ const auto tool_list = McpService::instance().get_all_tools();
docs_.reserve(tool_list.size());
for (const auto& t : tool_list) {
diff --git a/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp b/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp
index 0296454c1..83b59b433 100644
--- a/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp
+++ b/fincept-qt/src/screens/agent_config/AgenticTasksPanel.cpp
@@ -785,14 +785,19 @@ void AgenticTasksPanel::on_cancel_clicked() {
void AgenticTasksPanel::on_delete_clicked() {
if (selected_task_id_.isEmpty()) return;
- // Use existing delete_task action via run_python_stdin. There's no
- // dedicated wrapper on AgentService — Phase 2 may add one. For now,
- // request a list refresh; the delete itself happens via the existing
- // PLANNER tab tooling. To keep Phase 1 self-contained we still wire it
- // here by routing through the cancel + list pattern.
- services::AgentService::instance().cancel_task(selected_task_id_);
+ auto& svc = services::AgentService::instance();
+ const QString id = selected_task_id_;
+ // Cancel first (signals a running subprocess to stop), then actually remove the
+ // record. Previously this only called cancel_task, so the row lingered in a
+ // "cancelled" state — a scheduled/recurring task kept being re-fired and there was
+ // no way to truly delete it (runaway token/credit cost). delete_task removes it.
+ svc.cancel_task(id);
+ svc.delete_task(id);
selected_task_id_.clear();
refresh_list();
+ // delete_task is async — refresh once more after it has been applied so the row
+ // actually disappears rather than reappearing from the pre-delete snapshot.
+ QTimer::singleShot(500, this, [this]() { refresh_list(); });
}
QString AgenticTasksPanel::status_color_for(const QString& status) {
diff --git a/fincept-qt/src/screens/akshare/AkShareScreen.cpp b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
index c8222c5cf..1610dcb97 100644
--- a/fincept-qt/src/screens/akshare/AkShareScreen.cpp
+++ b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
@@ -391,6 +391,10 @@ QWidget* AkShareScreen::create_params_panel() {
param_period_ = new QComboBox;
param_period_->addItems({"daily", "weekly", "monthly"});
param_period_->setFixedWidth(90);
+ // Not wired: AKShare endpoints take `period` positionally per-function, so a
+ // generic pass-through is unsafe. Disable rather than pretend it filters.
+ param_period_->setEnabled(false);
+ param_period_->setToolTip(tr("Period is fixed to the endpoint default (not yet configurable)"));
// Execute button
exec_btn_ = new QPushButton(tr("EXECUTE"));
diff --git a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
index 14e741ff8..7ed93cd3c 100644
--- a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
+++ b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
@@ -481,7 +481,7 @@ void DeploymentDashboard::build_ui() {
eq_vl->addStretch();
- eq_hint_ = new QLabel(tr("Select a deployment to view curve"), equity_placeholder_);
+ eq_hint_ = new QLabel(tr("Equity curve — not yet available"), equity_placeholder_);
eq_hint_->setAlignment(Qt::AlignCenter);
eq_hint_->setStyleSheet(
QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
@@ -749,7 +749,7 @@ void DeploymentDashboard::retranslateUi() {
if (total_trades_caption_) total_trades_caption_->setText(tr("TOTAL TRADES"));
if (avg_win_rate_caption_) avg_win_rate_caption_->setText(tr("AVG WIN RATE"));
if (eq_title_) eq_title_->setText(tr("EQUITY CURVE"));
- if (eq_hint_) eq_hint_->setText(tr("Select a deployment to view curve"));
+ if (eq_hint_) eq_hint_->setText(tr("Equity curve — not yet available"));
if (refresh_btn_) refresh_btn_->setText(tr("REFRESH"));
if (stop_all_btn_) stop_all_btn_->setText(tr("STOP ALL"));
if (dep_title_) dep_title_->setText(tr("DEPLOYMENTS"));
diff --git a/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp b/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp
index e266ccce4..bc544ceac 100644
--- a/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp
+++ b/fincept-qt/src/screens/alpha_arena/NewCompetitionWizard.cpp
@@ -333,7 +333,9 @@ void NewCompetitionWizard::on_next_or_create() {
bool NewCompetitionWizard::engage_live_gates() {
if (!fincept::trading::hyperliquid::HyperliquidSigner::is_wired()) {
QMessageBox::critical(this, windowTitle(),
- tr("Live mode unavailable: the Hyperliquid signer failed to initialise in this build."));
+ tr("Live trading on Hyperliquid is not yet available in this build — paper mode is "
+ "fully supported. (Live mode is disabled so no real wallet key is stored for a "
+ "path that cannot execute a trade.)"));
return false;
}
#ifndef FINCEPT_UNSAFE_DISABLE_GEOFENCE
diff --git a/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp b/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp
index c55bfc2c5..da2bb8304 100644
--- a/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp
+++ b/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp
@@ -236,14 +236,18 @@ QWidget* AsiaMarketsScreen::create_header() {
hl->addLayout(title_col);
hl->addStretch(1);
- // Region buttons
+ // Region buttons — region filtering is not yet wired to the query layer.
+ // AKShare endpoints are inherently region-specific (the endpoint you pick
+ // already determines CN A/B, HK or US) and the connector scripts take no
+ // region argument, so these are shown disabled until real filtering exists.
const QStringList region_labels = {"CN A", "CN B", "HK", "US"};
for (int i = 0; i < regions_.size(); ++i) {
auto* btn = new QPushButton(region_labels[i]);
btn->setObjectName("asiaRegionBtn");
- btn->setCursor(Qt::PointingHandCursor);
+ btn->setEnabled(false);
+ btn->setToolTip(tr("Region filtering is not yet functional — endpoints are "
+ "region-specific; choose the relevant endpoint from the list."));
btn->setProperty("active", i == 0);
- connect(btn, &QPushButton::clicked, this, [this, i]() { on_region_changed(i); });
hl->addWidget(btn);
region_btns_.append(btn);
}
diff --git a/fincept-qt/src/screens/auth/LockScreen.cpp b/fincept-qt/src/screens/auth/LockScreen.cpp
index 8466b0a92..13ccf1358 100644
--- a/fincept-qt/src/screens/auth/LockScreen.cpp
+++ b/fincept-qt/src/screens/auth/LockScreen.cpp
@@ -397,6 +397,19 @@ void LockScreen::build_unlock_page() {
connect(unlock_btn_, &QPushButton::clicked, this, &LockScreen::on_unlock_submit);
vl->addWidget(unlock_btn_);
+ // "Forgot PIN?" escape — a forgotten PIN is recoverable by signing in again
+ // (this clears the PIN). Without this link the only path was to fail the unlock
+ // kMaxAttempts times through escalating lockouts, which is minutes of dead-end.
+ auto* forgot_link = new QPushButton(tr("Forgot PIN? Sign in again"));
+ forgot_link->setCursor(Qt::PointingHandCursor);
+ forgot_link->setStyleSheet(QString("QPushButton{color:%1; background:transparent; border:none;"
+ "font-size:12px; text-decoration:underline;"
+ "font-family:'Consolas','Courier New',monospace;}"
+ "QPushButton:hover{color:%2;}")
+ .arg(ui::colors::TEXT_DIM(), ui::colors::AMBER()));
+ connect(forgot_link, &QPushButton::clicked, this, [this]() { emit reauth_requested(); });
+ vl->addWidget(forgot_link, 0, Qt::AlignHCenter);
+
vl->addStretch();
connect(unlock_pin_input_, &QLineEdit::returnPressed, this, &LockScreen::on_unlock_submit);
diff --git a/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp
index ddd91c075..f417a7edd 100644
--- a/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/FeeDiscountPanel.cpp
@@ -146,7 +146,8 @@ void FeeDiscountPanel::build_ui() {
hint_ = new QLabel(
tr("Hold ≥ %1 $FNCPT to qualify for the discount on premium screens, "
- "AI reports, and deep backtests.")
+ "AI reports, and deep backtests. Projected only — the discount is "
+ "not yet applied automatically at checkout.")
.arg(QLocale::system().toString(
static_cast<double>(
fincept::billing::FeeDiscountConfig::kThresholdRaw)
@@ -292,7 +293,7 @@ void FeeDiscountPanel::update_view() {
const bool eligible = have_discount_ ? latest_.eligible
: (fncpt_held_ >= threshold);
if (eligible) {
- heading_status_->setText(tr("● %1% OFF ACTIVE").arg(discount_pct));
+ heading_status_->setText(tr("● %1% OFF ELIGIBLE").arg(discount_pct));
heading_status_->setObjectName(QStringLiteral("feeDiscountHeadStatusOk"));
const double save = FeeDiscountConfig::kReferencePriceUsd * discount_pct / 100.0;
const double net = FeeDiscountConfig::kReferencePriceUsd - save;
@@ -346,7 +347,8 @@ void FeeDiscountPanel::retranslateUi() {
if (hint_)
hint_->setText(
tr("Hold ≥ %1 $FNCPT to qualify for the discount on premium screens, "
- "AI reports, and deep backtests.")
+ "AI reports, and deep backtests. Projected only — the discount is "
+ "not yet applied automatically at checkout.")
.arg(QLocale::system().toString(
static_cast<double>(FeeDiscountConfig::kThresholdRaw)
/ std::pow(10.0, FeeDiscountConfig::kThresholdDecimals),
diff --git a/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp
index 8cbb6a607..64f3854b7 100644
--- a/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/LockPanel.cpp
@@ -545,13 +545,18 @@ void LockPanel::recompute_preview() {
.arg(fincept::billing::TierConfig::label_for(tier_after)));
}
- // Submit gating
- bool can_submit = !busy_
+ // Submit gating — the LOCK button must stay disabled until the on-chain
+ // program is actually deployed, so a demo-looking screen can never build a
+ // real staking transaction.
+ const bool program_ready =
+ fincept::wallet::StakingService::instance().program_is_configured();
+ bool can_submit = program_ready
+ && !busy_
&& !current_pubkey_.isEmpty()
&& amount_ui > 0.0
&& amount_ui <= fncpt_balance_ui_;
lock_button_->setEnabled(can_submit);
- if (!fincept::wallet::StakingService::instance().program_is_configured()) {
+ if (!program_ready) {
status_label_->setText(
tr("DEMO — fincept_lock not deployed; configure SecureStorage "
"fincept.lock_program_id to enable real locks."));
diff --git a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp
index d544d52bd..8f20dc2b5 100644
--- a/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp
+++ b/fincept-qt/src/screens/crypto_center/panels/SwapPanel.cpp
@@ -431,7 +431,7 @@ void SwapPanel::showEvent(QShowEvent* e) {
hub.request(current_balance_topic_, /*force=*/true);
}
resubscribe_prices();
- slippage_label_->setText(format_bps(slippage_bps()));
+ slippage_label_->setText(format_bps(slippage_pct() * 100));
route_label_->setText(QStringLiteral("PumpSwap (auto)"));
}
@@ -720,7 +720,7 @@ void SwapPanel::recompute_estimate() {
out_amount_label_->setText(out_text);
route_label_->setText(QStringLiteral("PumpSwap (auto)"));
impact_label_->setText(tr("set by PumpSwap; capped by slippage"));
- slippage_label_->setText(format_bps(slippage_bps()));
+ slippage_label_->setText(format_bps(slippage_pct() * 100));
if (!is_supported_pair()) {
// Show the estimate so the user understands what they're trying to
@@ -895,7 +895,11 @@ void SwapPanel::on_swap_clicked() {
const auto pubkey = current_pubkey_;
const int slip_pct = slippage_pct();
- const int slip_bps_for_display = slippage_bps();
+ // Display the tolerance actually sent and enforced — slippage_pct() rounds
+ // the raw bps up to a whole percent (floor 1, cap 5) and PumpPortal re-clamps
+ // to [1,5]. Showing the raw bps here would advertise a tighter tolerance than
+ // is executed (e.g. 50 bps sends/enforces 1% but would read "0.50%").
+ const int slip_bps_for_display = slip_pct * 100;
// The supported-pair gate above guarantees this is SOL→FNCPT or FNCPT→SOL.
const bool buying_fncpt = is_native_sol(from_mint_) && is_fncpt(to_mint_);
const auto action = buying_fncpt
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
index 22cc66db4..ee7126292 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
@@ -925,6 +925,23 @@ void CryptoBottomPanel::set_live_balance(double balance, double equity, double u
live_balance_label_->setText(QString("$%1").arg(balance, 0, 'f', 2));
live_equity_label_->setText(QString("$%1").arg(equity, 0, 'f', 2));
live_margin_label_->setText(QString("$%1").arg(used_margin, 0, 'f', 2));
+ // Clear any stale error tooltip left over from a prior unavailable state.
+ live_balance_label_->setToolTip(QString());
+ live_equity_label_->setToolTip(QString());
+ live_margin_label_->setToolTip(QString());
+}
+
+void CryptoBottomPanel::set_balance_unavailable(const QString& reason) {
+ if (!live_balance_label_)
+ return;
+ live_balance_label_->setText(tr("UNAVAILABLE"));
+ live_equity_label_->setText(QStringLiteral("—"));
+ live_margin_label_->setText(QStringLiteral("—"));
+ const QString tip = reason.isEmpty() ? tr("Balance unavailable")
+ : tr("Balance unavailable: %1").arg(reason);
+ live_balance_label_->setToolTip(tip);
+ live_equity_label_->setToolTip(tip);
+ live_margin_label_->setToolTip(tip);
}
} // namespace fincept::screens::crypto
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
index a232d6819..4f24a8b77 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
@@ -34,6 +34,11 @@ class CryptoBottomPanel : public QWidget {
void set_live_positions(const QJsonArray& positions);
void set_live_orders(const QJsonArray& orders);
void set_live_balance(double balance, double equity, double used_margin);
+ /// Live balance could not be fetched (bad API key / daemon error). Shows an
+ /// explicit UNAVAILABLE state instead of a misleading $0.00 (which is
+ /// indistinguishable from a genuinely empty account). `reason` goes into a
+ /// tooltip.
+ void set_balance_unavailable(const QString& reason);
void set_mode(bool is_paper);
// New live tabs
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
index 3333231ac..47430f2b9 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
@@ -111,11 +111,21 @@ void CryptoTradingScreen::async_fetch_live_balance() {
[self, result]() {
if (!self)
return;
- double total = result.value("total").toObject().value("USDT").toDouble();
- double free = result.value("free").toObject().value("USDT").toDouble();
- double used = result.value("used").toObject().value("USDT").toDouble();
- self->bottom_panel_->set_live_balance(free, total, used);
- self->order_entry_->set_balance(free);
+ // A daemon/bridge failure (e.g. bad API key) returns an "error"
+ // key or simply omits the balance keys — both would otherwise
+ // decode to 0.0 and render a misleading $0.00 that looks exactly
+ // like a genuinely empty account. Surface an explicit unavailable
+ // state instead, and leave the order-entry balance untouched.
+ if (result.contains("error") || !result.contains("total")) {
+ self->bottom_panel_->set_balance_unavailable(
+ result.value("error").toString(QStringLiteral("no data")));
+ } else {
+ double total = result.value("total").toObject().value("USDT").toDouble();
+ double free = result.value("free").toObject().value("USDT").toDouble();
+ double used = result.value("used").toObject().value("USDT").toDouble();
+ self->bottom_panel_->set_live_balance(free, total, used);
+ self->order_entry_->set_balance(free);
+ }
self->live_inflight_.fetch_sub(1);
},
Qt::QueuedConnection);
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
index 5a6d7d2b9..4902bdf8d 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
@@ -27,6 +27,7 @@
#include <QCompleter>
#include <QDateTime>
+#include <QMessageBox>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonObject>
@@ -232,9 +233,19 @@ void CryptoTradingScreen::on_order_submitted(const QString& side, const QString&
try {
if (trading_mode_ == TradingMode::Paper) {
auto ticker = ExchangeService::instance().get_cached_price(selected_symbol_);
+ // A paper market order fills immediately at the live price. Before the first
+ // tick (cold start / just-switched exchange) there is none — refuse rather than
+ // fill at a bogus $1000, which would corrupt paper cost-basis and P&L.
+ if (order_type == "market" && !(ticker.last > 0)) {
+ QMessageBox::warning(this, tr("Price Unavailable"),
+ tr("Live price for %1 is not available yet. Wait for the first tick, "
+ "or place a limit order.")
+ .arg(selected_symbol_));
+ return;
+ }
std::optional<double> price_opt;
if (order_type == "market")
- price_opt = ticker.last > 0 ? ticker.last : 1000.0;
+ price_opt = ticker.last;
else if (price > 0)
price_opt = price;
@@ -244,8 +255,12 @@ void CryptoTradingScreen::on_order_submitted(const QString& side, const QString&
auto order = pt_place_order(portfolio_id_, selected_symbol_, side, order_type, qty, price_opt, stop_opt);
if (order_type == "market") {
- double fill = ticker.last > 0 ? ticker.last : price_opt.value_or(1000.0);
- pt_fill_order(order.id, fill);
+ pt_fill_order(order.id, ticker.last);
+ // A market order fills immediately, so attach any SL/TP bracket to the
+ // resulting position here. The limit/stop branch does this for resting
+ // orders; skipping it left market entries silently unprotected.
+ if (sl > 0 || tp > 0)
+ OrderMatcher::instance().set_sl_tp(portfolio_id_, selected_symbol_, order.id, sl, tp);
} else {
OrderMatcher::instance().add_order(order);
if (sl > 0 || tp > 0)
@@ -253,43 +268,71 @@ void CryptoTradingScreen::on_order_submitted(const QString& side, const QString&
}
refresh_portfolio();
} else {
+ // A live order is real money with no undo, and single orders previously
+ // had NO confirmation — one click or a held Ctrl+Enter fired real funds.
+ // Gate it behind an explicit confirm (close-all/cancel-all already do).
+ const QString px_txt =
+ order_type == "market" ? tr("market price") : QString::number(price, 'f', 8);
+ const QString confirm_msg = tr("Place a LIVE %1 %2 order with real funds?\n\n%3 qty %4 @ %5")
+ .arg(side.toUpper(), order_type.toUpper(), selected_symbol_)
+ .arg(qty)
+ .arg(px_txt);
+ if (QMessageBox::question(this, tr("Confirm Live Order"), confirm_msg,
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ return;
+
// In-flight guard: place_exchange_order is dispatched to a worker and
// we return to the GUI thread immediately, so the submit button must
// be disabled for the lifetime of the POST — otherwise a double-click
// or held Ctrl+Enter fires a second real exchange order (CR-07).
order_entry_->set_submit_busy(true);
- // Read the reduce-only flag on the UI thread before dispatching.
+ // Snapshot everything the worker needs on the UI thread (symbol / reduce-only
+ // could otherwise be mutated concurrently while the POST is in flight).
const bool reduce_only = order_entry_->reduce_only();
+ const QString sym = selected_symbol_;
QPointer<CryptoTradingScreen> self = this;
QPointer<crypto::CryptoOrderEntry> oe = order_entry_;
- (void)QtConcurrent::run([self, oe, side, order_type, qty, price, stop_price, sl, tp, reduce_only]() {
+ (void)QtConcurrent::run([self, oe, sym, side, order_type, qty, price, stop_price, sl, tp, reduce_only]() {
// stop_price drives Stop / Stop-Limit triggers; sl/tp attach native
// bracket legs; reduce_only is honoured on perps. The daemon maps
// these to ccxt unified params (triggerPrice / stopLoss / takeProfit).
- // Re-enable the button on completion regardless of success/throw so
- // the user is never stuck on a permanently disabled SENDING… button.
+ QJsonObject result;
+ QString err;
try {
- if (self) {
- ExchangeService::instance().place_exchange_order(self->selected_symbol_, side, order_type, qty,
- price, stop_price, sl, tp, reduce_only);
- }
+ result = ExchangeService::instance().place_exchange_order(sym, side, order_type, qty, price,
+ stop_price, sl, tp, reduce_only);
} catch (const std::exception& e) {
+ err = QString::fromUtf8(e.what());
LOG_ERROR(TAG, QString("Live order failed: %1").arg(e.what()));
} catch (...) {
+ err = QStringLiteral("unknown error");
LOG_ERROR(TAG, "Live order failed: unknown exception");
}
+ // The daemon reports rejections IN-BAND ({"success":false,"error":…} or a
+ // timeout {"error":…}) — it never throws, so an empty catch does NOT mean
+ // the order filled. A present "error" (or explicit success:false) is a
+ // rejection: surface it instead of leaving it identical to a fill.
+ if (err.isEmpty() && (result.contains("error") || !result.value("success").toBool(true))) {
+ err = result.value("error").toString();
+ if (err.isEmpty())
+ err = QStringLiteral("The exchange rejected the order.");
+ LOG_ERROR(TAG, QString("Live order rejected: %1").arg(err));
+ }
// order_entry_ is a child of the screen, so if self is alive the
// order-entry widget is too. Posting onto self is sufficient.
if (!self)
return;
QMetaObject::invokeMethod(
self,
- [self, oe]() {
+ [self, oe, err]() {
if (oe)
oe->set_submit_busy(false);
- if (self)
- self->refresh_live_data();
+ if (!self)
+ return;
+ if (!err.isEmpty())
+ QMessageBox::warning(self, tr("Order Failed"), tr("Live order failed:\n%1").arg(err));
+ self->refresh_live_data();
},
Qt::QueuedConnection);
});
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp b/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp
index 05b77c0ee..1210a5d07 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.cpp
@@ -521,7 +521,14 @@ void DBnomicsSelectionPanel::add_comparison_slot() {
"border: 1px solid rgba(220,38,38,0.3); font-size: 11px; font-weight: 700; }"
"QPushButton:hover { background: rgba(220,38,38,0.25); }")
.arg(col::NEGATIVE()));
- connect(remove_btn, &QPushButton::clicked, this, [this, slot_idx]() { emit remove_slot_clicked(slot_idx); });
+ // Resolve the slot's index from its live layout position at click time — a
+ // baked-in slot_idx goes stale once an earlier slot is removed and the
+ // remaining widgets shift up.
+ connect(remove_btn, &QPushButton::clicked, this, [this, slot_widget]() {
+ const int idx = slots_layout_->indexOf(slot_widget);
+ if (idx >= 0)
+ emit remove_slot_clicked(idx);
+ });
header_layout->addWidget(remove_btn);
slot_layout->addWidget(header_row);
@@ -536,7 +543,11 @@ void DBnomicsSelectionPanel::add_comparison_slot() {
.arg(col::TEXT_TERTIARY())
.arg(col::BORDER_DIM())
.arg(col::AMBER()));
- connect(add_series_btn, &QPushButton::clicked, this, [this, slot_idx]() { emit add_to_slot_clicked(slot_idx); });
+ connect(add_series_btn, &QPushButton::clicked, this, [this, slot_widget]() {
+ const int idx = slots_layout_->indexOf(slot_widget);
+ if (idx >= 0)
+ emit add_to_slot_clicked(idx);
+ });
slot_layout->addWidget(add_series_btn);
slots_layout_->addWidget(slot_widget);
@@ -558,6 +569,23 @@ void DBnomicsSelectionPanel::remove_comparison_slot(int index) {
}
if (slot_count_ > 0)
--slot_count_;
+
+ // Remaining slot widgets shifted up — renumber their SLOT labels so the
+ // visible numbering stays 1..N and matches their new layout positions.
+ renumber_slots();
+}
+
+void DBnomicsSelectionPanel::renumber_slots() {
+ if (!slots_layout_)
+ return;
+ for (int i = 0; i < slots_layout_->count(); ++i) {
+ QLayoutItem* it = slots_layout_->itemAt(i);
+ QWidget* slot_widget = it ? it->widget() : nullptr;
+ if (!slot_widget)
+ continue;
+ if (auto* lbl = slot_widget->findChild<QLabel*>(QStringLiteral("dbnSlotLabel")))
+ lbl->setText(tr("SLOT %1").arg(i + 1));
+ }
}
void DBnomicsSelectionPanel::clear_slots() {
@@ -792,8 +820,11 @@ void DBnomicsSelectionPanel::update_slot_series(int slot_index, const QVector<se
"QPushButton:hover { color: %2; }")
.arg(col::TEXT_TERTIARY())
.arg(col::NEGATIVE()));
- connect(remove_btn, &QPushButton::clicked, this,
- [this, slot_index, series_id]() { emit remove_from_slot_clicked(slot_index, series_id); });
+ connect(remove_btn, &QPushButton::clicked, this, [this, slot_widget, series_id]() {
+ const int idx = slots_layout_->indexOf(slot_widget);
+ if (idx >= 0)
+ emit remove_from_slot_clicked(idx, series_id);
+ });
row_layout->addWidget(remove_btn);
slot_layout->addWidget(row);
diff --git a/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.h b/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.h
index c563efef1..a916d26f0 100644
--- a/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.h
+++ b/fincept-qt/src/screens/dbnomics/DBnomicsSelectionPanel.h
@@ -74,6 +74,7 @@ class DBnomicsSelectionPanel : public QWidget {
private:
void build_ui();
void retranslateUi();
+ void renumber_slots();
void tick_anim();
QWidget* build_search_section();
QWidget* build_provider_section();
diff --git a/fincept-qt/src/screens/equity_research/EquityFinancialsTab.cpp b/fincept-qt/src/screens/equity_research/EquityFinancialsTab.cpp
index f30d334ce..082901a8c 100644
--- a/fincept-qt/src/screens/equity_research/EquityFinancialsTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityFinancialsTab.cpp
@@ -169,6 +169,12 @@ EquityFinancialsTab::EquityFinancialsTab(QWidget* parent) : QWidget(parent) {
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::financials_loaded, this,
&EquityFinancialsTab::on_financials_loaded);
+ // Dismiss the "LOADING FINANCIALS…" overlay on failure — it's hidden only on success.
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if (ctx == "Financials" && loading_overlay_)
+ loading_overlay_->hide_loading();
+ });
}
void EquityFinancialsTab::set_symbol(const QString& symbol) {
diff --git a/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp b/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
index 887333936..0b62ac0ac 100644
--- a/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
@@ -18,6 +18,12 @@ EquityNewsTab::EquityNewsTab(QWidget* parent) : QWidget(parent) {
build_ui();
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::news_loaded, this, &EquityNewsTab::on_news_loaded);
+ // Dismiss the "LOADING NEWS…" overlay on failure — it's hidden only on success.
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if (ctx == "News" && loading_overlay_)
+ loading_overlay_->hide_loading();
+ });
}
void EquityNewsTab::set_symbol(const QString& symbol) {
diff --git a/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp b/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp
index 9ad943ce8..f5c4c4bb1 100644
--- a/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp
@@ -17,6 +17,12 @@ EquityPeersTab::EquityPeersTab(QWidget* parent) : QWidget(parent) {
build_ui();
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::peers_loaded, this, &EquityPeersTab::on_peers_loaded);
+ // Dismiss the "LOADING PEERS…" overlay on failure — it's hidden only on success.
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if (ctx == "Peers" && loading_overlay_)
+ loading_overlay_->hide_loading();
+ });
}
void EquityPeersTab::set_symbol(const QString& symbol) {
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 82fc45c45..532d7aed6 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -61,6 +61,13 @@ EquityResearchScreen::EquityResearchScreen(QWidget* parent) : QWidget(parent) {
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::quote_loaded, this, &EquityResearchScreen::on_quote_loaded);
connect(&svc, &services::equity::EquityResearchService::info_loaded, this, &EquityResearchScreen::on_info_loaded);
+ // Reset the quote bar off "Loading…" when the quote fetch fails (it's otherwise
+ // updated only on the success path, so a failed symbol shows "Loading…" forever).
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if (ctx == "Quote" && price_label_)
+ price_label_->setText(tr("Unavailable"));
+ });
// Keep the BUY/SELL buttons in sync as broker accounts connect/disconnect or
// are added/removed, so they appear/disappear without needing a tab re-show.
diff --git a/fincept-qt/src/screens/equity_research/EquityTechnicalsTab.cpp b/fincept-qt/src/screens/equity_research/EquityTechnicalsTab.cpp
index 19e14adc8..89258c6b5 100644
--- a/fincept-qt/src/screens/equity_research/EquityTechnicalsTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityTechnicalsTab.cpp
@@ -164,6 +164,13 @@ EquityTechnicalsTab::EquityTechnicalsTab(QWidget* parent) : QWidget(parent) {
auto& svc = services::equity::EquityResearchService::instance();
connect(&svc, &services::equity::EquityResearchService::technicals_loaded, this,
&EquityTechnicalsTab::on_technicals_loaded);
+ // Without this a failed fetch/compute leaves the overlay spinning "COMPUTING
+ // INDICATORS…" forever (the overlay is hidden only on the success path).
+ connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
+ [this](const QString& ctx, const QString&) {
+ if ((ctx == "Technicals" || ctx == "Historical") && loading_overlay_)
+ loading_overlay_->hide_loading();
+ });
}
void EquityTechnicalsTab::set_symbol(const QString& symbol) {
diff --git a/fincept-qt/src/screens/equity_trading/EquityChart.cpp b/fincept-qt/src/screens/equity_trading/EquityChart.cpp
index 6c1ff703b..e6707f48a 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChart.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityChart.cpp
@@ -390,6 +390,57 @@ void EquityChart::set_candles(const QVector<trading::BrokerCandle>& candles) {
update_last_price_marker();
}
+void EquityChart::update_last_candle(const trading::BrokerCandle& candle) {
+ if (candle.timestamp <= 0 || candle.open <= 0.0 || candle.high <= 0.0 ||
+ candle.low <= 0.0 || candle.close <= 0.0)
+ return;
+
+ if (candles_.isEmpty() || candle.timestamp > candles_.last().timestamp) {
+ // Roll-forward: a new forming bar. Reuse the bulk path (rebuild +
+ // overlays + axes) -- it runs at most once per bar interval.
+ QVector<trading::BrokerCandle> next = candles_;
+ next.append(candle);
+ set_candles(next);
+ return;
+ }
+ if (candle.timestamp != candles_.last().timestamp)
+ return; // tick for an older bar -- the next history reload reconciles
+
+ // Per-tick hot path: replace the forming bar in place.
+ candles_.last() = candle;
+
+ const auto sets = series_->sets();
+ QCandlestickSet* last_set = sets.isEmpty() ? nullptr : sets.last();
+ if (last_set &&
+ static_cast<int64_t>(last_set->timestamp()) == synth_ts_for(candles_.size() - 1)) {
+ last_set->setOpen(candle.open);
+ last_set->setHigh(candle.high);
+ last_set->setLow(candle.low);
+ last_set->setClose(candle.close);
+ } else {
+ // The last candle has no candlestick set (it was invalid when the
+ // history loaded) -- rebuild once so the forming bar is rendered.
+ rebuild_chart();
+ }
+
+ // Grow the price axis when the tick pierces the current bounds. Passing
+ // the sets' own raw synthetic range leaves the time axis untouched.
+ if (bounds_dirty_)
+ recompute_bounds();
+ if (cached_min_price_ > 0.0 &&
+ (candle.low < cached_min_price_ || candle.high > cached_max_price_)) {
+ cached_min_price_ = std::min(cached_min_price_, candle.low);
+ cached_max_price_ = std::max(cached_max_price_, candle.high);
+ const auto cur = series_->sets();
+ if (!cur.isEmpty())
+ update_axes(cached_min_price_, cached_max_price_,
+ static_cast<qint64>(cur.first()->timestamp()),
+ static_cast<qint64>(cur.last()->timestamp()));
+ }
+
+ update_last_price_marker();
+}
+
void EquityChart::recompute_bounds() {
const auto& sets = series_->sets();
if (sets.isEmpty()) {
diff --git a/fincept-qt/src/screens/equity_trading/EquityChart.h b/fincept-qt/src/screens/equity_trading/EquityChart.h
index 941c0d702..bbb8fc308 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChart.h
+++ b/fincept-qt/src/screens/equity_trading/EquityChart.h
@@ -36,6 +36,9 @@ public:
explicit EquityChart(QWidget* parent = nullptr);
void set_candles(const QVector<trading::BrokerCandle>& candles);
+ // Live-tick path: update the forming (last) bar in place, or append a new
+ // bar when the timestamp rolls past the current last one.
+ void update_last_candle(const trading::BrokerCandle& candle);
void clear();
// Draw/clear a dashed horizontal line at an open position's entry price.
diff --git a/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
index 16024fe0c..4060927b5 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityChartPanel.cpp
@@ -52,8 +52,10 @@ EquityChartPanel::EquityChartPanel(QWidget* parent) : QWidget(parent) {
delete kline_;
kline_ = nullptr;
fallback_ = new EquityChart(this);
- connect(fallback_, &EquityChart::timeframe_changed, this,
- &EquityChartPanel::timeframe_changed);
+ connect(fallback_, &EquityChart::timeframe_changed, this, [this](const QString& tf) {
+ have_bar_ = false; // fresh history will arrive for the new timeframe
+ emit timeframe_changed(tf);
+ });
connect(fallback_, &EquityChart::buy_requested, this, &EquityChartPanel::buy_requested);
connect(fallback_, &EquityChart::sell_requested, this, &EquityChartPanel::sell_requested);
connect(fallback_, &EquityChart::add_to_watchlist_requested, this,
@@ -124,29 +126,30 @@ QString EquityChartPanel::current_timeframe() const {
}
void EquityChartPanel::set_candles(const QVector<trading::BrokerCandle>& candles) {
- if (fallback_) {
- fallback_->set_candles(candles);
- return;
- }
- if (!kline_)
+ if (!fallback_ && !kline_)
return;
- QJsonArray arr;
- for (const auto& c : candles) {
- QJsonObject o;
- // BrokerCandle.timestamp is milliseconds; KLineChartWidget expects
- // seconds (it multiplies by 1000 internally).
- o[QStringLiteral("timestamp")] = static_cast<double>(c.timestamp / 1000);
- o[QStringLiteral("open")] = c.open;
- o[QStringLiteral("high")] = c.high;
- o[QStringLiteral("low")] = c.low;
- o[QStringLiteral("close")] = c.close;
- o[QStringLiteral("volume")] = c.volume;
- arr.append(o);
+ if (fallback_) {
+ fallback_->set_candles(candles);
+ } else {
+ QJsonArray arr;
+ for (const auto& c : candles) {
+ QJsonObject o;
+ // BrokerCandle.timestamp is milliseconds; KLineChartWidget expects
+ // seconds (it multiplies by 1000 internally).
+ o[QStringLiteral("timestamp")] = static_cast<double>(c.timestamp / 1000);
+ o[QStringLiteral("open")] = c.open;
+ o[QStringLiteral("high")] = c.high;
+ o[QStringLiteral("low")] = c.low;
+ o[QStringLiteral("close")] = c.close;
+ o[QStringLiteral("volume")] = c.volume;
+ arr.append(o);
+ }
+ kline_->set_candles(arr);
}
- kline_->set_candles(arr);
- // Seed forming-bar state from the most recent candle for live updates.
+ // Seed forming-bar state from the most recent candle for live updates
+ // (both backends extend this baseline in on_quote()).
if (!candles.isEmpty()) {
const auto& last = candles.last();
have_bar_ = true;
@@ -162,7 +165,7 @@ void EquityChartPanel::set_candles(const QVector<trading::BrokerCandle>& candles
}
void EquityChartPanel::on_quote(const trading::BrokerQuote& quote) {
- if (fallback_ || !kline_) // fallback chart has no incremental-update API
+ if (!fallback_ && !kline_)
return;
if (!have_bar_) // need a loaded history baseline to extend
return;
@@ -190,6 +193,14 @@ void EquityChartPanel::on_quote(const trading::BrokerQuote& quote) {
bar_low_ = px;
}
+ if (fallback_) {
+ // Qt-Charts backend — hand the forming bar over as a BrokerCandle; the
+ // chart updates its last bar in place (or appends on roll-forward).
+ fallback_->update_last_candle(
+ trading::BrokerCandle{bar_ts_ms_, bar_open_, bar_high_, bar_low_, bar_close_, bar_vol_});
+ return;
+ }
+
QJsonObject o;
o[QStringLiteral("timestamp")] = static_cast<double>(bar_ts_ms_ / 1000);
o[QStringLiteral("open")] = bar_open_;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 627669e2b..e7d7ad4cc 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -462,10 +462,20 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
return;
}
pt_fill_order(pt_order.id, fill_price);
+ // Register the protective SL/TP bracket against the filled position.
+ // check_sl_tp_triggers runs every tick but ran against an EMPTY registry
+ // because set_sl_tp was never called on the equity path — so equity paper
+ // stops gave zero protection until now.
+ if (order.stop_loss > 0 || order.take_profit > 0)
+ OrderMatcher::instance().set_sl_tp(portfolio_id, order.symbol, pt_order.id, order.stop_loss,
+ order.take_profit);
order_entry_->show_order_status(
tr("Paper order filled: %1 @ %2").arg(order.symbol).arg(fill_price, 0, 'f', 2), true);
} else {
OrderMatcher::instance().add_order(pt_order);
+ if (order.stop_loss > 0 || order.take_profit > 0)
+ OrderMatcher::instance().set_sl_tp(portfolio_id, order.symbol, pt_order.id, order.stop_loss,
+ order.take_profit);
order_entry_->show_order_status(tr("Paper order queued: %1").arg(order.symbol), true);
}
} catch (const std::exception& e) {
diff --git a/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp b/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
index ecb063fb2..5329901fa 100644
--- a/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/HDXDataPanel.cpp
@@ -26,6 +26,22 @@ HDXDataPanel::HDXDataPanel(QWidget* parent) : QWidget(parent) {
void HDXDataPanel::connect_service() {
auto& svc = GeopoliticsService::instance();
connect(&svc, &GeopoliticsService::hdx_results_loaded, this, &HDXDataPanel::on_hdx_results);
+ // Without this the panel hangs on "Loading HDX data…" forever whenever the
+ // fetch fails (and re-fires the failing request on every tab switch).
+ connect(&svc, &GeopoliticsService::error_occurred, this, &HDXDataPanel::on_error);
+}
+
+void HDXDataPanel::on_error(const QString& context, const QString& message) {
+ Q_UNUSED(context);
+ // Stop the perpetual spinner and surface the failure in its place.
+ if (datasets_table_)
+ datasets_table_->setRowCount(0);
+ if (dataset_count_)
+ dataset_count_->setText(QStringLiteral("0"));
+ if (loading_label_) {
+ loading_label_->setText(tr("Failed to load HDX data:\n%1").arg(message));
+ loading_label_->show();
+ }
}
void HDXDataPanel::build_ui() {
diff --git a/fincept-qt/src/screens/geopolitics/HDXDataPanel.h b/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
index f3a1ab32c..05967daad 100644
--- a/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
+++ b/fincept-qt/src/screens/geopolitics/HDXDataPanel.h
@@ -25,6 +25,7 @@ class HDXDataPanel : public QWidget {
private slots:
void on_hdx_results(const QString& context, QVector<fincept::services::geo::HDXDataset> datasets);
+ void on_error(const QString& context, const QString& message);
void on_view_changed(int index);
private:
diff --git a/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp b/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp
index 520dd8b94..c65e6889d 100644
--- a/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/RelationshipPanel.cpp
@@ -73,6 +73,19 @@ void RelationshipPanel::build_ui() {
.arg(ui::fonts::TINY)
.arg(ui::fonts::DATA_FAMILY()));
hhl->addWidget(title_lbl_);
+
+ // The network below is illustrative sample data (see build_nodes), not a live
+ // feed — surface that honestly with a badge so the figures are never mistaken
+ // for real conflict/humanitarian metrics.
+ sample_badge_ = new QLabel(tr("SAMPLE DATA"), header);
+ sample_badge_->setToolTip(tr("Illustrative network — not sourced from a live data feed."));
+ sample_badge_->setStyleSheet(QString("color:#000; background:%1; font-size:%2px; font-weight:700;"
+ "font-family:%3; padding:2px 6px; border-radius:2px; letter-spacing:1px;")
+ .arg(ui::colors::WARNING())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY));
+ hhl->addWidget(sample_badge_);
+
hhl->addStretch();
auto nodes = build_nodes();
@@ -114,6 +127,24 @@ void RelationshipPanel::build_ui() {
cvl->setContentsMargins(16, 16, 16, 16);
cvl->setSpacing(16);
+ // Honesty banner — the nodes/dataset counts are hardcoded sample data.
+ {
+ QColor warnc(ui::colors::WARNING());
+ const QString warn_rgb = QString("%1,%2,%3").arg(warnc.red()).arg(warnc.green()).arg(warnc.blue());
+ sample_note_ = new QLabel(
+ tr("Sample data — this relationship network is illustrative and is not sourced from a live "
+ "feed. Node counts and connections are placeholders, not real-time conflict metrics."),
+ content);
+ sample_note_->setWordWrap(true);
+ sample_note_->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:8px 10px;"
+ "background:rgba(%4,0.10); border:1px solid %1;")
+ .arg(ui::colors::WARNING())
+ .arg(ui::fonts::SMALL)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(warn_rgb));
+ cvl->addWidget(sample_note_);
+ }
+
// Helper: add a titled section with a 3-column card grid
auto add_section = [&](const QString& title, const QString& color, const QString& type, QLabel** out) {
auto* sec_lbl = new QLabel(title, content);
@@ -286,6 +317,14 @@ void RelationshipPanel::changeEvent(QEvent* event) {
void RelationshipPanel::retranslateUi() {
if (title_lbl_) title_lbl_->setText(tr("GEOPOLITICAL RELATIONSHIP NETWORK"));
+ if (sample_badge_) {
+ sample_badge_->setText(tr("SAMPLE DATA"));
+ sample_badge_->setToolTip(tr("Illustrative network — not sourced from a live data feed."));
+ }
+ if (sample_note_)
+ sample_note_->setText(
+ tr("Sample data — this relationship network is illustrative and is not sourced from a live "
+ "feed. Node counts and connections are placeholders, not real-time conflict metrics."));
if (stats_lbl_)
stats_lbl_->setText(tr("NODES: %1 | CONFLICTS: %2 | ORGANIZATIONS: %3")
.arg(node_count_)
diff --git a/fincept-qt/src/screens/geopolitics/RelationshipPanel.h b/fincept-qt/src/screens/geopolitics/RelationshipPanel.h
index 5fd9a50b4..493e0d2a9 100644
--- a/fincept-qt/src/screens/geopolitics/RelationshipPanel.h
+++ b/fincept-qt/src/screens/geopolitics/RelationshipPanel.h
@@ -30,6 +30,8 @@ class RelationshipPanel : public QWidget {
// Static text widgets (cached for retranslateUi)
QLabel* title_lbl_ = nullptr;
+ QLabel* sample_badge_ = nullptr; // "SAMPLE DATA" pill — data is hardcoded, not live
+ QLabel* sample_note_ = nullptr; // honesty banner above the network
QLabel* stats_lbl_ = nullptr;
QLabel* sec_conflicts_ = nullptr;
QLabel* sec_crisis_ = nullptr;
diff --git a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
index 5a659b868..4cc4cc36b 100644
--- a/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
+++ b/fincept-qt/src/screens/geopolitics/TradeAnalysisPanel.cpp
@@ -353,7 +353,10 @@ void TradeAnalysisPanel::build_ui() {
p["integration_type"] = bloc_combo->currentData().toString();
p["trade_creation"] = tc_spin->value();
p["trade_diversion"] = td_spin->value();
- GeopoliticsService::instance().analyze_trade_benefits(p); // reuses benefits endpoint with trading_blocs type
+ // Trading-bloc integration maps to the benefits/costs mode (trade creation vs.
+ // diversion are welfare effects). A dedicated `trading_blocs` backend mode exists
+ // in trade_geopolitics.py but is not yet exposed by GeopoliticsService.
+ GeopoliticsService::instance().analyze_trade_benefits(p);
});
p2l->addWidget(run2);
run_buttons_.append(run2);
@@ -417,7 +420,12 @@ void TradeAnalysisPanel::build_ui() {
p["liberalization_type"] = lib_combo->currentData().toString();
p["tariff_reduction"] = tariff_cut_spin->value();
p["gdp_size"] = gdp_spin->value();
- GeopoliticsService::instance().analyze_trade_restrictions(p); // reuses restrictions endpoint
+ // Barrier *removal* is trade liberalization — its economic impact maps to the
+ // benefits/costs analysis, NOT the trade-restrictions analysis (which models
+ // *imposing* tariffs/quotas, the opposite direction). Route to the benefits mode.
+ // A dedicated `barrier_removal` backend mode exists in trade_geopolitics.py but is
+ // not yet exposed by GeopoliticsService.
+ GeopoliticsService::instance().analyze_trade_benefits(p);
});
p3l->addWidget(run3);
run_buttons_.append(run3);
diff --git a/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp b/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp
index 465c24473..264b086e5 100644
--- a/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp
+++ b/fincept-qt/src/screens/gov_data/GovDataProviderPanel.cpp
@@ -161,8 +161,15 @@ void GovDataProviderPanel::build_ui() {
auto* combo = new QComboBox;
combo->setObjectName("govPortalCombo");
combo->addItems(options_.portal_combo_items);
+ // Portal switching is not yet wired: the universal CKAN connector script
+ // (datagovuk_api.py) hardcodes the data.gov.uk endpoint and takes no
+ // portal argument, so the selector is informational and shown disabled.
+ combo->setEnabled(false);
if (!options_.portal_combo_tooltip.isEmpty())
combo->setToolTip(options_.portal_combo_tooltip);
+ else
+ combo->setToolTip(tr("Portal switching is not yet functional — this panel "
+ "queries data.gov.uk only."));
combo->setStyleSheet(
QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
" font-size:10px; font-weight:700; padding:2px 8px; min-width:160px; }"
diff --git a/fincept-qt/src/screens/markets/MarketPanel.cpp b/fincept-qt/src/screens/markets/MarketPanel.cpp
index 069e2e2a9..c36f64a64 100644
--- a/fincept-qt/src/screens/markets/MarketPanel.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanel.cpp
@@ -114,6 +114,7 @@ void MarketPanel::build_ui() {
el->setAlignment(Qt::AlignCenter);
error_label_ = new QLabel;
error_label_->setAlignment(Qt::AlignCenter);
+ error_label_->setWordWrap(true); // narrow panels — wrap the failure message
retry_btn_ = new QPushButton(tr("[RETRY]"));
retry_btn_->setCursor(Qt::PointingHandCursor);
retry_btn_->setFlat(true);
@@ -335,6 +336,24 @@ void MarketPanel::hub_resubscribe() {
emit refresh_finished();
}
});
+ // Failure path: every requested topic ends with either publish()
+ // (delivered above) or publish_error(). Without an error subscription
+ // the panel never learns of a producer failure, so the LOADING overlay
+ // spins forever and refresh_finished() never emits. Mirror the drain
+ // here, then — once the whole initial set has resolved with nothing
+ // delivered — switch to the inline error state so [RETRY] is reachable.
+ hub.subscribe_errors(this, topic, [this, sym](const QString& err) {
+ if (refresh_inflight_ && pending_initial_.remove(sym) && pending_initial_.isEmpty()) {
+ refresh_inflight_ = false;
+ emit refresh_finished();
+ }
+ if (!has_data_ && pending_initial_.isEmpty()) {
+ fetch_failed_ = true;
+ show_error(err.trimmed().isEmpty()
+ ? tr("Failed to load market data")
+ : tr("Load failed: %1").arg(err.trimmed()));
+ }
+ });
}
// force=true: on cold start, DataHub::subscribe auto-triggers a fetch,
// but on user-initiated refresh_all() (F5 / auto-refresh tick / panel
@@ -388,6 +407,7 @@ void MarketPanel::show_data() {
}
void MarketPanel::show_error(const QString& msg) {
+ hide_loading(); // stop the spinner + hide the LOADING overlay
table_->setVisible(false);
error_widget_->setVisible(true);
error_label_->setText(msg);
diff --git a/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp b/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
index f2e9c4c35..30608c957 100644
--- a/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
+++ b/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
@@ -1046,14 +1046,18 @@ void NodeEditorScreen::on_deploy() {
wf.id = current_workflow_id_;
wf.name = dlg.workflow_name();
wf.description = dlg.workflow_description();
- wf.status = dlg.is_deploy() ? WorkflowStatus::Idle : WorkflowStatus::Draft;
+ // There is no scheduler or webhook runtime, so a saved workflow is never a
+ // live deployment. Persist it as a Draft rather than an "idle" (active,
+ // waiting-for-trigger) deployment so listings don't imply it will run again.
+ wf.status = WorkflowStatus::Draft;
toolbar_->set_workflow_name(wf.name);
WorkflowService::instance().save_workflow(wf);
if (dlg.is_deploy()) {
- LOG_INFO("NodeEditor", QString("Deployed workflow: %1").arg(wf.name));
- // Auto-execute after deploy
+ LOG_INFO("NodeEditor", QString("Saved and ran workflow once: %1").arg(wf.name));
+ // "Deploy" is save + run once. There is no scheduler/webhook listener to
+ // fire trigger.* / schedule nodes again, so the workflow does not stay active.
on_execute();
} else {
LOG_INFO("NodeEditor", QString("Saved draft: %1").arg(wf.name));
diff --git a/fincept-qt/src/screens/node_editor/toolbar/DeployDialog.cpp b/fincept-qt/src/screens/node_editor/toolbar/DeployDialog.cpp
index 4bfdf9a14..6580fb64e 100644
--- a/fincept-qt/src/screens/node_editor/toolbar/DeployDialog.cpp
+++ b/fincept-qt/src/screens/node_editor/toolbar/DeployDialog.cpp
@@ -17,7 +17,7 @@ static QString deploy_input_style() {
}
DeployDialog::DeployDialog(const QString& current_name, QWidget* parent) : QDialog(parent) {
- setWindowTitle(tr("Deploy Workflow"));
+ setWindowTitle(tr("Save & Run Workflow"));
setFixedSize(420, 320);
setStyleSheet(QString("QDialog { background: %1; }").arg(ui::colors::BG_SURFACE()));
build_ui(current_name);
@@ -36,7 +36,7 @@ void DeployDialog::build_ui(const QString& current_name) {
root->setSpacing(12);
// ── Title ──────────────────────────────────────────────────────
- title_label_ = new QLabel(tr("DEPLOY WORKFLOW"));
+ title_label_ = new QLabel(tr("SAVE & RUN WORKFLOW"));
title_label_->setStyleSheet(QString("color: %1; font-family: Consolas; font-size: 14px;"
"font-weight: bold; letter-spacing: 0.5px;")
.arg(ui::colors::AMBER()));
@@ -107,7 +107,7 @@ void DeployDialog::build_ui(const QString& current_name) {
});
btn_row->addWidget(draft_btn_);
- deploy_btn_ = new QPushButton(tr("DEPLOY"));
+ deploy_btn_ = new QPushButton(tr("SAVE & RUN"));
deploy_btn_->setFixedHeight(28);
deploy_btn_->setStyleSheet(
QString("QPushButton {"
@@ -133,14 +133,14 @@ void DeployDialog::changeEvent(QEvent* event) {
}
void DeployDialog::retranslateUi() {
- setWindowTitle(tr("Deploy Workflow"));
- if (title_label_) title_label_->setText(tr("DEPLOY WORKFLOW"));
+ setWindowTitle(tr("Save & Run Workflow"));
+ if (title_label_) title_label_->setText(tr("SAVE & RUN WORKFLOW"));
if (name_label_) name_label_->setText(tr("WORKFLOW NAME"));
if (desc_label_) desc_label_->setText(tr("DESCRIPTION"));
if (desc_edit_) desc_edit_->setPlaceholderText(tr("Describe what this workflow does..."));
if (cancel_btn_) cancel_btn_->setText(tr("CANCEL"));
if (draft_btn_) draft_btn_->setText(tr("SAVE DRAFT"));
- if (deploy_btn_) deploy_btn_->setText(tr("DEPLOY"));
+ if (deploy_btn_) deploy_btn_->setText(tr("SAVE & RUN"));
}
} // namespace fincept::workflow
diff --git a/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp b/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
index 65e5dfec5..9b73af689 100644
--- a/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
+++ b/fincept-qt/src/screens/node_editor/toolbar/NodeEditorToolbar.cpp
@@ -109,7 +109,7 @@ void NodeEditorToolbar::retranslateUi() {
if (import_btn_) import_btn_->setText(tr("IMPORT"));
if (export_btn_) export_btn_->setText(tr("EXPORT"));
if (templates_btn_) templates_btn_->setText(tr("TEMPLATES"));
- if (deploy_btn_) deploy_btn_->setText(tr("DEPLOY"));
+ if (deploy_btn_) deploy_btn_->setText(tr("SAVE & RUN"));
// Execute button text depends on running state; default to EXECUTE.
if (execute_btn_) execute_btn_->setText(tr("EXECUTE"));
}
@@ -213,7 +213,7 @@ void NodeEditorToolbar::build_ui() {
connect(templates_btn_, &QPushButton::clicked, this, &NodeEditorToolbar::templates_clicked);
// ── Deploy ─────────────────────────────────────────────────────
- deploy_btn_ = new QPushButton(tr("DEPLOY"));
+ deploy_btn_ = new QPushButton(tr("SAVE & RUN"));
deploy_btn_->setStyleSheet(btn_style());
layout->addWidget(deploy_btn_);
connect(deploy_btn_, &QPushButton::clicked, this, &NodeEditorToolbar::deploy_clicked);
diff --git a/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp b/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp
index ac7d641c6..930ca97c8 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp
@@ -784,6 +784,15 @@ void PolymarketScreen::on_adapter_error(const QString& ctx, const QString& msg)
browse_panel_->set_loading(false);
LOG_WARN("PredictionMarkets", ctx + ": " + msg);
if (status_bar_) status_bar_->set_selected(QString("%1: %2").arg(ctx, msg));
+ // A place_order failure/rejection lands here because run_py's error path emits
+ // error_occurred and skips the order_placed signal. Reset the order ticket from
+ // "Submitting…" and surface the reason, else the submit button stays disabled.
+ if (ctx == QStringLiteral("place_order") && detail_panel_) {
+ pred::OrderResult r;
+ r.ok = false;
+ r.error_message = msg;
+ detail_panel_->on_order_result(r);
+ }
}
// ── WebSocket handlers ──────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp b/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp
index 20d3a8c32..e655f0ad4 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioFFNView.cpp
@@ -58,6 +58,59 @@ static QTableWidgetItem* make_item(const QString& text, Qt::Alignment align, con
return item;
}
+// ── Benchmark stats ───────────────────────────────────────────────────────────
+// Computed natively from the SPY daily closes routed in via set_benchmark()
+// (same 1-year series the perf-chart overlay uses). All values are fractions.
+struct BenchStats {
+ bool valid = false;
+ double total_return = 0, cagr = 0, volatility = 0, sharpe = 0, max_drawdown = 0;
+};
+
+static BenchStats compute_bench_stats(const QVector<double>& closes) {
+ BenchStats s;
+ if (closes.size() < 3 || closes.first() <= 0.0 || closes.last() <= 0.0)
+ return s;
+
+ const int n = closes.size() - 1; // daily return periods
+ s.total_return = closes.last() / closes.first() - 1.0;
+ s.cagr = std::pow(closes.last() / closes.first(), 252.0 / n) - 1.0;
+
+ // Annualized volatility from daily simple returns (sample stdev × √252)
+ QVector<double> rets;
+ rets.reserve(n);
+ double mean = 0;
+ for (int i = 1; i < closes.size(); ++i) {
+ if (closes[i - 1] <= 0.0)
+ continue;
+ const double r = closes[i] / closes[i - 1] - 1.0;
+ rets.append(r);
+ mean += r;
+ }
+ if (rets.size() < 2)
+ return s;
+ mean /= rets.size();
+ double var = 0;
+ for (double r : rets)
+ var += (r - mean) * (r - mean);
+ var /= (rets.size() - 1);
+ s.volatility = std::sqrt(var) * std::sqrt(252.0);
+
+ // Mirrors PortfolioService::kDefaultRiskFreeRate (0.04) — keep in sync.
+ constexpr double kRfRate = 0.04;
+ s.sharpe = s.volatility > 1e-9 ? (s.cagr - kRfRate) / s.volatility : 0.0;
+
+ // Max drawdown: worst peak-to-trough decline
+ double peak = closes.first();
+ for (double c : closes) {
+ peak = std::max(peak, c);
+ if (peak > 0.0)
+ s.max_drawdown = std::min(s.max_drawdown, c / peak - 1.0);
+ }
+
+ s.valid = true;
+ return s;
+}
+
// ── Constructor / build_ui ────────────────────────────────────────────────────
PortfolioFFNView::PortfolioFFNView(QWidget* parent) : QWidget(parent) {
@@ -203,7 +256,7 @@ void PortfolioFFNView::build_ui() {
vl->addWidget(benchmark_table_);
benchmark_info_label_ = new QLabel(tr("Portfolio metrics computed from 1-year price history via yfinance.\n"
- "Connect a live benchmark feed to populate the Benchmark column."));
+ "Benchmark column: SPY (S&P 500), computed from 1-year daily closes."));
benchmark_info_label_->setWordWrap(true);
benchmark_info_label_->setStyleSheet(
QString("color:%1; font-size:10px; padding:6px 0;").arg(ui::colors::TEXT_TERTIARY()));
@@ -372,6 +425,16 @@ void PortfolioFFNView::set_data(const portfolio::PortfolioSummary& summary, cons
update_overview();
}
+void PortfolioFFNView::set_benchmark(const QVector<double>& closes) {
+ benchmark_closes_ = closes;
+ // Refresh the tables that carry a benchmark column. Same guards as
+ // retranslateUi(): each update_* needs its source data to be present.
+ if (!summary_.holdings.isEmpty())
+ update_overview();
+ if (!ffn_data_.isEmpty())
+ update_benchmark();
+}
+
// ── update_overview ───────────────────────────────────────────────────────────
void PortfolioFFNView::update_overview() {
@@ -407,11 +470,29 @@ void PortfolioFFNView::update_overview() {
worst_sym = h.symbol;
}
}
+ // Portfolio-level volatility/Sharpe/max-drawdown are NOT linear in the
+ // holding weights, so the per-symbol weighted sums above are statistically
+ // wrong for these. Prefer the FFN optimizer's real portfolio stats (the
+ // same source update_benchmark() uses); the weighted values remain only as
+ // a fallback when the optimizer block is absent.
+ auto cur_stats =
+ ffn_data_["optimization"].toObject()["stats"].toObject()["current"].toObject();
+ if (!cur_stats.isEmpty()) {
+ total_ann_ret = cur_stats["cagr"].toDouble();
+ total_ann_vol = cur_stats["volatility"].toDouble();
+ total_sharpe = cur_stats["sharpe"].toDouble();
+ total_max_dd = cur_stats["max_drawdown"].toDouble();
+ }
}
double pnl_pct = summary_.total_unrealized_pnl_percent;
double win_rate = summary_.total_positions > 0 ? summary_.gainers * 100.0 / summary_.total_positions : 0.0;
+ // Benchmark (SPY) column — "--" until set_benchmark() has delivered closes.
+ const BenchStats bench = compute_bench_stats(benchmark_closes_);
+ auto bench_pct = [&](double v) { return bench.valid ? pct_str(v) : QStringLiteral("--"); };
+ auto bench_num = [&](double v) { return bench.valid ? fmt(v) : QStringLiteral("--"); };
+
struct Row {
QString name;
QString value;
@@ -422,11 +503,12 @@ void PortfolioFFNView::update_overview() {
if (has_ffn) {
rows = {
- {tr("Annualized Return"), pct_str(total_ann_ret), "--",
+ {tr("Annualized Return"), pct_str(total_ann_ret), bench_pct(bench.cagr),
total_ann_ret >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE},
- {tr("Annualized Volatility"), pct_str(total_ann_vol), "--", ui::colors::CYAN},
- {tr("Sharpe Ratio"), fmt(total_sharpe), "--", total_sharpe >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE},
- {tr("Max Drawdown"), pct_str(total_max_dd), "--", ui::colors::NEGATIVE},
+ {tr("Annualized Volatility"), pct_str(total_ann_vol), bench_pct(bench.volatility), ui::colors::CYAN},
+ {tr("Sharpe Ratio"), fmt(total_sharpe), bench_num(bench.sharpe),
+ total_sharpe >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE},
+ {tr("Max Drawdown"), pct_str(total_max_dd), bench_pct(bench.max_drawdown), ui::colors::NEGATIVE},
{tr("Best Day (any)"), pct_str(total_best_day), "--", ui::colors::POSITIVE},
{tr("Worst Day (any)"), pct_str(total_worst_day), "--", ui::colors::NEGATIVE},
{tr("Positive Days"), QString::number(pos_days), "--", ui::colors::POSITIVE},
@@ -461,8 +543,10 @@ void PortfolioFFNView::update_overview() {
rows = {
{tr("Total Return (unrealized)"), pct_str(pnl_pct / 100.0), "--",
pnl_pct >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE},
- {tr("Annualized Volatility (est.)"), pct_str(ann_vol / 100.0), "--", ui::colors::CYAN},
- {tr("Sharpe Ratio (est.)"), fmt(sharpe), "--", sharpe >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE},
+ {tr("Annualized Volatility (est.)"), pct_str(ann_vol / 100.0), bench_pct(bench.volatility),
+ ui::colors::CYAN},
+ {tr("Sharpe Ratio (est.)"), fmt(sharpe), bench_num(bench.sharpe),
+ sharpe >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE},
{tr("Win Rate"), fmt(win_rate) + "%", "--", ui::colors::CYAN},
{tr("Positions"), QString::number(summary_.total_positions), "--", ui::colors::CYAN},
{tr("Total Value"), currency_ + " " + fmt(summary_.total_market_value), "--", ui::colors::WARNING},
@@ -479,7 +563,10 @@ void PortfolioFFNView::update_overview() {
r, 0, make_item(row.name, Qt::AlignLeft | Qt::AlignVCenter, QColor(ui::colors::TEXT_SECONDARY())));
overview_table_->setItem(r, 1, make_item(row.value, Qt::AlignRight | Qt::AlignVCenter, QColor(row.color)));
overview_table_->setItem(
- r, 2, make_item(row.benchmark, Qt::AlignRight | Qt::AlignVCenter, QColor(ui::colors::TEXT_TERTIARY())));
+ r, 2,
+ make_item(row.benchmark, Qt::AlignRight | Qt::AlignVCenter,
+ QColor(row.benchmark == QLatin1String("--") ? ui::colors::TEXT_TERTIARY()
+ : ui::colors::TEXT_PRIMARY())));
}
}
@@ -491,7 +578,14 @@ void PortfolioFFNView::update_benchmark() {
auto stats_obj = opt_obj["stats"].toObject();
auto cur_stats = stats_obj["current"].toObject();
- // Rows: metric | portfolio value | benchmark placeholder
+ // Benchmark (SPY) column — "--" until set_benchmark() has delivered closes.
+ const BenchStats bench = compute_bench_stats(benchmark_closes_);
+ const QStringList bench_vals =
+ bench.valid ? QStringList{pct_str(bench.total_return), pct_str(bench.cagr), pct_str(bench.volatility),
+ fmt(bench.sharpe), pct_str(bench.max_drawdown)}
+ : QStringList{"--", "--", "--", "--", "--"};
+
+ // Rows: metric | portfolio value | benchmark (aligned with bench_vals)
struct BRow {
QString metric;
QString portfolio;
@@ -525,7 +619,9 @@ void PortfolioFFNView::update_benchmark() {
benchmark_table_->setItem(
r, 1, make_item(row.portfolio, Qt::AlignRight | Qt::AlignVCenter, QColor(ui::colors::TEXT_PRIMARY())));
benchmark_table_->setItem(
- r, 2, make_item("--", Qt::AlignRight | Qt::AlignVCenter, QColor(ui::colors::TEXT_TERTIARY())));
+ r, 2,
+ make_item(bench_vals.value(r, QStringLiteral("--")), Qt::AlignRight | Qt::AlignVCenter,
+ QColor(bench.valid ? ui::colors::TEXT_PRIMARY() : ui::colors::TEXT_TERTIARY())));
}
}
@@ -940,7 +1036,7 @@ void PortfolioFFNView::retranslateUi() {
if (benchmark_info_label_)
benchmark_info_label_->setText(tr("Portfolio metrics computed from 1-year price history via yfinance.\n"
- "Connect a live benchmark feed to populate the Benchmark column."));
+ "Benchmark column: SPY (S&P 500), computed from 1-year daily closes."));
if (opt_placeholder_)
opt_placeholder_->setText(tr("EFFICIENT FRONTIER\n\nRun FFN Analysis to compute optimal weights\n"
diff --git a/fincept-qt/src/screens/portfolio/PortfolioFFNView.h b/fincept-qt/src/screens/portfolio/PortfolioFFNView.h
index b104f40d0..dd67a2a3f 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioFFNView.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioFFNView.h
@@ -28,6 +28,10 @@ class PortfolioFFNView : public QWidget {
void set_data(const portfolio::PortfolioSummary& summary, const QString& currency);
+ /// Benchmark (SPY) daily closes — feeds the BENCHMARK column of the
+ /// Overview and Benchmark tables (stats computed natively in C++).
+ void set_benchmark(const QVector<double>& closes);
+
signals:
void back_requested();
@@ -107,6 +111,7 @@ class PortfolioFFNView : public QWidget {
portfolio::PortfolioSummary summary_;
QString currency_;
QJsonObject ffn_data_;
+ QVector<double> benchmark_closes_; // SPY daily closes (1y), via set_benchmark()
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
index 20886d966..92ee432bd 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
@@ -82,10 +82,14 @@ PortfolioScreen::PortfolioScreen(QWidget* parent) : QWidget(parent) {
detail_wrapper_->update_correlation(matrix);
});
connect(&svc, &services::PortfolioService::spy_history_loaded, this,
- [this](QStringList /*dates*/, QVector<double> /*closes*/) {
+ [this](QStringList /*dates*/, QVector<double> closes) {
+ // Feed the FFN view's BENCHMARK (SPY) column — it computes
+ // total return / CAGR / vol / Sharpe / max-DD from the closes.
+ if (ffn_view_)
+ ffn_view_->set_benchmark(closes);
// Recompute metrics now that SPY data is available for OLS beta.
// The chart consumes the per-symbol benchmark_history_loaded
- // signal below — SPY here is purely a Beta signal.
+ // signal below — SPY there may differ from this Beta fetch.
if (summary_loaded_)
services::PortfolioService::instance().compute_metrics(current_summary_);
});
diff --git a/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp b/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp
index 9d920183d..0d43d5cc8 100644
--- a/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp
+++ b/fincept-qt/src/screens/report_builder/ReportBuilderScreen_Dialogs.cpp
@@ -20,6 +20,7 @@
#include <QDialog>
#include <QDialogButtonBox>
#include <QFileDialog>
+#include <QFileInfo>
#include <QFormLayout>
#include <QFrame>
#include <QHBoxLayout>
@@ -449,7 +450,15 @@ void ReportBuilderScreen::on_export_pdf() {
if (path.isEmpty())
return;
export_pdf_to(path);
- QMessageBox::information(this, tr("Export PDF"), tr("Report exported successfully to:\n%1").arg(path));
+ // export_pdf_to can fail without throwing (painter-begin failure, unwritable
+ // path, disk full) — verify a non-empty PDF actually landed before claiming
+ // success, instead of always reporting success.
+ const QFileInfo out(path);
+ if (out.exists() && out.size() > 0) {
+ QMessageBox::information(this, tr("Export PDF"), tr("Report exported successfully to:\n%1").arg(path));
+ } else {
+ QMessageBox::warning(this, tr("Export PDF"), tr("Failed to export the report to:\n%1").arg(path));
+ }
}
void ReportBuilderScreen::export_pdf_to(const QString& path) {
diff --git a/fincept-qt/src/screens/setup/SetupScreen.cpp b/fincept-qt/src/screens/setup/SetupScreen.cpp
index 1123e6ef5..dfe82ea6f 100644
--- a/fincept-qt/src/screens/setup/SetupScreen.cpp
+++ b/fincept-qt/src/screens/setup/SetupScreen.cpp
@@ -47,6 +47,14 @@ SetupScreen::SetupScreen(QWidget* parent) : QWidget(parent) {
timeout_timer_->setInterval(15 * 60 * 1000);
connect(timeout_timer_, &QTimer::timeout, this, &SetupScreen::on_setup_timeout);
+ // Reveal the Skip button ~45s in (not only after the full 15-min timeout) so
+ // first-run users are never trapped waiting on the Python setup. Independent
+ // of on_setup_timeout(), which still owns the real Timeout state at 15 min.
+ QTimer::singleShot(45 * 1000, this, [this]() {
+ if (skip_btn_)
+ skip_btn_->setVisible(true);
+ });
+
net_meter_ = new fincept::net::NetSpeedMeter(this);
connect(net_meter_, &fincept::net::NetSpeedMeter::speed_changed,
this, &SetupScreen::on_net_speed);
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp
index ab7d28df2..0775a76ba 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Providers.cpp
@@ -39,6 +39,8 @@ namespace fincept::surface {
using namespace fincept::ui;
void SurfaceAnalyticsScreen::on_vol_surface_received(const fincept::DatabentoVolSurfaceResult& r) {
+ if (r.success && control_panel_)
+ control_panel_->mark_synthetic(false); // real Databento data replaced the demo surface
if (data_inspector_)
data_inspector_->set_status(r.success ? tr("Vol surface loaded") : tr("Vol fetch failed"), r.success);
if (!r.success) {
@@ -103,6 +105,8 @@ void SurfaceAnalyticsScreen::on_vol_surface_received(const fincept::DatabentoVol
}
void SurfaceAnalyticsScreen::on_ohlcv_received(const fincept::DatabentoOhlcvResult& r) {
+ if (r.success && control_panel_)
+ control_panel_->mark_synthetic(false); // real data replaced the demo surface
if (data_inspector_) {
data_inspector_->set_status(r.success ? tr("OHLCV loaded") : tr("OHLCV fetch failed"), r.success);
if (!r.success)
@@ -130,6 +134,8 @@ void SurfaceAnalyticsScreen::on_ohlcv_received(const fincept::DatabentoOhlcvResu
}
void SurfaceAnalyticsScreen::on_futures_received(const fincept::DatabentoFuturesResult& r) {
+ if (r.success && control_panel_)
+ control_panel_->mark_synthetic(false); // real data replaced the demo surface
if (data_inspector_) {
data_inspector_->set_status(r.success ? tr("Futures curve loaded") : tr("Futures fetch failed"), r.success);
if (!r.success)
@@ -147,6 +153,8 @@ void SurfaceAnalyticsScreen::on_futures_received(const fincept::DatabentoFutures
}
void SurfaceAnalyticsScreen::on_surface_received(const fincept::DatabentoSurfaceResult& r) {
+ if (r.success && control_panel_)
+ control_panel_->mark_synthetic(false); // real data replaced the demo surface
if (data_inspector_) {
data_inspector_->set_status(r.success ? tr("Surface loaded") : tr("Surface fetch failed"), r.success);
if (!r.success)
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp
index 91405141f..e40cb25d4 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceAnalyticsScreen_Views.cpp
@@ -54,6 +54,10 @@ void SurfaceAnalyticsScreen::refresh_surface_bar() {
// ── Data loading ─────────────────────────────────────────────────────────────
void SurfaceAnalyticsScreen::load_demo_data() {
+ // This fills every surface with rand() sample data — tell the badge so it shows
+ // DEMO instead of the surface's LIVE/COMPUTED capability tier.
+ if (control_panel_)
+ control_panel_->mark_synthetic(true);
QString qsym = current_symbol_or_default();
std::string sym = qsym.toStdString();
float spot = spot_for(qsym);
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp
index 53f6219b1..654e25695 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.cpp
@@ -503,13 +503,23 @@ void SurfaceControlPanel::prefill_datasets() {
dataset_combo_->blockSignals(false);
}
+void SurfaceControlPanel::mark_synthetic(bool on) {
+ if (synthetic_ == on)
+ return;
+ synthetic_ = on;
+ set_capability(active_type_); // re-apply the badge with the new real/synthetic state
+}
+
void SurfaceControlPanel::set_capability(ChartType type) {
active_type_ = type;
const auto& cap = capability_for(type);
- // Tier badge
- QColor bg = tier_color(cap.tier);
- tier_badge_->setText(tier_name(cap.tier));
+ // Tier badge — when the displayed data is synthetic (demo/refresh with no real
+ // fetch) show DEMO regardless of the surface's *capability* tier, otherwise the
+ // rand() sample data reads as live/COMPUTED market data.
+ const SurfaceTier shown_tier = synthetic_ ? SurfaceTier::DEMO : cap.tier;
+ QColor bg = tier_color(shown_tier);
+ tier_badge_->setText(tier_name(shown_tier));
tier_badge_->setStyleSheet(
QString("background:%1; color:#000; font-size:9px; font-weight:bold; "
"padding:2px 6px; border-radius:2px; max-width:80px;")
diff --git a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h
index abef06d75..d147c2171 100644
--- a/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h
+++ b/fincept-qt/src/screens/surface_analytics/SurfaceControlPanel.h
@@ -54,6 +54,10 @@ class SurfaceControlPanel : public QWidget {
// Re-render sections to match the active surface's capability profile.
// Called by the screen on every chip click.
void set_capability(ChartType type);
+ /// Mark the currently-displayed data as synthetic (demo) or real (fetched). When
+ /// synthetic, the tier badge shows DEMO regardless of the surface's capability tier,
+ /// so rand() sample data never reads as live/COMPUTED market data.
+ void mark_synthetic(bool on);
// Push min/max/mean/median/std/skew/kurt of the active surface's z matrix.
void update_metrics(const std::vector<std::vector<float>>& z, const QString& units = "");
@@ -129,6 +133,7 @@ class SurfaceControlPanel : public QWidget {
QLabel* dataset_lbl_ = nullptr; // "Dataset:" (cached for retranslateUi)
QLabel* spot_label_ = nullptr;
QLabel* tier_badge_ = nullptr;
+ bool synthetic_ = false; // true while the displayed surface is demo/sample data
// ── Static field labels (cached for retranslateUi) ──────────────────────
QLabel* start_lbl_ = nullptr;
diff --git a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp
index 7d11ac168..3ab9de2c9 100644
--- a/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp
+++ b/fincept-qt/src/screens/trade_viz/TradeVizScreen.cpp
@@ -93,6 +93,22 @@ class TradeFlowChordWidget : public QWidget {
const int h = height();
const int cx = w / 2;
const int cy = h / 2;
+
+ // ── Honest provenance note ───────────────────────────────────────────
+ // This chord is rendered from a static, compile-time bilateral-trade
+ // table (g_partners[]), NOT a live feed. Label it so the visualization
+ // is never mistaken for real-time data.
+ {
+ QFont nf(FONT, 8);
+ nf.setBold(true);
+ p.setFont(nf);
+ p.setPen(QColor(ui::colors::AMBER()));
+ p.drawText(QRect(10, 6, w - 20, 16), Qt::AlignLeft | Qt::AlignTop,
+ QCoreApplication::translate(
+ "TradeFlowChordWidget",
+ "Illustrative — US bilateral trade, 2024 estimates (static)"));
+ }
+
const int radius = std::min(cx, cy) - 65;
if (radius < 60)
return;
diff --git a/fincept-qt/src/services/agents/AgentService.h b/fincept-qt/src/services/agents/AgentService.h
index 27d1cac32..231494400 100644
--- a/fincept-qt/src/services/agents/AgentService.h
+++ b/fincept-qt/src/services/agents/AgentService.h
@@ -72,6 +72,8 @@ class AgentService : public QObject
QString resume_task(const QString& task_id);
QString pause_task(const QString& task_id);
QString cancel_task(const QString& task_id);
+ /// Permanently remove a task record (cancel only signals a running task to stop).
+ QString delete_task(const QString& task_id);
QString list_tasks(const QString& status_filter = {}, int limit = 50);
QString get_task(const QString& task_id);
/// HITL: user replies to a clarifying question persisted on the task row.
diff --git a/fincept-qt/src/services/agents/AgentService_Execution.cpp b/fincept-qt/src/services/agents/AgentService_Execution.cpp
index 293c76151..538a5fa2e 100644
--- a/fincept-qt/src/services/agents/AgentService_Execution.cpp
+++ b/fincept-qt/src/services/agents/AgentService_Execution.cpp
@@ -692,6 +692,16 @@ QString AgentService::schedule_list() {
return req_id;
}
+QString AgentService::delete_task(const QString& task_id) {
+ const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ QJsonObject params;
+ params["task_id"] = task_id;
+ // "delete_task" removes the record via the state manager; "agentic_cancel_task"
+ // only sets a cooperative stop signal and leaves the row behind.
+ run_python_stdin(QStringLiteral("delete_task"), params, {}, [](bool, QJsonObject) {});
+ return req_id;
+}
+
QString AgentService::schedule_delete(const QString& schedule_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
diff --git a/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp b/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp
index c2f132d1b..76fdd48ec 100644
--- a/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp
+++ b/fincept-qt/src/services/alpha_arena/ArenaEngine.cpp
@@ -7,13 +7,23 @@
#include "services/alpha_arena/HyperliquidLiveVenue.h"
#include "storage/secure/SecureStorage.h"
#include <QDateTime>
+#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QPointer>
#include <QUuid>
namespace fincept::arena {
static constexpr const char* TAG = "ArenaEngine";
+static constexpr int kKillMarksTimeoutMs = 2000; // bounded wait; a kill must never hang
+
+static QString approval_summary(const AgentAction& act) {
+ return QStringLiteral("%1 %2 %3 $%4 @%5x")
+ .arg(act.kind == ActionKind::Open ? QStringLiteral("OPEN") : QStringLiteral("CLOSE"),
+ act.side.toUpper(), act.coin, QString::number(act.size_usd, 'f', 0),
+ QString::number(act.leverage, 'f', 0));
+}
ArenaEngine& ArenaEngine::instance() {
static ArenaEngine e;
@@ -115,6 +125,25 @@ Result<void> ArenaEngine::start(const QString& competition_id) {
}
ArenaStore::instance().set_competition_status(competition_id, "running");
emit competition_status_changed(competition_id, "running");
+ // Re-surface HITL approvals persisted by a previous run — a hidden panel or
+ // an app restart must not lose them. resume_after_hitl re-checks agent
+ // status and executes at the venue's CURRENT marks, so an old seq is safe.
+ pending_hitl_.clear();
+ if (auto hitl_r = ArenaStore::instance().hitl_pending_for(competition_id); hitl_r.is_ok())
+ for (const auto& h : hitl_r.value()) {
+ PendingApproval pa;
+ pa.id = h.id;
+ pa.agent_id = h.agent_id;
+ pa.seq = h.round_seq;
+ pa.action.kind = h.kind == QLatin1String("close") ? ActionKind::Close : ActionKind::Open;
+ pa.action.coin = h.coin;
+ pa.action.side = h.side;
+ pa.action.size_usd = h.size_usd;
+ pa.action.leverage = h.leverage;
+ pa.action.reason = h.reason;
+ pending_hitl_.append(pa);
+ emit hitl_requested(pa.id, pa.agent_id, approval_summary(pa.action));
+ }
timer_->start(comp_.cadence_seconds * 1000);
marks_timer_->start(marks_interval_ms_); // between-round live marks
force_round(); // first round immediately
@@ -155,16 +184,42 @@ Result<void> ArenaEngine::stop() {
round_in_flight_ = false;
pending_agents_ = 0;
round_notional_.clear();
- pending_hitl_.clear(); // un-actioned approvals die with the run
+ pending_hitl_.clear(); // in-memory only — persisted rows survive for the next start()
LOG_INFO(TAG, QStringLiteral("competition %1 stopped").arg(id));
return Result<void>::ok();
}
Result<void> ArenaEngine::kill_all() {
if (!venue_) return Result<void>::err("no active competition");
+ timer_->stop(); // no new round may start mid-kill
+ marks_timer_->stop();
+ refresh_marks_blocking(); // close at fresh prices, not last-tick marks
for (const auto& a : agents_) venue_->close_all(a.id, round_seq_);
- ArenaStore::instance().insert_event(active_id_, "", "kill_all", "{}");
- return stop();
+ // Verify the book is actually flat. On a resumed venue whose marks are empty
+ // (crash-recovery reload + a marks refresh that timed out), close_all skips any
+ // position with no mark and leaves it OPEN — surface that instead of a clean ok.
+ int open_left = 0;
+ for (const auto& a : agents_) open_left += venue_->account(a.id).positions.size();
+ // Un-actioned HITL approvals are moot once we've closed out. Resolve them as
+ // rejected orders (auditable, never silently dropped) and drop the persisted
+ // rows so a later restart cannot resurrect them.
+ for (const auto& pa : pending_hitl_) {
+ ArenaStore::instance().delete_hitl_pending(pa.id);
+ reject_approval(pa, QStringLiteral("kill_all"));
+ }
+ pending_hitl_.clear();
+ ArenaStore::instance().insert_event(
+ active_id_, "", "kill_all",
+ open_left ? QStringLiteral("{\"positions_left_open\":%1}").arg(open_left) : QStringLiteral("{}"));
+ auto stopped = stop();
+ if (open_left > 0) {
+ LOG_ERROR(TAG, QStringLiteral("kill_all left %1 position(s) OPEN (no live marks to close at)").arg(open_left));
+ return Result<void>::err(
+ QStringLiteral("Kill incomplete: %1 position(s) could not be closed (no live marks) and remain open.")
+ .arg(open_left)
+ .toStdString());
+ }
+ return stopped;
}
Result<void> ArenaEngine::kill_agent(const QString& agent_id) {
@@ -174,15 +229,18 @@ Result<void> ArenaEngine::kill_agent(const QString& agent_id) {
if (a.id == agent_id) { known = true; break; }
if (!known) return Result<void>::err("unknown agent id");
- const auto closes = venue_->close_all(agent_id, round_seq_);
- for (const auto& o : closes) emit order_executed(o.agent_id, o.id, o.status);
-
+ // Halt FIRST (immediate-halt rule): an LLM callback landing during the
+ // marks refresh below must execute nothing for this agent.
const QString reason = QStringLiteral("killed by user");
ArenaStore::instance().set_agent_status(agent_id, "halted_user", reason);
for (auto& a : agents_)
if (a.id == agent_id) { a.status = "halted_user"; a.halt_reason = reason; }
emit agent_status_changed(agent_id, "halted_user", reason);
+ refresh_marks_blocking(); // close at fresh prices, not last-tick marks
+ const auto closes = venue_->close_all(agent_id, round_seq_);
+ for (const auto& o : closes) emit order_executed(o.agent_id, o.id, o.status);
+
ArenaStore::instance().insert_event(
active_id_, agent_id, "agent_killed",
QString::fromUtf8(QJsonDocument(QJsonObject{{"agent_id", agent_id}, {"round_seq", round_seq_}})
@@ -199,6 +257,17 @@ Result<void> ArenaEngine::kill_agent(const QString& agent_id) {
s.balance = acct.balance;
for (auto it = acct.upnl.begin(); it != acct.upnl.end(); ++it) s.unrealized_pnl += it.value();
ArenaStore::instance().insert_equity_snapshot(s);
+ // If the (post-close) book still holds positions, the marks were missing and
+ // close_all left them OPEN — surface it instead of reporting a clean kill.
+ if (!acct.positions.isEmpty()) {
+ LOG_ERROR(TAG, QStringLiteral("kill_agent %1 left %2 position(s) OPEN (no live marks to close at)")
+ .arg(agent_id)
+ .arg(acct.positions.size()));
+ return Result<void>::err(
+ QStringLiteral("Kill incomplete: %1 position(s) could not be closed (no live marks) and remain open.")
+ .arg(acct.positions.size())
+ .toStdString());
+ }
return Result<void>::ok();
}
@@ -264,6 +333,32 @@ void ArenaEngine::run_marks_tick() {
});
}
+// Kill paths close positions immediately, but the venue's stored marks can be a
+// full marks-interval stale (or missing before the first tick — close_all then
+// leaves such positions open). Run one synchronous marks tick — set_marks plus
+// the mark_all sweep close_all's contract requires — with a bounded wait; on
+// timeout/error fall through and close at the stored marks: a kill never hangs.
+void ArenaEngine::refresh_marks_blocking() {
+ if (!venue_ || !market_) return;
+ QEventLoop loop;
+ QPointer<QEventLoop> alive(&loop); // late (post-timeout) callbacks find it null
+ const quint64 epoch = epoch_;
+ market_->fetch_mids(comp_.instruments, [this, epoch, alive](Result<QHash<QString, double>> r) {
+ if (epoch == epoch_ && venue_ && r.is_ok()) {
+ venue_->set_marks(r.value());
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ const auto liqs = venue_->mark_all(now - last_mark_ts_, round_seq_);
+ last_mark_ts_ = now;
+ for (const auto& o : liqs) emit order_executed(o.agent_id, o.id, o.status);
+ }
+ if (alive) alive->quit();
+ });
+ QTimer::singleShot(kKillMarksTimeoutMs, &loop, &QEventLoop::quit);
+ // ExcludeUserInputEvents: this wait must not deliver clicks — a "New"/resume/
+ // second-kill within these <=2s would re-enter the engine and corrupt the kill.
+ loop.exec(QEventLoop::ExcludeUserInputEvents);
+}
+
void ArenaEngine::run_round() {
if (round_in_flight_ || active_id_.isEmpty()) return;
round_in_flight_ = true;
@@ -464,13 +559,19 @@ void ArenaEngine::finish_agent(int seq, const AgentRow& agent, const ArenaLlmRes
pa.action = act;
pa.seq = seq;
pending_hitl_.append(pa);
- emit hitl_requested(pa.id, agent.id,
- QStringLiteral("%1 %2 %3 $%4 @%5x")
- .arg(act.kind == ActionKind::Open ? QStringLiteral("OPEN")
- : QStringLiteral("CLOSE"),
- act.side.toUpper(), act.coin,
- QString::number(act.size_usd, 'f', 0),
- QString::number(act.leverage, 'f', 0)));
+ HitlPendingRow hp;
+ hp.id = pa.id;
+ hp.competition_id = active_id_;
+ hp.agent_id = agent.id;
+ hp.round_seq = seq;
+ hp.kind = act.kind == ActionKind::Open ? QStringLiteral("open") : QStringLiteral("close");
+ hp.coin = act.coin;
+ hp.side = act.side;
+ hp.size_usd = act.size_usd;
+ hp.leverage = act.leverage;
+ hp.reason = act.reason;
+ ArenaStore::instance().insert_hitl_pending(hp); // survives hidden panel / restart
+ emit hitl_requested(pa.id, agent.id, approval_summary(act));
continue; // executed only after approval
}
if (act.kind == ActionKind::Open) round_notional_[agent.id] += act.size_usd;
@@ -484,39 +585,16 @@ void ArenaEngine::resume_after_hitl(const QString& approval_id, bool approved) {
for (int i = 0; i < pending_hitl_.size(); ++i) {
if (pending_hitl_[i].id != approval_id) continue;
const PendingApproval pa = pending_hitl_.takeAt(i);
+ ArenaStore::instance().delete_hitl_pending(pa.id); // actioned — drop the persisted row
if (!approved) {
- OrderRow rej;
- rej.competition_id = active_id_;
- rej.agent_id = pa.agent_id;
- rej.round_seq = pa.seq;
- rej.coin = pa.action.coin;
- rej.side = pa.action.side;
- rej.action = pa.action.kind == ActionKind::Open ? "open" : "close";
- rej.notional_usd = pa.action.size_usd;
- rej.leverage = pa.action.leverage;
- rej.status = "rejected_risk";
- rej.reject_reason = "HITL rejected";
- auto r = ArenaStore::instance().insert_order(rej);
- emit order_executed(pa.agent_id, r.is_ok() ? r.value() : QString(), rej.status);
+ reject_approval(pa, QStringLiteral("HITL rejected"));
return;
}
if (!venue_) return; // competition stopped between request and decision
if (!agent_is_active(pa.agent_id)) {
// Agent halted between the HITL request and the approval — same
// immediate-halt rule as finish_agent: record, never execute.
- OrderRow rej;
- rej.competition_id = active_id_;
- rej.agent_id = pa.agent_id;
- rej.round_seq = pa.seq;
- rej.coin = pa.action.coin;
- rej.side = pa.action.side;
- rej.action = pa.action.kind == ActionKind::Open ? "open" : "close";
- rej.notional_usd = pa.action.size_usd;
- rej.leverage = pa.action.leverage;
- rej.status = "rejected_risk";
- rej.reject_reason = "agent halted";
- auto r = ArenaStore::instance().insert_order(rej);
- emit order_executed(pa.agent_id, r.is_ok() ? r.value() : QString(), rej.status);
+ reject_approval(pa, QStringLiteral("agent halted"));
return;
}
auto fill = venue_->execute(pa.agent_id, pa.action, pa.seq);
@@ -525,6 +603,24 @@ void ArenaEngine::resume_after_hitl(const QString& approval_id, bool approved) {
}
}
+// Reject one queued HITL action: persist a rejected order row (audit trail —
+// approvals are never silently dropped) and notify listeners.
+void ArenaEngine::reject_approval(const PendingApproval& pa, const QString& reason) {
+ OrderRow rej;
+ rej.competition_id = active_id_;
+ rej.agent_id = pa.agent_id;
+ rej.round_seq = pa.seq;
+ rej.coin = pa.action.coin;
+ rej.side = pa.action.side;
+ rej.action = pa.action.kind == ActionKind::Open ? "open" : "close";
+ rej.notional_usd = pa.action.size_usd;
+ rej.leverage = pa.action.leverage;
+ rej.status = "rejected_risk";
+ rej.reject_reason = reason;
+ auto r = ArenaStore::instance().insert_order(rej);
+ emit order_executed(pa.agent_id, r.is_ok() ? r.value() : QString(), rej.status);
+}
+
void ArenaEngine::record_failure(const AgentRow& agent, const QString& kind) {
for (auto& a : agents_) {
if (a.id != agent.id) continue;
diff --git a/fincept-qt/src/services/alpha_arena/ArenaEngine.h b/fincept-qt/src/services/alpha_arena/ArenaEngine.h
index 3824e6f5e..2f426743e 100644
--- a/fincept-qt/src/services/alpha_arena/ArenaEngine.h
+++ b/fincept-qt/src/services/alpha_arena/ArenaEngine.h
@@ -23,8 +23,8 @@ class ArenaEngine : public QObject {
Result<void> start(const QString& competition_id); // load + begin ticking
Result<void> pause(); // status "paused", timer stops
Result<void> resume(); // status "running"
- Result<void> stop(); // status "ended"; positions stay
- Result<void> kill_all(); // close every position + stop
+ Result<void> stop(); // status "ended"; positions stay; pending HITL rows persist
+ Result<void> kill_all(); // refresh marks, close every position, reject pending HITL + stop
/// Per-agent kill switch: close that agent's positions now, halt it
/// ("halted_user"), snapshot its equity. Competition keeps running.
Result<void> kill_agent(const QString& agent_id);
@@ -36,6 +36,7 @@ class ArenaEngine : public QObject {
/// HITL (live mode): approve/reject a queued action by approval id.
/// Approved actions execute at the venue's CURRENT marks; rejections are
/// persisted as "rejected_risk" orders with reason "HITL rejected".
+ /// Pending approvals persist in the store and re-surface on start().
void resume_after_hitl(const QString& approval_id, bool approved);
// Crash recovery: competitions found "running" at init(); UI can resume or dismiss.
@@ -87,6 +88,8 @@ class ArenaEngine : public QObject {
void record_failure(const AgentRow& agent, const QString& kind);
bool agent_is_active(const QString& agent_id) const; // CURRENT status in agents_
void run_marks_tick(); // between-round live marks
+ void refresh_marks_blocking(); // kill paths: bounded-wait marks
+ // refresh + sweep → close fresh
QString active_id_;
CompetitionRow comp_;
@@ -103,7 +106,9 @@ class ArenaEngine : public QObject {
MarketSnapshot last_snapshot_;
QHash<QString, double> round_notional_; // agent_id → Σ new notional this round
struct PendingApproval { QString id, agent_id; AgentAction action; int seq = 0; };
- QVector<PendingApproval> pending_hitl_; // live mode only; cleared on stop()/kill_all()
+ void reject_approval(const PendingApproval& pa, const QString& reason); // rejected order + signal
+ QVector<PendingApproval> pending_hitl_; // live mode only; mirrors arena_hitl_pending rows
+ // (survive stop(), reload on start; kill_all rejects)
std::unique_ptr<PaperExchange> venue_;
IArenaMarketData* market_ = nullptr; // owned (parent=this)
IArenaLlmClient* llm_ = nullptr; // owned (parent=this)
diff --git a/fincept-qt/src/services/alpha_arena/ArenaStore.cpp b/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
index 93e59c435..671b8e7dd 100644
--- a/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
+++ b/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
@@ -151,6 +151,40 @@ EquitySnapshotRow map_equity(QSqlQuery& q) {
constexpr const char* kEquityCols =
"competition_id, agent_id, round_seq, ts, equity, balance, unrealized_pnl";
+HitlPendingRow map_hitl(QSqlQuery& q) {
+ HitlPendingRow h;
+ h.id = q.value(0).toString();
+ h.competition_id = q.value(1).toString();
+ h.agent_id = q.value(2).toString();
+ h.round_seq = q.value(3).toInt();
+ h.kind = q.value(4).toString();
+ h.coin = q.value(5).toString();
+ h.side = q.value(6).toString();
+ h.size_usd = q.value(7).toDouble();
+ h.leverage = q.value(8).toDouble();
+ h.reason = q.value(9).toString();
+ h.ts = q.value(10).toLongLong();
+ return h;
+}
+constexpr const char* kHitlCols =
+ "id, competition_id, agent_id, round_seq, kind, coin, side, size_usd, leverage, reason, ts";
+
+// arena_hitl_pending postdates migration v050 — create it lazily (same pattern
+// as workflow_audit_log) so existing profiles pick it up without a migration.
+Result<void> ensure_hitl_table() {
+ static bool ready = false;
+ if (ready) return Result<void>::ok();
+ auto r = Database::instance().exec(
+ "CREATE TABLE IF NOT EXISTS arena_hitl_pending ("
+ " id TEXT PRIMARY KEY, competition_id TEXT NOT NULL, agent_id TEXT NOT NULL,"
+ " round_seq INTEGER NOT NULL DEFAULT 0, kind TEXT NOT NULL DEFAULT 'open',"
+ " coin TEXT NOT NULL DEFAULT '', side TEXT NOT NULL DEFAULT '',"
+ " size_usd REAL NOT NULL DEFAULT 0, leverage REAL NOT NULL DEFAULT 1,"
+ " reason TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL DEFAULT 0)");
+ if (r.is_ok()) ready = true;
+ return r;
+}
+
} // namespace
ArenaStore& ArenaStore::instance() {
@@ -211,9 +245,11 @@ Result<void> ArenaStore::set_cadence(const QString& id, int seconds) {
}
Result<void> ArenaStore::delete_competition_cascade(const QString& id) {
+ if (auto hr = ensure_hitl_table(); hr.is_err())
+ return hr;
for (const char* table : {"arena_agents", "arena_rounds", "arena_decisions", "arena_orders",
"arena_positions", "arena_accounts", "arena_equity_snapshots",
- "arena_events"}) {
+ "arena_events", "arena_hitl_pending"}) {
auto r = exec_write(
QStringLiteral("DELETE FROM %1 WHERE competition_id = ?").arg(QLatin1String(table)),
{id});
@@ -494,4 +530,32 @@ Result<QVector<QString>> ArenaStore::recent_events(const QString& competition_id
return Result<QVector<QString>>::ok(std::move(out));
}
+// ── HITL pending approvals ───────────────────────────────────────────────────
+
+Result<void> ArenaStore::insert_hitl_pending(HitlPendingRow h) {
+ if (auto r = ensure_hitl_table(); r.is_err())
+ return r;
+ h.ts = now_millis();
+ return exec_write(
+ "INSERT OR REPLACE INTO arena_hitl_pending (id, competition_id, agent_id, round_seq,"
+ " kind, coin, side, size_usd, leverage, reason, ts) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
+ {h.id, h.competition_id, h.agent_id, h.round_seq, nn(h.kind), nn(h.coin), nn(h.side),
+ h.size_usd, h.leverage, nn(h.reason), h.ts});
+}
+
+Result<void> ArenaStore::delete_hitl_pending(const QString& id) {
+ if (auto r = ensure_hitl_table(); r.is_err())
+ return r;
+ return exec_write("DELETE FROM arena_hitl_pending WHERE id = ?", {id});
+}
+
+Result<QVector<HitlPendingRow>> ArenaStore::hitl_pending_for(const QString& competition_id) {
+ if (auto r = ensure_hitl_table(); r.is_err())
+ return Result<QVector<HitlPendingRow>>::err(r.error());
+ return query_list_as<HitlPendingRow>(
+ QStringLiteral("SELECT %1 FROM arena_hitl_pending WHERE competition_id = ? ORDER BY ts ASC")
+ .arg(kHitlCols),
+ {competition_id}, map_hitl);
+}
+
} // namespace fincept::arena
diff --git a/fincept-qt/src/services/alpha_arena/ArenaStore.h b/fincept-qt/src/services/alpha_arena/ArenaStore.h
index 124da637c..6dc6f1100 100644
--- a/fincept-qt/src/services/alpha_arena/ArenaStore.h
+++ b/fincept-qt/src/services/alpha_arena/ArenaStore.h
@@ -7,6 +7,15 @@
namespace fincept::arena {
+/// One queued HITL approval (live mode): a parsed action awaiting a human
+/// decision. Persisted so a hidden panel or an app restart cannot lose it.
+struct HitlPendingRow {
+ QString id, competition_id, agent_id, kind, coin, side, reason; // kind: "open" | "close"
+ int round_seq = 0;
+ double size_usd = 0, leverage = 1;
+ qint64 ts = 0;
+};
+
class ArenaStore : public BaseRepository<CompetitionRow> {
public:
static ArenaStore& instance();
@@ -55,6 +64,12 @@ class ArenaStore : public BaseRepository<CompetitionRow> {
Result<void> insert_event(const QString& competition_id, const QString& agent_id,
const QString& type, const QString& payload_json);
Result<QVector<QString>> recent_events(const QString& competition_id, int limit); // "ts|agent|type|payload"
+
+ // HITL pending approvals (live mode). arena_hitl_pending is store-managed
+ // (created lazily, no migration); rows survive stop()/restart until actioned.
+ Result<void> insert_hitl_pending(HitlPendingRow h); // fills ts (id = approval id)
+ Result<void> delete_hitl_pending(const QString& id);
+ Result<QVector<HitlPendingRow>> hitl_pending_for(const QString& competition_id); // oldest-first
};
} // namespace fincept::arena
diff --git a/fincept-qt/src/services/gov_data/GovDataService.cpp b/fincept-qt/src/services/gov_data/GovDataService.cpp
index 295e21e35..b6b5d7ef9 100644
--- a/fincept-qt/src/services/gov_data/GovDataService.cpp
+++ b/fincept-qt/src/services/gov_data/GovDataService.cpp
@@ -36,15 +36,12 @@ static const QVector<GovProviderInfo> kProviders = {
{"openafrica", "openAFRICA", "openAFRICA Open Data Portal",
"African open data from organizations across the continent", "#F59E0B", "Africa", "AF",
- "canada_gov_api.py"}, // Uses CKAN pattern
-
- // Spain is served via the generic CKAN client for now. A native datos.gob.es
- // client (scripts/spain_data.py) exists but exposes a different CLI/response
- // contract (catalogues vs publishers, page-based datasets); align it to the
- // GovDataProviderPanel contract + validate against the live portal before
- // switching the script below.
- {"spain", "Spain Open Data", "datos.gob.es", "Spanish government open data portal", "#DC2626", "Spain", "ES",
- "canada_gov_api.py"},
+ "openafrica_api.py"}, // native openAFRICA CKAN client (open.africa) — was wrongly canada_gov_api.py
+
+ // NOTE: Spain (datos.gob.es) was REMOVED — it was mis-wired to canada_gov_api.py and
+ // served CANADIAN datasets under the Spanish flag (a data-provenance bug). datos.gob.es
+ // is not a CKAN portal; re-add once scripts/spain_data.py is aligned to the
+ // GovDataProviderPanel CLI/response contract and validated against the live portal.
{"universal-ckan", "CKAN Portals", "Universal CKAN Open Data Portals",
"8 CKAN portals: US, UK, Australia, Italy, Brazil & more", "#10B981", "Multi-Country", "CKAN", "datagovuk_api.py"},
diff --git a/fincept-qt/src/services/llm/LlmModelsApi.cpp b/fincept-qt/src/services/llm/LlmModelsApi.cpp
index b178de43f..dff6b2c02 100644
--- a/fincept-qt/src/services/llm/LlmModelsApi.cpp
+++ b/fincept-qt/src/services/llm/LlmModelsApi.cpp
@@ -2,6 +2,7 @@
#include "services/llm/LlmService.h"
+#include "services/llm/ProviderCatalog.h"
#include "auth/AuthManager.h"
#include "core/config/AppConfig.h"
#include "core/logging/Logger.h"
@@ -29,6 +30,11 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
Q_UNUSED(api_key) // Auth in headers, not URL.
const QString p = provider.toLower();
+ // Blocked provider (AtlasCloud, removed) — no models URL, so the Fetch button
+ // can never reach it even if base_url was hand-pointed at the host.
+ if (ProviderCatalog::is_blocked(p, base_url))
+ return {};
+
// Ollama uses /api/tags, not /v1/models — must short-circuit before the custom-base_url branch
// or a user with base_url=http://localhost:11434 hits the wrong path and parses a 404 page.
if (p == "ollama") {
@@ -70,7 +76,6 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
if (p == "xai") return "https://api.x.ai/v1/models";
if (p == "kimi") return "https://api.moonshot.ai/v1/models";
if (p == "aihubmix") return "https://aihubmix.com/v1/models"; // fallback if prefilled base_url was cleared
- if (p == "atlascloud") return "https://api.atlascloud.ai/v1/models"; // fallback if prefilled base_url was cleared
if (p == "fincept") return fincept::AppConfig::instance().api_base_url() + "/research/llm/models";
// minimax has no public /v1/models — caller falls back to known models.
return {};
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index b7ca008cc..707558996 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -5,6 +5,7 @@
#include "services/llm/LlmContentExtractors.h"
#include "services/llm/LlmRequestPolicy.h"
#include "services/llm/ModelCatalog.h"
+#include "services/llm/ProviderCatalog.h"
#include "auth/AuthManager.h"
#include "core/logging/Logger.h"
@@ -284,6 +285,9 @@ bool LlmService::is_configured() const {
ensure_config();
if (provider_.isEmpty())
return false;
+ // Blocked provider (AtlasCloud, removed) is never considered configured.
+ if (ProviderCatalog::is_blocked(provider_, base_url_))
+ return false;
if (provider_requires_api_key(provider_))
return !api_key_.isEmpty();
return true;
@@ -330,6 +334,13 @@ QString LlmService::get_endpoint_url() const {
// Called with mutex_ held.
const QString& p = provider_;
+ // Blocked provider (AtlasCloud, removed) — refuse to resolve any endpoint,
+ // including a base_url that was hand-pointed at the host. do_request /
+ // do_streaming_request already block earlier with a clear message; this is
+ // the last-line backstop for any other caller.
+ if (ProviderCatalog::is_blocked(p, base_url_))
+ return {};
+
// Fincept sync chat endpoint (async lives in fincept_async_request).
if (p == "fincept") {
return fincept::AppConfig::instance().api_base_url() + "/research/chat";
@@ -379,9 +390,6 @@ QString LlmService::get_endpoint_url() const {
// Fallback for when the prefilled base_url was cleared; the custom-base_url
// branch above wins whenever it's set (incl. regional/proxy overrides).
return "https://aihubmix.com/v1/chat/completions";
- if (p == "atlascloud")
- // Fallback if the prefilled base_url was cleared; custom-base_url branch wins otherwise.
- return "https://api.atlascloud.ai/v1/chat/completions";
return {};
}
@@ -422,6 +430,11 @@ QMap<QString, QString> LlmService::get_headers() const {
LlmResponse LlmService::do_request(const QString& user_message, const std::vector<ConversationMessage>& history) {
LlmResponse resp;
+ if (ProviderCatalog::is_blocked(provider_, base_url_)) {
+ resp.error = "AtlasCloud has been banned by Fincept and cannot be used.";
+ return resp;
+ }
+
QString url = get_endpoint_url();
if (url.isEmpty()) {
resp.error = "No endpoint URL for provider: " + provider_;
@@ -795,6 +808,12 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
}
LlmResponse resp;
+ if (ProviderCatalog::is_blocked(provider_, base_url_)) {
+ resp.error = "AtlasCloud has been banned by Fincept and cannot be used.";
+ on_chunk("", true);
+ return resp;
+ }
+
QString url = get_endpoint_url();
if (url.isEmpty()) {
resp.error = "No endpoint URL for provider: " + provider_;
@@ -1097,6 +1116,13 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
LlmResponse LlmService::chat(const QString& user_message, const std::vector<ConversationMessage>& history,
bool use_tools) {
+ // INTERIM serialization guard (see request_serialize_mutex_): held until return
+ // because do_request() reads provider_/api_key_/base_url_/model_ lock-free across
+ // the network call — a concurrent chat()/chat_streaming() worker rewriting them
+ // mid-flight could send one provider's API key to another provider's base_url.
+ // We run on a background thread, so this serializes LLM workers, not the UI.
+ // Proper fix (deferred): thread a per-request config context through do_request.
+ QMutexLocker request_lock(&request_serialize_mutex_);
{
QMutexLocker lock(&mutex_);
ensure_config();
@@ -1104,9 +1130,9 @@ LlmResponse LlmService::chat(const QString& user_message, const std::vector<Conv
return LlmResponse{.content = {}, .error = "No LLM provider configured"};
}
// Helpers read members directly. ensure_config() already wrote them under
- // mutex; we release before the blocking network call to avoid serialising
- // concurrent chats. Reassigning a local snapshot back to the members after
- // unlocking would clobber any reload_config() that landed in the gap.
+ // mutex_, and request_lock keeps other workers from rewriting them before we
+ // return. Reassigning a local snapshot back to the members after unlocking
+ // mutex_ would clobber any reload_config() that landed in the gap.
// thread_local guard avoids racing with concurrent chat_streaming calls from the floating bubble.
detail::ToolPolicyGuard guard(use_tools ? ToolPolicy::All : ToolPolicy::None);
@@ -1185,6 +1211,15 @@ void LlmService::chat_streaming(const QString& user_message, const std::vector<C
if (!self)
return;
+ // INTERIM serialization guard (see request_serialize_mutex_): held until
+ // this worker finishes so a concurrent chat()/chat_streaming() worker
+ // can't rewrite the shared provider/key/url/model members below while
+ // do_streaming_request() reads them lock-free — that could send one
+ // provider's API key to another provider's base_url. QtConcurrent thread
+ // only; the UI is never blocked. Proper fix (deferred): thread a
+ // per-request config context through do_streaming_request.
+ QMutexLocker request_lock(&self->request_serialize_mutex_);
+
// Snapshot under mutex so do_*_request see consistent state and don't race with reload_config().
{
QMutexLocker lock(&self->mutex_);
diff --git a/fincept-qt/src/services/llm/LlmService.h b/fincept-qt/src/services/llm/LlmService.h
index fa73f395b..03d3fe295 100644
--- a/fincept-qt/src/services/llm/LlmService.h
+++ b/fincept-qt/src/services/llm/LlmService.h
@@ -24,8 +24,7 @@ inline bool provider_supports_streaming(const QString& provider) {
return provider == "openai" || provider == "anthropic" || provider == "gemini" || provider == "google" ||
provider == "groq" || provider == "deepseek" || provider == "openrouter" || provider == "minimax" ||
provider == "kimi" || provider == "ollama" || provider == "xai" || provider == "fincept" ||
- provider == "astraflow" || provider == "astraflow_cn" || provider == "aihubmix" ||
- provider == "atlascloud";
+ provider == "astraflow" || provider == "astraflow_cn" || provider == "aihubmix";
}
inline bool provider_requires_api_key(const QString& provider) {
@@ -122,6 +121,16 @@ class LlmService : public QObject {
mutable QMutex mutex_;
+ // INTERIM serialization guard: held for the WHOLE duration of each LLM request
+ // (chat() and the chat_streaming() worker) because do_request/do_streaming_request
+ // read provider_/api_key_/base_url_/model_ lock-free across the network call — a
+ // concurrent worker rewriting them mid-flight could send one provider's API key
+ // to another provider's base_url. Only ever acquired on worker threads (never the
+ // UI thread), and always BEFORE mutex_, never while holding it. Proper fix
+ // (deferred): thread a per-request config context through do_*_request instead
+ // of reading shared members.
+ QMutex request_serialize_mutex_;
+
// Lazily reloaded; mutable so const accessors can call ensure_config().
mutable QString provider_;
mutable QString api_key_;
diff --git a/fincept-qt/src/services/llm/ModelCatalog.cpp b/fincept-qt/src/services/llm/ModelCatalog.cpp
index 5883b096c..2b7b1a819 100644
--- a/fincept-qt/src/services/llm/ModelCatalog.cpp
+++ b/fincept-qt/src/services/llm/ModelCatalog.cpp
@@ -159,12 +159,6 @@ const CatalogEntry kCatalog[] = {
// (user max_tokens still applies).
{"aihubmix", "*", kNoPublishedCap},
- // ── AtlasCloud (OpenAI-compatible aggregator) ───────────────────────────
- // https://www.atlascloud.ai/docs/models/llm — serves 300+ open models
- // (DeepSeek, Qwen, GLM, Kimi, MiniMax, Llama, ...); per-model cap varies and
- // can't be derived from the id, so use a generous default (user max_tokens applies).
- {"atlascloud", "*", kNoPublishedCap},
-
// ── Fincept (proxies upstream) ──────────────────────────────────────
// Fincept's /research/llm/async wraps various upstream models. We
// don't know which one is selected server-side, so go with a generous
diff --git a/fincept-qt/src/services/llm/ProviderCatalog.cpp b/fincept-qt/src/services/llm/ProviderCatalog.cpp
index dd46c62bd..f08e5dcdf 100644
--- a/fincept-qt/src/services/llm/ProviderCatalog.cpp
+++ b/fincept-qt/src/services/llm/ProviderCatalog.cpp
@@ -12,17 +12,27 @@ namespace fincept::ai_chat {
const QStringList& ProviderCatalog::known_providers() {
static const QStringList kProviders = {"openai", "anthropic", "gemini", "groq", "deepseek",
"openrouter", "minimax", "kimi", "ollama", "xai", "fincept",
- "astraflow", "astraflow_cn", "aihubmix", "atlascloud"};
+ "astraflow", "astraflow_cn", "aihubmix"};
return kProviders;
}
+// AtlasCloud is banned by Fincept and has been removed as a provider. This hard
+// block ensures it stays unreachable even if someone re-adds "atlascloud" to a
+// config row by hand or points an OpenAI-compatible provider's base_url at
+// api.atlascloud.ai.
+bool ProviderCatalog::is_blocked(const QString& provider, const QString& base_url) {
+ if (provider.toLower() == "atlascloud")
+ return true;
+ return base_url.toLower().contains(QStringLiteral("atlascloud"));
+}
+
QString ProviderCatalog::display_name(const QString& provider_id) {
static const QHash<QString, QString> kNames = {
{"openai", "OpenAI"}, {"anthropic", "Anthropic"}, {"gemini", "Gemini"},
{"groq", "Groq"}, {"deepseek", "DeepSeek"}, {"openrouter", "OpenRouter"},
{"minimax", "MiniMax"}, {"kimi", "Kimi"}, {"ollama", "Ollama"},
{"xai", "xAI"}, {"fincept", "Fincept LLM (recommended)"}, {"astraflow", "AstraFlow"},
- {"astraflow_cn", "AstraFlow CN"}, {"aihubmix", "AIHubMix"}, {"atlascloud", "AtlasCloud"},
+ {"astraflow_cn", "AstraFlow CN"}, {"aihubmix", "AIHubMix"},
};
const QString id = provider_id.toLower();
const auto it = kNames.find(id);
@@ -66,8 +76,6 @@ QString ProviderCatalog::default_base_url(const QString& provider) {
return "https://api.modelverse.cn/v1"; // Astraflow China endpoint (UCloud)
if (p == "aihubmix")
return "https://aihubmix.com/v1"; // AIHubMix — OpenAI-compatible aggregator (500+ models)
- if (p == "atlascloud")
- return "https://api.atlascloud.ai/v1"; // AtlasCloud — OpenAI-compatible aggregator (300+ open models)
return {};
}
@@ -76,8 +84,9 @@ QStringList ProviderCatalog::fallback_models(const QString& provider) {
if (p == "openai")
return {"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o3-mini"};
if (p == "anthropic")
- return {"claude-sonnet-4-5-20250514", "claude-opus-4-5", "claude-3-5-sonnet-20241022",
- "claude-3-haiku-20240307"};
+ // Current, valid Anthropic model ids (a bad snapshot 404s on first chat).
+ return {"claude-opus-4-8", "claude-sonnet-5", "claude-sonnet-4-5-20250929",
+ "claude-opus-4-5-20251101", "claude-haiku-4-5"};
if (p == "gemini")
return {"gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"};
if (p == "groq")
@@ -127,16 +136,6 @@ QStringList ProviderCatalog::fallback_models(const QString& provider) {
"gemini-2.5-flash", "gemini-2.5-pro",
"deepseek-chat", "deepseek-reasoner",
"qwen-max", "qwen-plus", "grok-4"};
- if (p == "atlascloud")
- // AtlasCloud — OpenAI-compatible aggregator (300+ models). Model ids are
- // HuggingFace-style "org/model" strings (NOT short aliases). Note: a few ids
- // listed by /v1/models are unprovisioned and return 400 (e.g. google/gemini-2.0-flash,
- // openai/gpt-4o*). The list below is a verified-working starter set; use the
- // Fetch button for the full live catalog (/v1/models).
- return {"deepseek-ai/DeepSeek-V3.1", "deepseek-ai/deepseek-r1-0528",
- "qwen/qwen3-32b", "Qwen/Qwen3-235B-A22B-Instruct-2507",
- "zai-org/GLM-4.6", "moonshotai/Kimi-K2-Instruct", "MiniMaxAI/MiniMax-M2",
- "google/gemini-2.5-flash", "anthropic/claude-haiku-4.5-20251001"};
return {};
}
@@ -156,7 +155,7 @@ QString ProviderCatalog::brand_color(const QString& provider) {
{"groq", "#F55036"}, {"deepseek", "#4D6BFE"}, {"openrouter", "#8B5CF6"},
{"minimax", "#FF4D6A"}, {"kimi", "#16D9C4"}, {"ollama", "#9CA3AF"},
{"xai", "#E7E9EA"}, {"fincept", "#FF8800"}, {"astraflow", "#38BDF8"},
- {"astraflow_cn", "#38BDF8"}, {"aihubmix", "#F59E0B"}, {"atlascloud", "#34D399"},
+ {"astraflow_cn", "#38BDF8"}, {"aihubmix", "#F59E0B"},
};
const auto it = kColors.find(provider.toLower());
if (it != kColors.end()) return it.value();
diff --git a/fincept-qt/src/services/llm/ProviderCatalog.h b/fincept-qt/src/services/llm/ProviderCatalog.h
index 0c03f34e3..74a0091da 100644
--- a/fincept-qt/src/services/llm/ProviderCatalog.h
+++ b/fincept-qt/src/services/llm/ProviderCatalog.h
@@ -13,6 +13,11 @@ namespace fincept::ai_chat {
class ProviderCatalog {
public:
static const QStringList& known_providers();
+ /// Hard block for retired/forbidden providers (currently AtlasCloud). Returns
+ /// true for the blocked provider id AND for any base_url pointing at its host,
+ /// so it can't be reached even by manually pointing an OpenAI-compatible
+ /// provider at the endpoint. Enforced at every request chokepoint in LlmService.
+ static bool is_blocked(const QString& provider, const QString& base_url = {});
static QString display_name(const QString& provider_id);
static QStringList fallback_models(const QString& provider);
static QString default_base_url(const QString& provider);
diff --git a/fincept-qt/src/services/updater/UpdateService.cpp b/fincept-qt/src/services/updater/UpdateService.cpp
index 6807489b3..8adc062e7 100644
--- a/fincept-qt/src/services/updater/UpdateService.cpp
+++ b/fincept-qt/src/services/updater/UpdateService.cpp
@@ -407,7 +407,14 @@ void UpdateService::launch_installer(const QString& path) {
// startDetached is the right call here — we want the installer to outlive
// this process so the user can restart and finish installation.
+#ifdef Q_OS_MACOS
+ // The macOS release asset is a .dmg, which is NOT executable — startDetached(path)
+ // always fails on it and silently drops to reveal-in-Finder. `open` mounts the dmg
+ // (or launches a .pkg) so the user can actually complete the install.
+ const bool started = QProcess::startDetached(QStringLiteral("/usr/bin/open"), {path});
+#else
const bool started = QProcess::startDetached(path, {});
+#endif
if (!started) {
LOG_WARN("UpdateService", "startDetached failed — falling back to reveal-in-file-manager");
reveal_in_file_manager(path);
diff --git a/fincept-qt/src/trading/ActionCenter.cpp b/fincept-qt/src/trading/ActionCenter.cpp
index d661073f4..488d6c879 100644
--- a/fincept-qt/src/trading/ActionCenter.cpp
+++ b/fincept-qt/src/trading/ActionCenter.cpp
@@ -5,6 +5,7 @@
#include "storage/repositories/SettingsRepository.h"
#include "storage/sqlite/Database.h"
#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
#include "trading/TradingEvents.h"
#include "trading/UnifiedTrading.h"
@@ -325,12 +326,11 @@ ActionCenter::Stats ActionCenter::get_stats(const QString& account_id) const {
QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString& err) {
ok = false;
- if (po.order_type == "placeorder" || po.order_type == "smartorder" ||
- po.order_type == "placegttorder") {
- // Smart/GTT collapse to a standard place via UnifiedTrading for now —
- // the serialized order carries the same fields. (place_smart_order /
- // GTT-specific routing can be wired here later without changing the
- // queue/approve contract.)
+ if (po.order_type == "placeorder" || po.order_type == "smartorder") {
+ // Smart collapses to a standard place via UnifiedTrading for now —
+ // the serialized order carries the same fields. (place_smart_order
+ // routing can be wired here later without changing the queue/approve
+ // contract.)
UnifiedOrder order = deserialize_unified_order(po.order_data);
UnifiedOrderResponse resp = UnifiedTrading::instance().place_order(po.account_id, order);
ok = resp.success;
@@ -338,6 +338,57 @@ QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString&
return resp.order_id;
}
+ if (po.order_type == "placegttorder") {
+ // A GTT is a RESTING trigger at the broker — it must NEVER collapse
+ // into an immediate place_order (that fires the order right away).
+ // Route to the broker's native GTT API; when the account has no GTT
+ // path, fail loudly so the user is not misled into an instant fill.
+ auto account = AccountManager::instance().get_account(po.account_id);
+ if (account.account_id.isEmpty()) {
+ err = "Account not found: " + po.account_id;
+ return {};
+ }
+ if (account.trading_mode == "paper") {
+ err = "GTT not supported for paper accounts";
+ return {};
+ }
+ auto* broker = BrokerRegistry::instance().get(account.broker_id);
+ if (!broker) {
+ err = "Broker not found: " + account.broker_id;
+ return {};
+ }
+ const UnifiedOrder base = deserialize_unified_order(po.order_data);
+ if (base.stop_price <= 0.0) {
+ err = "GTT order missing trigger_price";
+ return {};
+ }
+ GttOrder gtt;
+ gtt.symbol = base.symbol;
+ gtt.exchange = base.exchange;
+ gtt.type = GttOrderType::Single;
+ gtt.last_price = po.order_data.value("last_price").toDouble();
+ GttTrigger trig;
+ trig.trigger_price = base.stop_price; // deserialize maps trigger_price/stop_price here
+ trig.limit_price = base.price;
+ trig.quantity = base.quantity;
+ trig.side = base.side;
+ // GTT legs are Market or Limit only: SL-M fires at market on trigger,
+ // Limit / SL carry their limit price.
+ trig.order_type = (base.order_type == OrderType::Market || base.order_type == OrderType::StopLoss)
+ ? OrderType::Market
+ : OrderType::Limit;
+ trig.product = base.product_type;
+ gtt.triggers.append(trig);
+
+ const auto creds = AccountManager::instance().load_credentials(po.account_id);
+ // Brokers without a gtt_place override return the base-class
+ // "GTT not supported for this broker" — surfaced as a rejection.
+ const GttPlaceResponse resp = broker->gtt_place(creds, gtt);
+ ok = resp.success;
+ err = resp.error;
+ return resp.gtt_id;
+ }
+
if (po.order_type == "basketorder") {
BasketOrderRequest basket;
basket.strategy_name = po.order_data.value("strategy").toString();
diff --git a/fincept-qt/src/trading/ActionCenter.h b/fincept-qt/src/trading/ActionCenter.h
index a30fdacfa..2b0e760bd 100644
--- a/fincept-qt/src/trading/ActionCenter.h
+++ b/fincept-qt/src/trading/ActionCenter.h
@@ -139,8 +139,9 @@ class ActionCenter : public QObject {
// Row mapper for the pending_orders table.
static PendingOrder map_row(class QSqlQuery& q);
- // Execute a queued order against UnifiedTrading. Returns the broker order id
- // (empty on failure) and sets `ok`/`err`.
+ // Execute a queued order against UnifiedTrading (placegttorder routes to the
+ // broker's native gtt_place — never an immediate order). Returns the broker
+ // order id / GTT id (empty on failure) and sets `ok`/`err`.
QString execute_pending(const PendingOrder& po, bool& ok, QString& err);
};
diff --git a/fincept-qt/src/trading/ExchangeSession.cpp b/fincept-qt/src/trading/ExchangeSession.cpp
index e98ef05c8..7883a08b5 100644
--- a/fincept-qt/src/trading/ExchangeSession.cpp
+++ b/fincept-qt/src/trading/ExchangeSession.cpp
@@ -21,6 +21,14 @@ namespace fincept::trading {
namespace {
const QString kSessionTag = "ExchangeSession";
+// Bounded auto-restart policy for a WS subprocess that dies unexpectedly.
+// Capped + exponentially backed off so a python script that crashes on start
+// can't spin into a tight respawn loop.
+constexpr int kMaxWsRestartAttempts = 5;
+constexpr int kWsRestartBaseMs = 1000; // first backoff; doubles each attempt
+constexpr int kWsRestartMaxMs = 30000; // backoff ceiling
+constexpr qint64 kWsHealthyRunMs = 60000; // uptime past which a drop earns a fresh budget
+
// SecureStorage keys for per-exchange crypto credentials. Keeping three
// separate keys (rather than one JSON blob) matches the existing `auth`
// module convention and lets operators rotate fields independently.
@@ -263,8 +271,17 @@ bool ExchangeSession::start_ws(const QString& primary_symbol, const QStringList&
.arg(static_cast<int>(err)));
ws_connected_ = false;
});
+ // A clean subprocess exit emits no python "status" line, so ws_connected_
+ // would otherwise stay stale (badge stuck on LIVE). Detect the death here,
+ // drop the flag, and attempt a bounded respawn. stop_ws() disconnects
+ // `this` before a deliberate terminate, so this only fires on unexpected
+ // exits.
+ connect(ws_process_, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
+ [this](int code, QProcess::ExitStatus status) { handle_ws_finished(code, status); });
ws_process_->start(python_path, args);
+ ws_should_run_ = true;
+ ws_uptime_.restart();
LOG_INFO(kSessionTag, QString("WS stream start requested for %1/%2").arg(exchange_id_, primary_symbol));
return true;
}
@@ -279,6 +296,7 @@ void ExchangeSession::stop_ws() {
auto* proc = ws_process_;
ws_process_ = nullptr;
ws_connected_ = false;
+ ws_should_run_ = false; // deliberate stop — suppress the finished-driven respawn
proc->disconnect(this);
proc->terminate();
connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), proc, &QObject::deleteLater);
@@ -288,6 +306,55 @@ void ExchangeSession::stop_ws() {
});
}
+void ExchangeSession::handle_ws_finished(int exit_code, QProcess::ExitStatus status) {
+ ws_connected_ = false;
+ LOG_WARN(kSessionTag, QString("[%1] WS process exited (code=%2, %3)")
+ .arg(exchange_id_)
+ .arg(exit_code)
+ .arg(status == QProcess::CrashExit ? "crash" : "normal"));
+
+ // Reap the finished process object. stop_ws() disconnects `this` before a
+ // deliberate terminate, so reaching here means an *unexpected* exit.
+ if (ws_process_) {
+ ws_process_->deleteLater();
+ ws_process_ = nullptr;
+ }
+
+ if (!ws_should_run_)
+ return; // not supposed to be running — leave it down
+
+ // A stream that ran healthily and only just dropped earns a fresh restart
+ // budget; a fast crash-loop keeps burning the existing one.
+ if (ws_uptime_.isValid() && ws_uptime_.elapsed() >= kWsHealthyRunMs)
+ ws_restart_attempts_ = 0;
+
+ if (ws_restart_attempts_ >= kMaxWsRestartAttempts) {
+ LOG_ERROR(kSessionTag, QString("[%1] WS not restarting — gave up after %2 attempts")
+ .arg(exchange_id_)
+ .arg(ws_restart_attempts_));
+ return;
+ }
+
+ ++ws_restart_attempts_;
+ const int backoff_ms = qMin(kWsRestartBaseMs * (1 << (ws_restart_attempts_ - 1)), kWsRestartMaxMs);
+ LOG_INFO(kSessionTag, QString("[%1] WS restart attempt %2/%3 in %4ms")
+ .arg(exchange_id_)
+ .arg(ws_restart_attempts_)
+ .arg(kMaxWsRestartAttempts)
+ .arg(backoff_ms));
+
+ QPointer<ExchangeSession> self = this;
+ const QString primary = ws_primary_symbol_;
+ const QStringList all = ws_all_symbols_;
+ QTimer::singleShot(backoff_ms, this, [self, primary, all]() {
+ if (!self || !self->ws_should_run_)
+ return;
+ if (self->is_ws_active())
+ return; // already back up (e.g. a manual restart beat us to it)
+ self->start_ws(primary, all);
+ });
+}
+
void ExchangeSession::set_ws_primary_symbol(const QString& symbol) {
{
QMutexLocker lock(&mutex_);
diff --git a/fincept-qt/src/trading/ExchangeSession.h b/fincept-qt/src/trading/ExchangeSession.h
index 4a32dcb0c..2f4ada074 100644
--- a/fincept-qt/src/trading/ExchangeSession.h
+++ b/fincept-qt/src/trading/ExchangeSession.h
@@ -20,6 +20,7 @@
#include "trading/TradingTypes.h"
+#include <QElapsedTimer>
#include <QHash>
#include <QJsonObject>
#include <QMutex>
@@ -126,6 +127,11 @@ class ExchangeSession : public QObject {
void handle_ws_line(const QString& line);
void drain_ws_buffer();
+ /// QProcess::finished handler for the WS subprocess. Clears the connected
+ /// flag (so the polled UI badge drops to OFFLINE) and — if the stream was
+ /// still supposed to be up — schedules a bounded, backed-off respawn.
+ void handle_ws_finished(int exit_code, QProcess::ExitStatus status);
+
/// Apply the exchange→requested symbol remap (e.g. on Hyperliquid,
/// `BTC/USDC:USDC` → `BTC/USDT`). Returns the input unchanged when no
/// remap is known. Thread-safe — takes the session mutex internally.
@@ -145,6 +151,9 @@ class ExchangeSession : public QObject {
QProcess* ws_process_ = nullptr;
std::atomic<bool> ws_connected_{false};
+ bool ws_should_run_ = false; // true between a successful start_ws() and stop_ws()
+ int ws_restart_attempts_ = 0; // consecutive auto-restarts; reset after a healthy run
+ QElapsedTimer ws_uptime_; // since the current ws_process_ was spawned
QString ws_primary_symbol_;
QStringList ws_all_symbols_;
QHash<QString, QString> ws_symbol_map_; // exchange_symbol → requested_symbol
diff --git a/fincept-qt/src/trading/WebhookListener.cpp b/fincept-qt/src/trading/WebhookListener.cpp
deleted file mode 100644
index af45e99c0..000000000
--- a/fincept-qt/src/trading/WebhookListener.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-#include "trading/WebhookListener.h"
-
-#include "core/logging/Logger.h"
-
-#include <QHostAddress>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QTcpSocket>
-
-namespace fincept::trading {
-
-namespace {
-constexpr const char* WH_TAG = "WebhookListener";
-}
-
-WebhookListener::WebhookListener(QObject* parent) : QObject(parent) {
- server_ = new QTcpServer(this);
- connect(server_, &QTcpServer::newConnection, this, &WebhookListener::handle_new_connection);
-}
-
-WebhookListener::~WebhookListener() {
- stop();
-}
-
-bool WebhookListener::start(quint16 preferred_port) {
- if (server_->isListening())
- return true;
-
- if (!server_->listen(QHostAddress::LocalHost, preferred_port)) {
- // Preferred port busy — fall back to an ephemeral port.
- if (!server_->listen(QHostAddress::LocalHost, 0)) {
- const QString err = server_->errorString();
- LOG_ERROR(WH_TAG, QString("Failed to bind webhook listener: %1").arg(err));
- emit error_occurred(err);
- return false;
- }
- }
- port_ = server_->serverPort();
- LOG_INFO(WH_TAG, QString("Webhook listener on 127.0.0.1:%1").arg(port_));
- return true;
-}
-
-void WebhookListener::stop() {
- if (server_ && server_->isListening())
- server_->close();
- port_ = 0;
-}
-
-bool WebhookListener::is_listening() const {
- return server_ && server_->isListening();
-}
-
-void WebhookListener::handle_new_connection() {
- while (server_->hasPendingConnections()) {
- QTcpSocket* sock = server_->nextPendingConnection();
- connect(sock, &QTcpSocket::readyRead, this, [this, sock]() {
- const QByteArray raw = sock->readAll();
- if (raw.isEmpty())
- return;
-
- QString path;
- QJsonObject body;
- QJsonArray body_array;
- bool is_array = false;
- const bool ok = parse_http_request(raw, path, body, body_array, is_array);
-
- QByteArray response;
- if (!ok) {
- response = http_response(400, "Bad Request: expected JSON body");
- } else {
- route_payload(path, body, body_array, is_array);
- response = http_response(200, "OK");
- }
- sock->write(response);
- sock->flush();
- sock->disconnectFromHost();
- });
- connect(sock, &QTcpSocket::disconnected, sock, &QObject::deleteLater);
- }
-}
-
-bool WebhookListener::parse_http_request(const QByteArray& raw, QString& path, QJsonObject& body,
- QJsonArray& body_array, bool& is_array) {
- // Split headers from body at the blank line.
- const int sep = raw.indexOf("\r\n\r\n");
- if (sep < 0)
- return false;
-
- const QByteArray header_block = raw.left(sep);
- const QByteArray body_block = raw.mid(sep + 4);
-
- // Request line: "POST /tradingview HTTP/1.1"
- const int line_end = header_block.indexOf("\r\n");
- const QByteArray request_line = line_end < 0 ? header_block : header_block.left(line_end);
- const QList<QByteArray> parts = request_line.split(' ');
- if (parts.size() >= 2)
- path = QString::fromUtf8(parts[1]);
-
- if (body_block.trimmed().isEmpty())
- return false;
-
- QJsonParseError perr;
- const QJsonDocument doc = QJsonDocument::fromJson(body_block, &perr);
- if (perr.error != QJsonParseError::NoError)
- return false;
-
- if (doc.isArray()) {
- is_array = true;
- body_array = doc.array();
- return true;
- }
- if (doc.isObject()) {
- is_array = false;
- body = doc.object();
- return true;
- }
- return false;
-}
-
-void WebhookListener::route_payload(const QString& path, const QJsonObject& body,
- const QJsonArray& body_array, bool is_array) {
- const QString p = path.toLower();
-
- // ChartInk scanner alert — carries scan_name + comma-separated "stocks".
- if (p.contains("chartink") || body.contains("stocks") || body.contains("scan_name")) {
- route_chartink(body);
- return;
- }
-
- // TradingView alert(s). Array payloads are treated as multiple alerts.
- auto emit_tv = [this](const QJsonObject& obj) {
- const bool is_smart = obj.contains("position_size");
- emit tradingview_alert(obj, is_smart);
- };
-
- if (is_array) {
- for (const auto& v : body_array) {
- if (v.isObject())
- emit_tv(v.toObject());
- }
- } else {
- emit_tv(body);
- }
-}
-
-void WebhookListener::route_chartink(const QJsonObject& body) {
- // ChartInk webhook format:
- // { "stocks": "SBIN,INFY", "trigger_prices": "500,1450",
- // "scan_name": "Bullish Breakout BUY", "alert_name": "...", "triggered_at": "..." }
- // The action is inferred from a keyword in scan_name.
- const QString scan_name = body.value("scan_name").toString().toUpper();
- QString action;
- if (scan_name.contains("SHORT"))
- action = "SELL";
- else if (scan_name.contains("COVER"))
- action = "BUY";
- else if (scan_name.contains("SELL"))
- action = "SELL";
- else if (scan_name.contains("BUY"))
- action = "BUY";
-
- if (action.isEmpty()) {
- LOG_WARN(WH_TAG, QString("ChartInk alert has no BUY/SELL/SHORT/COVER keyword in scan_name: %1")
- .arg(scan_name));
- emit error_occurred("ChartInk: no action keyword in scan_name");
- return;
- }
-
- const QStringList stocks = body.value("stocks").toString().split(',', Qt::SkipEmptyParts);
- const QStringList prices = body.value("trigger_prices").toString().split(',', Qt::SkipEmptyParts);
-
- for (int i = 0; i < stocks.size(); ++i) {
- QJsonObject alert;
- alert["symbol"] = stocks[i].trimmed();
- alert["exchange"] = "NSE"; // ChartInk is NSE/BSE; default NSE, consumer can remap
- alert["action"] = action;
- if (i < prices.size())
- alert["trigger_price"] = prices[i].trimmed().toDouble();
- alert["scan_name"] = scan_name;
- alert["source"] = "chartink";
- emit chartink_alert(alert);
- }
-}
-
-QByteArray WebhookListener::http_response(int status, const QString& message) {
- const QJsonObject obj{{"status", status == 200 ? "success" : "error"}, {"message", message}};
- const QByteArray json = QJsonDocument(obj).toJson(QJsonDocument::Compact);
- const QString reason = status == 200 ? "OK" : "Bad Request";
- QByteArray resp;
- resp += QString("HTTP/1.1 %1 %2\r\n").arg(status).arg(reason).toUtf8();
- resp += "Content-Type: application/json\r\n";
- resp += QString("Content-Length: %1\r\n").arg(json.size()).toUtf8();
- resp += "Connection: close\r\n\r\n";
- resp += json;
- return resp;
-}
-
-} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/WebhookListener.h b/fincept-qt/src/trading/WebhookListener.h
deleted file mode 100644
index 86e126762..000000000
--- a/fincept-qt/src/trading/WebhookListener.h
+++ /dev/null
@@ -1,64 +0,0 @@
-#pragma once
-// WebhookListener — local loopback HTTP server that receives alert webhooks
-// from external charting platforms (TradingView, ChartInk) and turns them into
-// orders routed through UnifiedTrading.
-//
-// Desktop app: there is no public server, so this binds 127.0.0.1:<port>. To
-// receive alerts from a cloud platform behind NAT, the user tunnels this port
-// (ngrok / cloudflared) — that is out of scope here; we only parse and route.
-//
-// TradingView alert JSON (line alert) → placeorder
-// TradingView alert JSON (strategy) → smartorder (has "position_size")
-// ChartInk scanner alert JSON → placeorder per scanned symbol
-//
-// The listener does NOT place orders itself. It validates + parses the payload
-// and emits a signal; the owner (a screen or a service) decides what to do —
-// route to UnifiedTrading directly, or queue via the Action Center (Phase 3).
-
-#include <QObject>
-#include <QTcpServer>
-#include <QJsonObject>
-
-namespace fincept::trading {
-
-class WebhookListener : public QObject {
- Q_OBJECT
- public:
- explicit WebhookListener(QObject* parent = nullptr);
- ~WebhookListener() override;
-
- // Start listening on 127.0.0.1:preferred_port. Falls back to an ephemeral
- // port if busy; read the actual port via port(). Returns true on success.
- bool start(quint16 preferred_port = 8125);
- void stop();
- bool is_listening() const;
- quint16 port() const { return port_; }
-
- signals:
- // Emitted for a TradingView line/strategy alert. `is_smart` is true when the
- // payload carried "position_size" (strategy alert → smart order).
- void tradingview_alert(const QJsonObject& alert, bool is_smart);
- // Emitted once per scanned symbol from a ChartInk scanner alert.
- void chartink_alert(const QJsonObject& alert);
- void error_occurred(const QString& message);
-
- private slots:
- void handle_new_connection();
-
- private:
- // Parse a raw HTTP request: extract method, path, and JSON body.
- // Returns true and fills `body` if a JSON body was found.
- static bool parse_http_request(const QByteArray& raw, QString& path, QJsonObject& body,
- QJsonArray& body_array, bool& is_array);
-
- void route_payload(const QString& path, const QJsonObject& body,
- const QJsonArray& body_array, bool is_array);
- void route_chartink(const QJsonObject& body);
-
- static QByteArray http_response(int status, const QString& message);
-
- QTcpServer* server_ = nullptr;
- quint16 port_ = 0;
-};
-
-} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp
index a937864bc..eacba89e4 100644
--- a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp
@@ -378,8 +378,9 @@ ApiResponse<QVector<BrokerCandle>> AlpacaBroker::get_history(const BrokerCredent
for (const auto& v : bars_arr) {
auto b = v.toObject();
BrokerCandle c;
- // Parse RFC3339 timestamp string to epoch seconds
- c.timestamp = QDateTime::fromString(b.value("t").toString(), Qt::ISODateWithMs).toSecsSinceEpoch();
+ // Parse RFC3339 timestamp → epoch MILLISECONDS (BrokerCandle.timestamp contract;
+ // seconds here render candles in Jan 1970 on the chart).
+ c.timestamp = QDateTime::fromString(b.value("t").toString(), Qt::ISODateWithMs).toMSecsSinceEpoch();
c.open = b.value("o").toDouble();
c.high = b.value("h").toDouble();
c.low = b.value("l").toDouble();
@@ -463,7 +464,8 @@ static QMap<QString, QString> alpaca_data_headers(const BrokerCredentials& creds
static BrokerCandle parse_bar(const QJsonObject& b, const QString& symbol = {}) {
BrokerCandle c;
Q_UNUSED(symbol);
- c.timestamp = QDateTime::fromString(b.value("t").toString(), Qt::ISODateWithMs).toSecsSinceEpoch();
+ // Epoch MILLISECONDS (BrokerCandle contract); seconds → candles in Jan 1970.
+ c.timestamp = QDateTime::fromString(b.value("t").toString(), Qt::ISODateWithMs).toMSecsSinceEpoch();
c.open = b.value("o").toDouble();
c.high = b.value("h").toDouble();
c.low = b.value("l").toDouble();
diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
index 17da00865..f94f02cc6 100644
--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
@@ -336,6 +336,35 @@ ApiResponse<QJsonObject> DhanBroker::get_trade_book(const BrokerCredentials& cre
return {true, resp.json, "", ts};
}
+// ── LTP hydration ─────────────────────────────────────────────────────────────
+// Positions/holdings responses carry no price field. Batch-fetch last prices via
+// POST /v2/marketfeed/ltp (same endpoint as get_quotes) using the securityIds the
+// rows themselves carry, keyed "<segment>:<securityId>". Best-effort: on any
+// failure the map stays empty and rows keep ltp = 0 (never fabricate prices).
+static QMap<QString, double> fetch_ltp_by_security_id(const QMap<QString, QString>& headers,
+ const QMap<QString, QJsonArray>& ids_by_segment) {
+ QMap<QString, double> ltp_map;
+ if (ids_by_segment.isEmpty())
+ return ltp_map;
+
+ QJsonObject body;
+ for (auto it = ids_by_segment.constBegin(); it != ids_by_segment.constEnd(); ++it)
+ body[it.key()] = it.value();
+
+ auto resp = BrokerHttp::instance().post_json(BASE + "/v2/marketfeed/ltp", body, headers);
+ if (!resp.success || resp.json.value("errorType").toString().length() > 0)
+ return ltp_map;
+
+ // Response: {"data": {"NSE_EQ": {"12345": {"last_price": 500.0}}}}
+ const auto data = resp.json.value("data").toObject();
+ for (auto seg_it = data.constBegin(); seg_it != data.constEnd(); ++seg_it) {
+ const auto tokens = seg_it.value().toObject();
+ for (auto tok_it = tokens.constBegin(); tok_it != tokens.constEnd(); ++tok_it)
+ ltp_map[seg_it.key() + ":" + tok_it.key()] = tok_it.value().toObject().value("last_price").toDouble();
+ }
+ return ltp_map;
+}
+
// ── Get Positions ─────────────────────────────────────────────────────────────
// GET /v2/positions — returns array directly
ApiResponse<QVector<BrokerPosition>> DhanBroker::get_positions(const BrokerCredentials& creds) {
@@ -353,6 +382,8 @@ ApiResponse<QVector<BrokerPosition>> DhanBroker::get_positions(const BrokerCrede
QVector<BrokerPosition> positions;
positions.reserve(arr.size());
+ QVector<QString> ltp_keys; // parallel to positions: "<segment>:<securityId>"
+ QMap<QString, QJsonArray> ids_by_segment;
for (const auto& v : arr) {
auto p = v.toObject();
double qty = p.value("netQty").toDouble();
@@ -371,16 +402,34 @@ ApiResponse<QVector<BrokerPosition>> DhanBroker::get_positions(const BrokerCrede
pos.avg_price = qty > 0 ? buy_avg : sell_avg;
if (pos.avg_price == 0.0) // older deployments do return avgCostPrice
pos.avg_price = p.value("avgCostPrice").toDouble();
- // Positions don't carry an LTP field; callers wanting live MTM must
- // refresh via /v2/marketfeed/ltp. Leave 0 here.
- // TODO: hydrate LTP to populate pnl_pct
+ // Positions don't carry an LTP field — hydrated below via /v2/marketfeed/ltp
+ // using the row's own securityId + exchangeSegment.
pos.ltp = 0.0;
pos.pnl = p.value("unrealizedProfit").toDouble();
pos.day_pnl = p.value("realizedProfit").toDouble();
pos.side = qty > 0 ? "LONG" : "SHORT";
- pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
+ pos.pnl_pct = 0.0;
+ const QString seg = p.value("exchangeSegment").toString();
+ const QString sec_id = p.value("securityId").toVariant().toString();
+ ltp_keys.append(seg + ":" + sec_id);
+ if (!seg.isEmpty() && !sec_id.isEmpty())
+ ids_by_segment[seg].append(sec_id);
positions.append(pos);
}
+
+ // Hydrate live LTP so MTM/pnl_pct aren't silently 0 (best-effort, read-only).
+ const auto ltp_map = fetch_ltp_by_security_id(auth_headers(creds), ids_by_segment);
+ for (int i = 0; i < positions.size(); ++i) {
+ const double ltp = ltp_map.value(ltp_keys.at(i), 0.0);
+ if (ltp <= 0.0)
+ continue;
+ auto& pos = positions[i];
+ pos.ltp = ltp;
+ if (pos.avg_price > 0.0)
+ pos.pnl_pct = ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0;
+ if (pos.pnl == 0.0) // keep broker-reported MTM when present
+ pos.pnl = (pos.ltp - pos.avg_price) * pos.quantity;
+ }
return {true, positions, "", ts};
}
@@ -407,6 +456,8 @@ ApiResponse<QVector<BrokerHolding>> DhanBroker::get_holdings(const BrokerCredent
QVector<BrokerHolding> holdings;
holdings.reserve(arr.size());
+ QVector<QString> ltp_keys; // parallel to holdings: "<segment>:<securityId>"
+ QMap<QString, QJsonArray> ids_by_segment;
for (const auto& v : arr) {
auto h = v.toObject();
BrokerHolding holding;
@@ -414,16 +465,37 @@ ApiResponse<QVector<BrokerHolding>> DhanBroker::get_holdings(const BrokerCredent
holding.exchange = h.value("exchange").toString();
holding.quantity = h.value("totalQty").toDouble();
holding.avg_price = h.value("avgCostPrice").toDouble();
- // /v2/holdings does NOT return an LTP field. Caller must hydrate via
- // /v2/marketfeed/ltp using securityId — leave zero rather than fabricate.
- // TODO: hydrate LTP to populate current_value/pnl
+ // /v2/holdings does NOT return an LTP field — hydrated below via
+ // /v2/marketfeed/ltp using the row's own securityId.
holding.ltp = 0.0;
holding.invested_value = holding.quantity * holding.avg_price;
holding.current_value = 0.0;
holding.pnl = 0.0;
holding.pnl_pct = 0.0;
+ // Holdings carry a plain exchange ("NSE"/"BSE"/"ALL") — quote on the
+ // matching equity segment (dhan_exchange defaults unknowns to NSE_EQ).
+ const QString seg = dhan_exchange(holding.exchange);
+ const QString sec_id = h.value("securityId").toVariant().toString();
+ ltp_keys.append(seg + ":" + sec_id);
+ if (!sec_id.isEmpty())
+ ids_by_segment[seg].append(sec_id);
holdings.append(holding);
}
+
+ // Hydrate live LTP and derive value/P&L — previously left 0, so holdings views
+ // without a live-quote subscription showed ₹0 value/P&L for real positions.
+ const auto ltp_map = fetch_ltp_by_security_id(auth_headers(creds), ids_by_segment);
+ for (int i = 0; i < holdings.size(); ++i) {
+ const double ltp = ltp_map.value(ltp_keys.at(i), 0.0);
+ if (ltp <= 0.0)
+ continue;
+ auto& holding = holdings[i];
+ holding.ltp = ltp;
+ holding.current_value = holding.quantity * ltp;
+ holding.pnl = holding.current_value - holding.invested_value;
+ if (holding.invested_value > 0.0)
+ holding.pnl_pct = (holding.pnl / holding.invested_value) * 100.0;
+ }
return {true, holdings, "", ts};
}
diff --git a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
index c0bfca5b7..f5361e84b 100644
--- a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
+++ b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
@@ -427,16 +427,18 @@ ApiResponse<QVector<BrokerHolding>> FlattradeBroker::get_holdings(const BrokerCr
return {false, std::nullopt, "get_holdings: invalid response", ts};
QVector<BrokerHolding> holdings;
+ QVector<QString> quote_syms; // "EXCH:TSYM:TOKEN" for LTP hydration below
for (const QJsonValue& v : doc.array()) {
QJsonObject o = v.toObject();
- QString symbol, exchange;
+ QString symbol, exchange, token;
QJsonArray exch_tsym = o.value("exch_tsym").toArray();
if (!exch_tsym.isEmpty()) {
QJsonObject et = exch_tsym[0].toObject();
symbol = et.value("tsym").toString();
exchange = et.value("exch").toString();
+ token = et.value("token").toString();
}
if (symbol.isEmpty())
continue;
@@ -456,16 +458,39 @@ ApiResponse<QVector<BrokerHolding>> FlattradeBroker::get_holdings(const BrokerCr
h.exchange = exchange;
h.quantity = total_qty;
h.avg_price = o.value("upldprc").toString().toDouble();
- // Holdings response carries no LTP field — hydrate via GetQuotes for live MTM.
- // TODO: hydrate LTP to populate current_value/pnl
+ // Holdings response carries no LTP field — hydrated below via GetQuotes.
h.ltp = 0.0;
h.invested_value = total_qty * h.avg_price;
h.current_value = 0.0;
h.pnl = 0.0;
h.pnl_pct = 0.0;
+ if (!token.isEmpty())
+ quote_syms.append(exchange + ":" + symbol + ":" + token);
holdings.append(h);
}
+ // Hydrate LTP and derive value/P&L via the existing GetQuotes plumbing (the
+ // exch_tsym rows carry the numeric token it needs). Previously left 0, so
+ // holdings views without a live-quote subscription showed ₹0 for real
+ // positions. Best-effort: on failure rows keep ltp = 0.
+ if (!quote_syms.isEmpty()) {
+ auto quotes = get_quotes(creds, quote_syms);
+ if (quotes.success && quotes.data.has_value()) {
+ for (auto& h : holdings) {
+ for (const auto& q : quotes.data.value()) {
+ if (q.symbol != h.symbol || q.ltp <= 0.0)
+ continue;
+ h.ltp = q.ltp;
+ h.current_value = h.quantity * q.ltp;
+ h.pnl = h.current_value - h.invested_value;
+ if (h.invested_value > 0.0)
+ h.pnl_pct = (h.pnl / h.invested_value) * 100.0;
+ break;
+ }
+ }
+ }
+ }
+
return {true, holdings, "", ts};
}
diff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
index 428489da5..e77641d58 100644
--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
@@ -493,6 +493,7 @@ ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCred
int64_t ts = now_ts();
auto hdrs = auth_headers(creds);
QVector<BrokerPosition> positions;
+ QMap<QString, QVector<SymbolRef>> refs_by_segment; // for LTP hydration below
auto fetch_segment = [&](const QString& segment) -> bool {
QString url = QString("https://api.groww.in/v1/positions/user?segment=%1").arg(segment);
@@ -531,11 +532,18 @@ ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCred
pos.exchange = p["exchange"].toString();
pos.quantity = qty;
pos.avg_price = avg;
- pos.ltp = 0.0; // Not returned by positions endpoint; query live-data/ltp separately if needed.
+ pos.ltp = 0.0; // Not returned by positions endpoint — hydrated below via /live-data/ltp.
pos.pnl = p["realised_pnl"].toDouble();
pos.product_type = p["product"].toString();
- // TODO: hydrate LTP to populate pnl_pct
- pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
+ pos.pnl_pct = 0.0;
+
+ SymbolRef ref;
+ ref.orig = pos.symbol;
+ ref.exchange = pos.exchange.isEmpty() ? QStringLiteral("NSE") : pos.exchange;
+ ref.trading_symbol = pos.symbol;
+ ref.segment = segment;
+ ref.exchange_symbol = groww_exchange(ref.exchange) + "_" + ref.trading_symbol;
+ refs_by_segment[segment].append(ref);
positions.append(pos);
}
return true;
@@ -544,6 +552,24 @@ ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCred
fetch_segment("CASH");
fetch_segment("FNO");
+ // Hydrate LTP — the positions endpoint returns no price, which left value/P&L
+ // silently 0. Batch via the existing /v1/live-data/ltp plumbing (≤50/call).
+ QVector<BrokerQuote> ltp_quotes;
+ for (auto it = refs_by_segment.constBegin(); it != refs_by_segment.constEnd(); ++it)
+ fetch_ltp_batch(creds, it.key(), it.value(), ltp_quotes);
+ for (auto& pos : positions) {
+ for (const auto& q : ltp_quotes) {
+ if (q.symbol != pos.symbol || q.ltp <= 0.0)
+ continue;
+ pos.ltp = q.ltp;
+ if (pos.avg_price > 0.0)
+ pos.pnl_pct = ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0;
+ // realised_pnl (above) misses the open MTM — add the unrealised leg.
+ pos.pnl += (pos.ltp - pos.avg_price) * pos.quantity;
+ break;
+ }
+ }
+
return {true, positions, "", ts};
}
@@ -571,14 +597,42 @@ ApiResponse<QVector<BrokerHolding>> GrowwBroker::get_holdings(const BrokerCreden
holding.quantity = h["quantity"].toInt();
holding.avg_price = h["average_price"].toDouble();
holding.invested_value = holding.quantity * holding.avg_price;
- // TODO: hydrate LTP to populate current_value/pnl
- holding.ltp = 0.0; // Not returned by holdings endpoint; query live-data/ltp separately if needed.
+ holding.ltp = 0.0; // Not returned by holdings endpoint — hydrated below via /live-data/ltp.
holding.current_value = 0.0;
- holding.pnl = 0.0; // Derived value — compute in the service layer once LTP is fetched.
+ holding.pnl = 0.0;
holding.pnl_pct = 0.0;
holdings.append(holding);
}
+ // Hydrate LTP and derive value/P&L — previously left 0, so holdings views
+ // without a live-quote subscription showed ₹0 for real positions. Demat
+ // holdings are equities → CASH segment; batch via /v1/live-data/ltp.
+ QVector<SymbolRef> refs;
+ refs.reserve(holdings.size());
+ for (const auto& h : holdings) {
+ SymbolRef ref;
+ ref.orig = h.symbol;
+ ref.exchange = h.exchange;
+ ref.trading_symbol = h.symbol;
+ ref.segment = QStringLiteral("CASH");
+ ref.exchange_symbol = groww_exchange(ref.exchange) + "_" + ref.trading_symbol;
+ refs.append(ref);
+ }
+ QVector<BrokerQuote> ltp_quotes;
+ fetch_ltp_batch(creds, QStringLiteral("CASH"), refs, ltp_quotes);
+ for (auto& holding : holdings) {
+ for (const auto& q : ltp_quotes) {
+ if (q.symbol != holding.symbol || q.ltp <= 0.0)
+ continue;
+ holding.ltp = q.ltp;
+ holding.current_value = holding.quantity * q.ltp;
+ holding.pnl = holding.current_value - holding.invested_value;
+ if (holding.invested_value > 0.0)
+ holding.pnl_pct = (holding.pnl / holding.invested_value) * 100.0;
+ break;
+ }
+ }
+
return {true, holdings, "", ts};
}
diff --git a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
index e5666b74c..abc435d1c 100644
--- a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
+++ b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
@@ -564,7 +564,7 @@ ApiResponse<QVector<BrokerCandle>> IciciDirectBroker::get_history(const BrokerCr
QDateTime when = QDateTime::fromString(dt, Qt::ISODate);
if (!when.isValid())
when = QDateTime::fromString(dt, "yyyy-MM-dd hh:mm:ss");
- c.timestamp = when.isValid() ? when.toSecsSinceEpoch() : 0;
+ c.timestamp = when.isValid() ? when.toMSecsSinceEpoch() : 0; // BrokerCandle contract = ms
c.open = jnum(o, "open");
c.high = jnum(o, "high");
c.low = jnum(o, "low");
diff --git a/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp b/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
index afaf981c6..80cf66976 100644
--- a/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
+++ b/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
@@ -725,7 +725,7 @@ ApiResponse<QVector<BrokerCandle>> MetaApiBroker::get_history(const BrokerCreden
const QString time_str = c.value("time").toString();
const auto dt = QDateTime::fromString(time_str, Qt::ISODate);
- candle.timestamp = dt.isValid() ? dt.toSecsSinceEpoch() : 0;
+ candle.timestamp = dt.isValid() ? dt.toMSecsSinceEpoch() : 0; // BrokerCandle contract = ms
candle.open = c.value("open").toDouble();
candle.high = c.value("high").toDouble();
@@ -770,7 +770,7 @@ ApiResponse<QVector<BrokerCandle>> MetaApiBroker::get_history(const BrokerCreden
const QString time_str = c.value("time").toString();
const auto dt = QDateTime::fromString(time_str, Qt::ISODate);
- candle.timestamp = dt.isValid() ? dt.toSecsSinceEpoch() : 0;
+ candle.timestamp = dt.isValid() ? dt.toMSecsSinceEpoch() : 0; // BrokerCandle contract = ms
candle.open = c.value("open").toDouble();
candle.high = c.value("high").toDouble();
diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
index d8ebe679f..d813c6e65 100644
--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
@@ -679,7 +679,7 @@ ApiResponse<QVector<BrokerCandle>> MotilalBroker::get_history(const BrokerCreden
continue;
}
BrokerCandle c;
- c.timestamp = d.isValid() ? QDateTime(d, QTime(15, 30)).toSecsSinceEpoch() : 0;
+ c.timestamp = d.isValid() ? QDateTime(d, QTime(15, 30)).toMSecsSinceEpoch() : 0; // BrokerCandle contract = ms
c.open = o.value("open").toDouble();
c.high = o.value("high").toDouble();
c.low = o.value("low").toDouble();
diff --git a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
index bdfa3b2d7..25606689a 100644
--- a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
+++ b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
@@ -6,6 +6,7 @@
#include <QTimeZone>
#include <QJsonArray>
#include <QJsonDocument>
+#include <QRegularExpression>
#include <QUrlQuery>
#include <algorithm>
@@ -52,6 +53,15 @@ bool TradierBroker::is_token_expired(const BrokerHttpResponse& resp) {
return (resp.status_code == 401);
}
+// OCC option symbols: ROOT (1-6 letters) + YYMMDD + C/P + 8-digit strike,
+// e.g. AAPL240119C00150000. Their quotes are per-share while cost_basis (and
+// thus avg_price) bakes the 100x contract multiplier, so P&L math must scale
+// the quoted mark to match.
+static bool is_occ_option(const QString& symbol) {
+ static const QRegularExpression re(QStringLiteral("^[A-Z]{1,6}\\d{6}[CP]\\d{8}$"));
+ return re.match(symbol).hasMatch();
+}
+
QString TradierBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
if (is_token_expired(resp))
return "[TOKEN_EXPIRED] Access token is invalid or expired";
@@ -336,11 +346,37 @@ ApiResponse<QVector<BrokerPosition>> TradierBroker::get_positions(const BrokerCr
// multiplier (cost_basis is the full notional); we do NOT un-bake it here.
pos.avg_price = (qty != 0) ? o.value("cost_basis").toDouble() / qty : 0.0;
pos.side = qty > 0 ? "LONG" : "SHORT";
- // TODO: hydrate LTP for current_value/pnl — the positions endpoint carries no
- // price, so ltp/pnl/pnl_pct stay 0 (do not fabricate prices).
+ // ltp/pnl/pnl_pct hydrated below — the positions endpoint carries no price.
positions.append(pos);
}
+ // Hydrate LTP via the existing /v1/markets/quotes plumbing (read-only,
+ // batched). Without this, views with no live-quote subscription showed $0
+ // value/P&L for real positions. Best-effort: on failure rows keep ltp = 0.
+ if (!positions.isEmpty()) {
+ QVector<QString> syms;
+ syms.reserve(positions.size());
+ for (const auto& p : positions)
+ syms.append(p.symbol);
+ auto quotes = get_quotes(creds, syms);
+ if (quotes.success && quotes.data.has_value()) {
+ for (auto& pos : positions) {
+ for (const auto& q : quotes.data.value()) {
+ if (q.symbol != pos.symbol || q.ltp <= 0.0)
+ continue;
+ pos.ltp = q.ltp;
+ // Scale option marks by the 100x contract multiplier to match
+ // the cost_basis-derived avg_price (see is_occ_option).
+ const double mark = is_occ_option(pos.symbol) ? q.ltp * 100.0 : q.ltp;
+ pos.pnl = (mark - pos.avg_price) * pos.quantity;
+ if (pos.avg_price > 0.0)
+ pos.pnl_pct = ((mark - pos.avg_price) / pos.avg_price) * 100.0;
+ break;
+ }
+ }
+ }
+ }
+
return {true, positions, "", ts};
}
@@ -384,11 +420,37 @@ ApiResponse<QVector<BrokerHolding>> TradierBroker::get_holdings(const BrokerCred
// Prefer the API cost_basis; fall back to qty*avg_price when it's absent.
const double cost_basis = o.value("cost_basis").toDouble();
h.invested_value = (cost_basis != 0.0) ? cost_basis : h.quantity * h.avg_price;
- // TODO: hydrate LTP for current_value/pnl — the positions endpoint carries no
- // price, so ltp/current_value/pnl/pnl_pct stay 0 (do not fabricate prices).
+ // ltp/current_value/pnl hydrated below — the endpoint carries no price.
holdings.append(h);
}
+ // Hydrate LTP and derive value/P&L via the existing /v1/markets/quotes
+ // plumbing (read-only, batched). Best-effort: on failure rows keep ltp = 0.
+ if (!holdings.isEmpty()) {
+ QVector<QString> syms;
+ syms.reserve(holdings.size());
+ for (const auto& h : holdings)
+ syms.append(h.symbol);
+ auto quotes = get_quotes(creds, syms);
+ if (quotes.success && quotes.data.has_value()) {
+ for (auto& h : holdings) {
+ for (const auto& q : quotes.data.value()) {
+ if (q.symbol != h.symbol || q.ltp <= 0.0)
+ continue;
+ h.ltp = q.ltp;
+ // Scale option marks by the 100x contract multiplier so
+ // current_value is on the same basis as cost_basis.
+ const double mark = is_occ_option(h.symbol) ? q.ltp * 100.0 : q.ltp;
+ h.current_value = h.quantity * mark;
+ h.pnl = h.current_value - h.invested_value;
+ if (h.invested_value > 0.0)
+ h.pnl_pct = (h.pnl / h.invested_value) * 100.0;
+ break;
+ }
+ }
+ }
+ }
+
return {true, holdings, "", ts};
}
diff --git a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp
index 445af397a..8535f35be 100644
--- a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp
+++ b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp
@@ -520,15 +520,16 @@ ApiResponse<QVector<BrokerCandle>> UpstoxBroker::get_history(const BrokerCredent
BrokerCandle candle;
// v3 returns ISO8601 string; some endpoints/snapshots return epoch ms.
// Try string first, fall back to numeric.
+ // BrokerCandle.timestamp contract is MILLISECONDS (seconds → candles in Jan 1970).
const QString ts_str = c[0].toString();
if (!ts_str.isEmpty()) {
- candle.timestamp = QDateTime::fromString(ts_str, Qt::ISODate).toSecsSinceEpoch();
+ candle.timestamp = QDateTime::fromString(ts_str, Qt::ISODate).toMSecsSinceEpoch();
if (candle.timestamp == 0)
- candle.timestamp = QDateTime::fromString(ts_str, Qt::ISODateWithMs).toSecsSinceEpoch();
+ candle.timestamp = QDateTime::fromString(ts_str, Qt::ISODateWithMs).toMSecsSinceEpoch();
}
if (candle.timestamp == 0) {
- const qint64 ms = c[0].toVariant().toLongLong();
- candle.timestamp = ms > 1'000'000'000'000LL ? ms / 1000 : ms;
+ const qint64 v = c[0].toVariant().toLongLong();
+ candle.timestamp = v > 1'000'000'000'000LL ? v : v * 1000; // seconds → ms
}
candle.open = c[1].toDouble();
candle.high = c[2].toDouble();
diff --git a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.cpp b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.cpp
index d61d59f04..2bd6327de 100644
--- a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.cpp
+++ b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.cpp
@@ -232,7 +232,13 @@ QByteArray HyperliquidSigner::action_struct_hash(const QJsonObject& action) {
}
bool HyperliquidSigner::is_wired() {
- return true;
+ // The keccak/ECDSA primitives are linked, but the live ORDER path is NOT
+ // production-ready: HyperliquidVenue::place_order still hardcodes the asset id
+ // and rejects every order with "hl_live_path_not_yet_wired", and the signer's
+ // recovery id / EIP-712 domain are not yet known-vector-verified. Report
+ // not-wired so the Alpha Arena live gate refuses to capture (and persist) a
+ // real wallet private key for a path that cannot actually execute a trade.
+ return false;
}
Result<SignedAction> HyperliquidSigner::sign_action(const QJsonObject& action,
diff --git a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.h b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.h
index 495c793ed..e901b5f20 100644
--- a/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.h
+++ b/fincept-qt/src/trading/exchanges/hyperliquid/HyperliquidSigner.h
@@ -1,9 +1,10 @@
#pragma once
// HyperliquidSigner — EIP-712 typed-data signer for Hyperliquid actions.
//
-// STATE (Phase 5c): fully wired. keccak256 (Keccak256.h) + ECDSA over
-// secp256k1 (OpenSSL) + EIP-712 typed data are linked; is_wired() returns true
-// and sign_action() produces a live signature.
+// STATE: the signing primitives (keccak256 + secp256k1 ECDSA + EIP-712 typed
+// data) are linked, but the live ORDER path is NOT production-ready — is_wired()
+// returns false so the Alpha Arena live gate stays closed (no real wallet key is
+// captured) until order placement + signature vectors are verified.
//
// EIP-712 shape (reference):
// struct HyperliquidSignTransaction { name: string, version: string,
diff --git a/fincept-qt/src/ui/navigation/StatusBar.cpp b/fincept-qt/src/ui/navigation/StatusBar.cpp
index f57ab3f87..2c817c7e5 100644
--- a/fincept-qt/src/ui/navigation/StatusBar.cpp
+++ b/fincept-qt/src/ui/navigation/StatusBar.cpp
@@ -25,7 +25,7 @@ StatusBar::StatusBar(QWidget* parent) : QWidget(parent) {
return l;
};
- hl->addWidget(mk("v4.1.0", "sbVersion"));
+ hl->addWidget(mk("v" FINCEPT_VERSION_STRING, "sbVersion"));
hl->addWidget(mk(" | ", "sbSep"));
const char* feeds[] = {"EQ", "FX", "CM", "FI", "CR"};
for (auto& f : feeds) {