FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
version fixed
tilakpatel22696056cf564f
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex 1ef7221b3..72360109d 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -1,5 +1,5 @@cmake_minimum_required(VERSION 3.27)-project(FinceptTerminal VERSION 4.0.2 LANGUAGES CXX)+project(FinceptTerminal VERSION 4.0.1 LANGUAGES CXX)set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)diff --git a/fincept-qt/_build_netspeed.bat b/fincept-qt/_build_netspeed.batnew file mode 100644index 000000000..003367979--- /dev/null+++ b/fincept-qt/_build_netspeed.bat@@ -0,0 +1,4 @@+@echo off+call "C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Auxiliary\Build\vcvars64.bat" >nul+cmake --build --preset win-release 2>&1+exit /b %errorlevel%diff --git a/fincept-qt/_build_voice.bat b/fincept-qt/_build_voice.batnew file mode 100644index 000000000..94ef84d1b--- /dev/null+++ b/fincept-qt/_build_voice.bat@@ -0,0 +1,5 @@+@echo off+cd /d C:\windowsdisk\finceptTerminal\fincept-qt+call "C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1+cmake --build --preset win-release > build_voice.log 2>&1+exit /b %ERRORLEVEL%diff --git a/fincept-qt/docs/DATAHUB_TOPICS.md b/fincept-qt/docs/DATAHUB_TOPICS.mdindex daf72696e..6095296bb 100644--- a/fincept-qt/docs/DATAHUB_TOPICS.md+++ b/fincept-qt/docs/DATAHUB_TOPICS.md@@ -14,13 +14,18 @@ Topic segments separate with `:`. The first segment is the domain; subsequent se## WebSocket streams (Phase 4)+Producer changed to `ExchangeSessionManager` with the multi-broker refactor+(Phase 2). Sessions (one per exchange, kept warm for the app lifetime) hand+fan-out data to the manager via `SessionPublisher`; the manager is the sole+hub registrant for `ws:<exchange>:*`.+| Pattern | Producer | TTL | Notes ||---|---|---|---|-| `ws:kraken:ticker:<pair>` | `ExchangeService` | push-only | Coalesced 50 ms |-| `ws:kraken:orderbook:<pair>` | `ExchangeService` | push-only | |-| `ws:kraken:trades:<pair>` | `ExchangeService` | push-only | |-| `ws:kraken:ohlc:<pair>:<interval>` | `ExchangeService` | push-only | |-| `ws:hyperliquid:*` | `ExchangeService` | push-only | Same sub-families as Kraken |+| `ws:kraken:ticker:<pair>` | `ExchangeSessionManager` | push-only | Coalesced 50 ms |+| `ws:kraken:orderbook:<pair>` | `ExchangeSessionManager` | push-only | |+| `ws:kraken:trades:<pair>` | `ExchangeSessionManager` | push-only | |+| `ws:kraken:ohlc:<pair>:<interval>` | `ExchangeSessionManager` | push-only | |+| `ws:hyperliquid:*` | `ExchangeSessionManager` | push-only | Same sub-families as Kraken || `prediction:polymarket:price:<asset_id>` | `PolymarketWebSocket` | push-only | Was `polymarket:price:*` before the prediction-markets refactor || `prediction:polymarket:orderbook:<asset_id>` | `PolymarketWebSocket` | push-only | Was `polymarket:orderbook:*` before the prediction-markets refactor || `prediction:kalshi:price:<ticker>:<side>` | `KalshiWsClient` | push-only | `<side>` is `yes` or `no`. Requires credentials — streaming activates in Phase 7 |diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qsindex 057391b1d..aaab9e6e9 100644--- a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/installscript.qs@@ -1,18 +1,51 @@// installscript.qs -- Fincept Terminal QtIFW component script-// Handles: shortcuts on install, user data cleanup on uninstall//-// Data locations cleaned on uninstall (when user confirms):-// Windows: %LOCALAPPDATA%\com.fincept.terminal\-// macOS: ~/Library/Application Support/com.fincept.terminal/-// Linux: ~/.local/share/com.fincept.terminal/-// QSettings (registry/plist/conf), credentials, temp files+// Handles:+// - Platform shortcuts on install (Start Menu, Desktop, .desktop entry)+// - Full user-data cleanup on uninstall (with user confirmation)+//+// Data locations cleaned on uninstall:+// Windows : %LOCALAPPDATA%\com.fincept.terminal\+// %LOCALAPPDATA%\Fincept\* (legacy)+// %LOCALAPPDATA%\FinceptTerminal\* (legacy)+// %APPDATA%\Fincept\* (QSettings roaming)+// HKCU\Software\Fincept (registry)+// Windows Credential Manager: FinceptTerminal/*+// %TEMP%\fincept_*+// macOS : ~/Library/Application Support/com.fincept.terminal/+// ~/Library/Preferences/com.fincept.FinceptTerminal.plist+// ~/Library/Preferences/Fincept.plist (if present)+// Keychain: com.fincept.terminal service entries+// $TMPDIR/fincept_*, /tmp/fincept_*+// Linux : ~/.local/share/com.fincept.terminal/+// ~/.config/Fincept/+// /tmp/fincept_*+// ~/.local/share/applications/fincept-terminal.desktop+//+// Debug: run the maintenance tool with `-v` (or `--verbose`) to see console.log output.++// ---------------------------------------------------------------------------+// Component constructor: wire up lifecycle hooks+// ---------------------------------------------------------------------------function Component(){- installer.installationFinished.connect(this, Component.prototype.installationFinished);+ console.log("[Fincept] Component() constructor — isInstaller=" ++ installer.isInstaller() ++ " isUninstaller=" + installer.isUninstaller() ++ " isUpdater=" + installer.isUpdater() ++ " isPackageManager=" + installer.isPackageManager());++ // Connect signals using the 1-arg form. The 2-arg form (thisObj, fn) is+ // not reliably supported by the QJSEngine that backs QtIFW component+ // scripts — connections silently no-op on some versions.+ if (installer.isInstaller()) {+ installer.installationFinished.connect(onInstallationFinished);+ }if (installer.isUninstaller()) {- installer.uninstallationStarted.connect(this, Component.prototype.uninstallationStarted);+ installer.uninstallationStarted.connect(onUninstallationStarted);+ installer.uninstallationFinished.connect(onUninstallationFinished);}}@@ -22,6 +55,7 @@ function Component()Component.prototype.createOperations = function(){+ // Always call base first so file extraction happens.component.createOperations();var targetDir = installer.value("TargetDir");@@ -63,24 +97,25 @@ Component.prototype.createOperations = function()"Keywords=finance;trading;stocks;crypto;portfolio;AI;analytics;markets;\n");}-// macOS: .app bundle is self-contained, no shortcuts needed};-Component.prototype.installationFinished = function()+function onInstallationFinished(){- // Reserved for future post-install actions (URL handlers, file associations)-};+ console.log("[Fincept] Installation finished.");+}// ----------------------------------------------------------------------------// Uninstall: prompt for user data removal, then clean up+// Uninstall: ask the user, then clean everything// ----------------------------------------------------------------------------Component.prototype.uninstallationStarted = function()+function onUninstallationStarted(){- var result = QMessageBox.question(+ console.log("[Fincept] uninstallationStarted — prompting for user-data removal.");++ var answer = QMessageBox.question("fincept.uninstall.data",- "Remove User Data?",+ "Remove Fincept Terminal User Data?","Do you want to remove all Fincept Terminal user data?\n\n" +"This includes:\n" +" - Databases (chat history, portfolio, watchlists)\n" +@@ -96,176 +131,264 @@ Component.prototype.uninstallationStarted = function()QMessageBox.No);- if (result === QMessageBox.Yes) {- cleanUserData();+ if (answer === QMessageBox.Yes) {+ console.log("[Fincept] User chose Yes — cleaning all user data.");+ try {+ cleanUserData();+ } catch (e) {+ console.log("[Fincept] cleanUserData threw: " + e);+ }+ } else {+ console.log("[Fincept] User chose No — keeping user data.");}-};--// ----------------------------------------------------------------------------// Data cleanup implementation-// ---------------------------------------------------------------------------+}-function cleanUserData()+function onUninstallationFinished(){- // 1. Remove main data directory- removeDataRoot();-- // 2. Remove legacy data directories (Windows only)- removeLegacyDirs();-- // 3. Remove QSettings (registry / plist / conf)- removeSettings();-- // 4. Remove credentials from OS secure storage- removeCredentials();-- // 5. Clean temp files- removeTempFiles();+ console.log("[Fincept] Uninstallation finished.");}-// -- 1. Main data root --+// ---------------------------------------------------------------------------+// Data cleanup implementation — dispatches to per-platform routines+// ----------------------------------------------------------------------------function removeDataRoot()+function cleanUserData(){- var dataRoot = "";-if (systemInfo.kernelType === "winnt") {- dataRoot = installer.environmentVariable("LOCALAPPDATA") +- "/com.fincept.terminal";+ cleanUserDataWindows();} else if (systemInfo.kernelType === "darwin") {- dataRoot = installer.environmentVariable("HOME") +- "/Library/Application Support/com.fincept.terminal";+ cleanUserDataMac();} else {- dataRoot = installer.environmentVariable("HOME") +- "/.local/share/com.fincept.terminal";- }-- if (installer.fileExists(dataRoot)) {- removeDirectoryRecursive(dataRoot);+ cleanUserDataLinux();}}-// -- 2. Legacy directories (pre-v4 Windows paths) --+// ---------- Windows -----------function removeLegacyDirs()+function cleanUserDataWindows(){- if (systemInfo.kernelType !== "winnt") return;-var localAppData = installer.environmentVariable("LOCALAPPDATA");-- var legacy1 = localAppData + "/Fincept/FinceptTerminal";- if (installer.fileExists(legacy1)) {- removeDirectoryRecursive(legacy1);- }-- var legacy2 = localAppData + "/FinceptTerminal";- if (installer.fileExists(legacy2)) {- removeDirectoryRecursive(legacy2);+ var appData = installer.environmentVariable("APPDATA");+ var tempDir = installer.environmentVariable("TEMP");++ // 1. Main data root+ removeDirWindows(localAppData + "/com.fincept.terminal");++ // 2. Legacy data roots+ removeDirWindows(localAppData + "/Fincept/FinceptTerminal");+ removeDirWindows(localAppData + "/FinceptTerminal");+ // Remove the Fincept/ parent if it's now empty+ removeDirIfEmptyWindows(localAppData + "/Fincept");++ // 3. Roaming QSettings (INI fallback, rare but possible)+ removeDirWindows(appData + "/Fincept/FinceptTerminal");+ removeDirIfEmptyWindows(appData + "/Fincept");++ // 4. Registry — QSettings default format on Windows+ runAndLog("reg.exe", ["delete", "HKCU\\Software\\Fincept\\FinceptTerminal", "/f"]);+ runAndLog("reg.exe", ["delete", "HKCU\\Software\\Fincept\\FinceptTerminal-Secure", "/f"]);+ // Remove parent key last — only succeeds if no other Fincept apps remain.+ runAndLog("reg.exe", ["delete", "HKCU\\Software\\Fincept", "/f"]);++ // 5. Windows Credential Manager entries: FinceptTerminal/*+ // cmdkey has no wildcard delete. Enumerate via PowerShell and delete each.+ runAndLog("powershell.exe", [+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",+ "$list = cmdkey /list 2>$null | Select-String -Pattern 'FinceptTerminal/'; " ++ "foreach ($line in $list) { " ++ " $target = ($line.ToString() -replace '^\\s*Target:\\s*','').Trim(); " ++ " if ($target) { cmdkey /delete:$target | Out-Null } " ++ "}"+ ]);++ // 6. Temp files — single shell string so wildcards expand inside cmd.+ // Covers: fincept_cell_*, fincept_arg_*, fincept_report_autosave.*,+ // fincept_paste_*, fincept_chart_*, fincept_spark_*, UpdateService temp.+ runAndLog("cmd.exe", ["/c",+ "del /q /f \"" + toWin(tempDir) + "\\fincept_*\" 2>nul & " ++ "del /q /f \"" + toWin(tempDir) + "\\fincept-boot.log\" 2>nul & " ++ "exit /b 0"]);++ // 7. Screenshots saved under %USERPROFILE% by MainWindow "save screenshot"+ // with the strict pattern fincept_YYYYMMDD_HHMMSS.png. Only match that+ // exact shape so we don't delete unrelated user files.+ var userProfile = installer.environmentVariable("USERPROFILE");+ if (userProfile) {+ runAndLog("powershell.exe", [+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",+ "Get-ChildItem -LiteralPath '" + toWin(userProfile) + "' -File " ++ "-Filter 'fincept_*.png' -ErrorAction SilentlyContinue | " ++ "Where-Object { $_.Name -match '^fincept_\\d{8}_\\d{6}\\.png$' } | " ++ "Remove-Item -Force -ErrorAction SilentlyContinue"+ ]);}+}- // Remove empty parent directory- var finceptParent = localAppData + "/Fincept";- if (installer.fileExists(finceptParent)) {- installer.execute("cmd", ["/c", "rmdir", finceptParent.replace(/\//g, "\\")]);+function removeDirWindows(pathFwd)+{+ if (!pathFwd) return;+ if (!installer.fileExists(pathFwd)) {+ console.log("[Fincept] skip (not present): " + pathFwd);+ return;}+ var win = toWin(pathFwd);+ // Quote the path inside a single shell string so spaces in the path+ // survive argv splitting. `exit /b 0` ensures we never surface an error.+ runAndLog("cmd.exe", ["/c",+ "rmdir /s /q \"" + win + "\" 2>nul & exit /b 0"]);}-// -- 3. QSettings --+function removeDirIfEmptyWindows(pathFwd)+{+ if (!pathFwd || !installer.fileExists(pathFwd)) return;+ var win = toWin(pathFwd);+ // `rmdir` without /s fails if the directory isn't empty — which is what we want.+ runAndLog("cmd.exe", ["/c",+ "rmdir \"" + win + "\" 2>nul & exit /b 0"]);+}-function removeSettings()+function toWin(pathFwd){- if (systemInfo.kernelType === "winnt") {- // Registry: HKCU\Software\Fincept\FinceptTerminal- installer.execute("reg", ["delete",- "HKCU\\Software\\Fincept\\FinceptTerminal", "/f"]);- // Registry: HKCU\Software\Fincept\FinceptTerminal-Secure- installer.execute("reg", ["delete",- "HKCU\\Software\\Fincept\\FinceptTerminal-Secure", "/f"]);- // Remove empty parent key if no other Fincept apps- installer.execute("reg", ["delete",- "HKCU\\Software\\Fincept", "/f"]);+ return pathFwd.replace(/\//g, "\\");+}- } else if (systemInfo.kernelType === "darwin") {- var plistPath = installer.environmentVariable("HOME") +- "/Library/Preferences/com.fincept.FinceptTerminal.plist";- if (installer.fileExists(plistPath)) {- installer.execute("rm", ["-f", plistPath]);- }+// ---------- macOS ----------- } else {- // Linux: QSettings .conf files- var home = installer.environmentVariable("HOME");- var confPath = home + "/.config/Fincept/FinceptTerminal.conf";- if (installer.fileExists(confPath)) {- installer.execute("rm", ["-f", confPath]);- }+function cleanUserDataMac()+{+ var home = installer.environmentVariable("HOME");++ // 1. Main data root+ removeDirPosix(home + "/Library/Application Support/com.fincept.terminal");++ // 2. Preferences / plist+ removeFilePosix(home + "/Library/Preferences/com.fincept.FinceptTerminal.plist");+ removeFilePosix(home + "/Library/Preferences/Fincept.FinceptTerminal.plist");+ removeFilePosix(home + "/Library/Preferences/Fincept.FinceptTerminal-Secure.plist");++ // 3. Caches (Qt/QSettings/logs occasionally land here)+ removeDirPosix(home + "/Library/Caches/com.fincept.terminal");+ removeDirPosix(home + "/Library/Caches/Fincept");++ // 4. Saved application state+ removeDirPosix(home + "/Library/Saved Application State/com.fincept.terminal.savedState");++ // 5. Keychain: delete all entries under service "com.fincept.terminal".+ // security(1) removes one entry per call — loop until it fails (no more).+ runAndLog("/bin/bash", ["-c",+ "while /usr/bin/security delete-generic-password -s 'com.fincept.terminal' >/dev/null 2>&1; do :; done; exit 0"+ ]);++ // 6. Temp files+ runAndLog("/bin/bash", ["-c",+ "rm -f /tmp/fincept_* /tmp/fincept-boot.log 2>/dev/null; " ++ "rm -f \"${TMPDIR:-/tmp}\"/fincept_* \"${TMPDIR:-/tmp}\"/fincept-boot.log 2>/dev/null; " ++ "exit 0"+ ]);++ // 7. Timestamped screenshots saved to $HOME by MainWindow save-screenshot+ // Pattern: fincept_YYYYMMDD_HHMMSS.png — strict match to avoid collateral.+ runAndLog("/bin/bash", ["-c",+ "find \"" + shellEscape(home) + "\" -maxdepth 1 -type f " ++ "-regex '.*/fincept_[0-9]\\{8\\}_[0-9]\\{6\\}\\.png$' " ++ "-delete 2>/dev/null; exit 0"+ ]);+}- var secureConf = home + "/.config/Fincept/FinceptTerminal-Secure.conf";- if (installer.fileExists(secureConf)) {- installer.execute("rm", ["-f", secureConf]);- }+// ---------- Linux ----------- // Remove empty parent dir- var configDir = home + "/.config/Fincept";- if (installer.fileExists(configDir)) {- installer.execute("rmdir", [configDir]);- }- }+function cleanUserDataLinux()+{+ var home = installer.environmentVariable("HOME");+ var xdgCfg = installer.environmentVariable("XDG_CONFIG_HOME");+ var xdgDat = installer.environmentVariable("XDG_DATA_HOME");+ var xdgCch = installer.environmentVariable("XDG_CACHE_HOME");++ if (!xdgCfg) xdgCfg = home + "/.config";+ if (!xdgDat) xdgDat = home + "/.local/share";+ if (!xdgCch) xdgCch = home + "/.cache";++ // 1. Main data root (respect XDG)+ removeDirPosix(xdgDat + "/com.fincept.terminal");+ removeDirPosix(home + "/.local/share/com.fincept.terminal");++ // 2. QSettings .conf files+ removeFilePosix(xdgCfg + "/Fincept/FinceptTerminal.conf");+ removeFilePosix(xdgCfg + "/Fincept/FinceptTerminal-Secure.conf");+ removeDirIfEmptyPosix(xdgCfg + "/Fincept");++ // 3. Cache dir (if the app used one)+ removeDirPosix(xdgCch + "/com.fincept.terminal");+ removeDirPosix(xdgCch + "/Fincept");++ // 4. Desktop entry (installed via CreateDesktopEntry at install time — IFW's+ // own UNDO step removes it, but clean up any stale copies just in case).+ removeFilePosix(home + "/.local/share/applications/fincept-terminal.desktop");++ // 5. Temp files+ runAndLog("/bin/bash", ["-c",+ "rm -f /tmp/fincept_* /tmp/fincept-boot.log 2>/dev/null; " ++ "rm -f \"${TMPDIR:-/tmp}\"/fincept_* \"${TMPDIR:-/tmp}\"/fincept-boot.log 2>/dev/null; " ++ "exit 0"+ ]);++ // 6. Timestamped screenshots saved to $HOME by MainWindow save-screenshot+ runAndLog("/bin/bash", ["-c",+ "find \"" + shellEscape(home) + "\" -maxdepth 1 -type f " ++ "-regextype posix-extended " ++ "-regex '.*/fincept_[0-9]{8}_[0-9]{6}\\.png' " ++ "-delete 2>/dev/null; exit 0"+ ]);}-// -- 4. Credentials --+// ---------- Unix helpers (mac + linux) -----------function removeCredentials()+function removeDirPosix(path){- if (systemInfo.kernelType === "winnt") {- // Windows Credential Manager: enumerate and delete FinceptTerminal/* entries- // cmdkey doesn't support wildcards, so use PowerShell to enumerate + delete- installer.execute("powershell", [- "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",- "$targets = cmdkey /list 2>&1 | Select-String 'FinceptTerminal/' | " +- "ForEach-Object { ($_ -replace '.*Target:\\s*', '').Trim() }; " +- "foreach ($t in $targets) { cmdkey /delete:$t 2>$null }"- ]);-- } else if (systemInfo.kernelType === "darwin") {- // macOS Keychain: delete all entries with service "com.fincept.terminal"- // security delete-generic-password only removes one at a time, so loop- installer.execute("/bin/bash", ["-c",- "while /usr/bin/security delete-generic-password " +- "-s 'com.fincept.terminal' 2>/dev/null; do :; done"- ]);+ if (!path) return;+ if (!installer.fileExists(path)) {+ console.log("[Fincept] skip (not present): " + path);+ return;}-- // Linux: credentials are stored in FinceptTerminal-Secure.conf (already deleted above)+ // Use /bin/rm with -rf so missing paths never error. Shell-wrap so the+ // path string survives any unusual characters (spaces in $HOME, etc).+ runAndLog("/bin/bash", ["-c", "rm -rf \"" + shellEscape(path) + "\"; exit 0"]);}-// -- 5. Temp files --+function removeFilePosix(path)+{+ if (!path) return;+ if (!installer.fileExists(path)) {+ console.log("[Fincept] skip (not present): " + path);+ return;+ }+ runAndLog("/bin/bash", ["-c", "rm -f \"" + shellEscape(path) + "\"; exit 0"]);+}-function removeTempFiles()+function removeDirIfEmptyPosix(path){- if (systemInfo.kernelType === "winnt") {- var tempDir = installer.environmentVariable("TEMP");- installer.execute("cmd", ["/c",- "del /q \"" + tempDir.replace(/\//g, "\\") + "\\fincept_*\" 2>nul"]);+ if (!path || !installer.fileExists(path)) return;+ // rmdir fails if non-empty; ignore.+ runAndLog("/bin/bash", ["-c", "rmdir \"" + shellEscape(path) + "\" 2>/dev/null; exit 0"]);+}- } else {- installer.execute("/bin/bash", ["-c",- "rm -f /tmp/fincept_* 2>/dev/null; " +- "rm -f \"${TMPDIR:-/tmp}\"/fincept_* 2>/dev/null"- ]);- }+function shellEscape(s)+{+ // Escape backslashes and double-quotes for embedding in a double-quoted shell string.+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");}-// ----------------------------------------------------------------------------// Helpers-// ---------------------------------------------------------------------------+// ---------- Generic runner with logging -----------function removeDirectoryRecursive(path)+function runAndLog(program, args){- if (systemInfo.kernelType === "winnt") {- installer.execute("cmd", ["/c", "rmdir", "/s", "/q",- path.replace(/\//g, "\\")]);- } else {- installer.execute("/bin/rm", ["-rf", path]);+ var result = installer.execute(program, args);+ // installer.execute returns [stdout, exitCode] on success,+ // or [] (empty) if the program failed to launch.+ if (!result || result.length === 0) {+ console.log("[Fincept] FAILED to launch: " + program + " " + args.join(" "));+ return;}+ var exitCode = result.length >= 2 ? result[1] : "?";+ console.log("[Fincept] ran " + program + " (exit=" + exitCode + ")");}diff --git a/fincept-qt/packaging/linux/AppImageBuilder.yml b/fincept-qt/packaging/linux/AppImageBuilder.ymlindex 5ce0da0f4..bfb5362a1 100644--- a/fincept-qt/packaging/linux/AppImageBuilder.yml+++ b/fincept-qt/packaging/linux/AppImageBuilder.yml@@ -16,7 +16,7 @@ AppDir:id: com.fincept.terminalname: Fincept Terminalicon: fincept-terminal- version: !ENV ${FINCEPT_VERSION:-4.0.2}+ version: !ENV ${FINCEPT_VERSION:-4.0.1}exec: usr/bin/FinceptTerminalexec_args: $@@@ -56,6 +56,6 @@ AppDir:AppImage:arch: x86_64comp: xz- file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.0.2}-x86_64.AppImage+ file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.0.1}-x86_64.AppImagesign-key: Noneupdate-information: gh-releases-zsync|Fincept-Corporation|FinceptTerminal|latest|FinceptTerminal-*x86_64.AppImage.zsyncdiff --git a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml b/fincept-qt/packaging/linux/fincept-terminal.appdata.xmlindex ad8832e0b..a1c725b67 100644--- a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml+++ b/fincept-qt/packaging/linux/fincept-terminal.appdata.xml@@ -28,9 +28,9 @@<binary>FinceptTerminal</binary></provides><releases>- <release version="4.0.2" date="2026-04-14">+ <release version="4.0.1" date="2026-04-14"><description>- <p>Version 4.0.2 — Patch release.</p>+ <p>Version 4.0.1 — Patch release.</p></description></release><release version="4.0.0" date="2025-01-01">diff --git a/fincept-qt/scripts/bcb_data.py b/fincept-qt/scripts/bcb_data.pyindex c71ef8aeb..e649f1fbb 100644--- a/fincept-qt/scripts/bcb_data.py+++ b/fincept-qt/scripts/bcb_data.py@@ -138,7 +138,7 @@ class BCBWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "*/*",})diff --git a/fincept-qt/scripts/bnm_data.py b/fincept-qt/scripts/bnm_data.pyindex c1618e509..72315636d 100644--- a/fincept-qt/scripts/bnm_data.py+++ b/fincept-qt/scripts/bnm_data.py@@ -99,7 +99,7 @@ class BNMWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": ACCEPT_HEADER,})diff --git a/fincept-qt/scripts/bnr_data.py b/fincept-qt/scripts/bnr_data.pyindex 24166f242..f82ea0601 100644--- a/fincept-qt/scripts/bnr_data.py+++ b/fincept-qt/scripts/bnr_data.py@@ -80,7 +80,7 @@ class BNRWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/xml, text/xml, */*",})diff --git a/fincept-qt/scripts/boc_data.py b/fincept-qt/scripts/boc_data.pyindex 4ed8d1b03..1e2ea5544 100644--- a/fincept-qt/scripts/boc_data.py+++ b/fincept-qt/scripts/boc_data.py@@ -121,7 +121,7 @@ class BoCWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/json",})diff --git a/fincept-qt/scripts/boi_data.py b/fincept-qt/scripts/boi_data.pyindex 2ea265212..708fee8db 100644--- a/fincept-qt/scripts/boi_data.py+++ b/fincept-qt/scripts/boi_data.py@@ -108,7 +108,7 @@ class BOIWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "text/csv, application/json, */*",})diff --git a/fincept-qt/scripts/cnb_data.py b/fincept-qt/scripts/cnb_data.pyindex 1b9491d72..bd993ea33 100644--- a/fincept-qt/scripts/cnb_data.py+++ b/fincept-qt/scripts/cnb_data.py@@ -103,7 +103,7 @@ class CNBWrapper:self.lang = langself.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/json",})diff --git a/fincept-qt/scripts/hnb_data.py b/fincept-qt/scripts/hnb_data.pyindex ff3588258..08d5afcd8 100644--- a/fincept-qt/scripts/hnb_data.py+++ b/fincept-qt/scripts/hnb_data.py@@ -94,7 +94,7 @@ class HNBWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/json",})diff --git a/fincept-qt/scripts/ilostat_data.py b/fincept-qt/scripts/ilostat_data.pyindex caab94f2f..c784b6456 100644--- a/fincept-qt/scripts/ilostat_data.py+++ b/fincept-qt/scripts/ilostat_data.py@@ -135,7 +135,7 @@ def _session() -> requests.Session:"""Return a pre-configured requests Session."""s = requests.Session()s.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2 (ILOSTAT-wrapper)",+ "User-Agent": "Fincept-Terminal/4.0.1 (ILOSTAT-wrapper)","Accept-Language": "en",})return sdiff --git a/fincept-qt/scripts/mnb_data.py b/fincept-qt/scripts/mnb_data.pyindex 391c686b7..8120f360b 100644--- a/fincept-qt/scripts/mnb_data.py+++ b/fincept-qt/scripts/mnb_data.py@@ -88,7 +88,7 @@ class MNBWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Content-Type": "text/xml; charset=utf-8",})diff --git a/fincept-qt/scripts/nbp_data.py b/fincept-qt/scripts/nbp_data.pyindex 4e9f38392..984da333f 100644--- a/fincept-qt/scripts/nbp_data.py+++ b/fincept-qt/scripts/nbp_data.py@@ -93,7 +93,7 @@ class NBPWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/json",})diff --git a/fincept-qt/scripts/norges_bank_data.py b/fincept-qt/scripts/norges_bank_data.pyindex dfcbc1efc..b2f59485a 100644--- a/fincept-qt/scripts/norges_bank_data.py+++ b/fincept-qt/scripts/norges_bank_data.py@@ -104,7 +104,7 @@ class NorgesBankWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "text/csv,text/plain,*/*",})diff --git a/fincept-qt/scripts/polymarket.py b/fincept-qt/scripts/polymarket.pyindex 97b422b44..d016d5d0f 100644--- a/fincept-qt/scripts/polymarket.py+++ b/fincept-qt/scripts/polymarket.py@@ -28,7 +28,7 @@ def get_markets(limit=10):}headers = {"Accept": "application/json",- "User-Agent": "FinceptTerminal/4.0.2",+ "User-Agent": "FinceptTerminal/4.0.1",}r = requests.get(url, params=params, headers=headers, timeout=15)r.raise_for_status()diff --git a/fincept-qt/scripts/prediction_kalshi.py b/fincept-qt/scripts/prediction_kalshi.pyindex 94da7a299..8f3dfe21a 100644--- a/fincept-qt/scripts/prediction_kalshi.py+++ b/fincept-qt/scripts/prediction_kalshi.py@@ -159,6 +159,8 @@ def cmd_positions(payload: dict) -> None:positions = []# As of Mar 12, 2026 Kalshi removed integer cent fields from responses.# Use position_fp (signed contract count, 2dp) and *_dollars (decimal $).+ # Kalshi does not expose unrealized PnL directly — the UI shows 0 rather+ # than the cumulative traded notional (which was mislabeled previously).for p in data.get("market_positions", []) or []:position_fp = _to_float(p.get("position_fp"))market_exposure = _to_float(p.get("market_exposure_dollars"))@@ -171,8 +173,10 @@ def cmd_positions(payload: dict) -> None:"size": size,"avg_price": avg_price,"realized_pnl": _to_float(p.get("realized_pnl_dollars")),- "unrealized_pnl": _to_float(p.get("total_traded_dollars")),+ "unrealized_pnl": 0.0,"current_value": market_exposure,+ "total_traded_dollars": _to_float(p.get("total_traded_dollars")),+ "fees_paid_dollars": _to_float(p.get("fees_paid_dollars")),})_emit({"ok": True, "positions": positions})@@ -232,7 +236,35 @@ def cmd_fills(payload: dict) -> None:if not ok:_fail(f"HTTP {code}", detail=data)return- _emit({"ok": True, "fills": data.get("fills", []) or []})+ # Normalize Kalshi fills to a shape consumers can render without+ # knowing Kalshi-specific field names. ts_ms is epoch ms; price is+ # decimal dollars; side is YES/NO.+ fills_out = []+ for f in data.get("fills", []) or []:+ side = (f.get("side") or "").lower()+ ts_ms = 0+ ct = f.get("created_time") or ""+ if ct:+ try:+ ts_ms = int(datetime.datetime.fromisoformat(+ ct.replace("Z", "+00:00")).timestamp() * 1000)+ except ValueError:+ ts_ms = 0+ fills_out.append({+ "type": "FILL",+ "fill_id": f.get("fill_id", ""),+ "trade_id": f.get("trade_id", ""),+ "order_id": f.get("order_id", ""),+ "market_id": f.get("ticker") or f.get("market_ticker", ""),+ "side": side.upper(),+ "action": (f.get("action") or "").upper(),+ "size": _to_float(f.get("count_fp")),+ "price": _to_float(f.get("yes_price_dollars") if side == "yes"+ else f.get("no_price_dollars")),+ "is_taker": bool(f.get("is_taker", False)),+ "ts_ms": ts_ms,+ })+ _emit({"ok": True, "fills": fills_out})def cmd_settlements(payload: dict) -> None:@@ -298,6 +330,146 @@ def cmd_decrease_order(payload: dict) -> None:_emit({"ok": True, "raw": data})+def cmd_get_order(payload: dict) -> None:+ order_id = str(payload["order_id"])+ ok, code, data = _request(payload, "GET", f"/portfolio/orders/{order_id}")+ if not ok:+ _fail(f"HTTP {code}", detail=data)+ return+ _emit({"ok": True, "order": data.get("order", data)})+++def cmd_amend_order(payload: dict) -> None:+ """POST /portfolio/orders/{order_id}/amend++ Kalshi accepts a price change (cents integer OR *_dollars string on+ request) + an updated buy_max_cost in cents. Only include fields the+ caller provided so we don't accidentally reset other constraints.+ """+ order_id = str(payload["order_id"])+ body = {}+ if "yes_price_cents" in payload:+ body["yes_price"] = int(payload["yes_price_cents"])+ elif "no_price_cents" in payload:+ body["no_price"] = int(payload["no_price_cents"])+ if "buy_max_cost" in payload:+ body["buy_max_cost"] = int(payload["buy_max_cost"])+ if "client_order_id" in payload:+ body["client_order_id"] = str(payload["client_order_id"])++ if not body:+ _fail("amend_order requires yes_price_cents, no_price_cents, "+ "or buy_max_cost")+ return++ ok, code, data = _request(payload, "POST",+ f"/portfolio/orders/{order_id}/amend", body=body)+ if not ok:+ _fail(f"HTTP {code}", detail=data)+ return+ _emit({"ok": True, "order": data.get("order", data)})+++def cmd_place_orders_batch(payload: dict) -> None:+ """POST /portfolio/orders/batched++ `orders` is a list of order dicts with the same shape accepted by+ `cmd_place_order`. Kalshi returns {orders: [...]} with per-order+ success/error; we surface the whole array for the caller to inspect.+ """+ orders_in = payload.get("orders") or []+ if not isinstance(orders_in, list) or not orders_in:+ _fail("place_orders_batch requires a non-empty `orders` list")+ return++ body = {"orders": []}+ for o in orders_in:+ entry = {+ "ticker": o["ticker"],+ "action": str(o.get("action", "buy")).lower(),+ "side": str(o.get("side", "yes")).lower(),+ "count": int(o["count"]),+ "type": str(o.get("order_type", "limit")).lower(),+ "client_order_id": o.get("client_order_id") or str(uuid.uuid4()),+ }+ if entry["type"] == "limit":+ if "yes_price_cents" in o:+ entry["yes_price"] = int(o["yes_price_cents"])+ elif "no_price_cents" in o:+ entry["no_price"] = int(o["no_price_cents"])+ if o.get("expiration_ts"):+ entry["expiration_ts"] = int(o["expiration_ts"])+ body["orders"].append(entry)++ ok, code, data = _request(payload, "POST", "/portfolio/orders/batched",+ body=body)+ if not ok:+ _fail(f"HTTP {code}", detail=data)+ return+ _emit({"ok": True, "orders": data.get("orders", []) or [], "raw": data})+++def cmd_cancel_orders_batch(payload: dict) -> None:+ """DELETE /portfolio/orders/batched++ Kalshi expects the order_ids in the body on DELETE. Sends a single+ round-trip regardless of list size.+ """+ ids = payload.get("order_ids") or []+ if not ids:+ _fail("cancel_orders_batch requires `order_ids`")+ return+ body = {"order_ids": [str(i) for i in ids]}+ ok, code, data = _request(payload, "DELETE", "/portfolio/orders/batched",+ body=body)+ if not ok:+ _fail(f"HTTP {code}", detail=data)+ return+ _emit({"ok": True, "results": data.get("orders", []) or [], "raw": data})+++def cmd_historical_fills(payload: dict) -> None:+ params = {"limit": int(payload.get("limit", 200))}+ if payload.get("cursor"):+ params["cursor"] = str(payload["cursor"])+ if payload.get("ticker"):+ params["ticker"] = str(payload["ticker"])+ if payload.get("min_ts"):+ params["min_ts"] = int(payload["min_ts"])+ if payload.get("max_ts"):+ params["max_ts"] = int(payload["max_ts"])+ ok, code, data = _request(payload, "GET", "/historical/fills",+ params=params)+ if not ok:+ _fail(f"HTTP {code}", detail=data)+ return+ _emit({+ "ok": True,+ "fills": data.get("fills", []) or [],+ "cursor": data.get("cursor", ""),+ })+++def cmd_historical_orders(payload: dict) -> None:+ params = {"limit": int(payload.get("limit", 200))}+ if payload.get("cursor"):+ params["cursor"] = str(payload["cursor"])+ if payload.get("ticker"):+ params["ticker"] = str(payload["ticker"])+ if payload.get("status"):+ params["status"] = str(payload["status"])+ ok, code, data = _request(payload, "GET", "/historical/orders",+ params=params)+ if not ok:+ _fail(f"HTTP {code}", detail=data)+ return+ _emit({+ "ok": True,+ "orders": data.get("orders", []) or [],+ "cursor": data.get("cursor", ""),+ })++COMMANDS = {"balance": cmd_balance,"positions": cmd_positions,@@ -307,6 +479,12 @@ COMMANDS = {"place_order": cmd_place_order,"cancel_order": cmd_cancel_order,"decrease_order": cmd_decrease_order,+ "get_order": cmd_get_order,+ "amend_order": cmd_amend_order,+ "place_orders_batch": cmd_place_orders_batch,+ "cancel_orders_batch": cmd_cancel_orders_batch,+ "historical_fills": cmd_historical_fills,+ "historical_orders": cmd_historical_orders,}diff --git a/fincept-qt/scripts/riksbank_data.py b/fincept-qt/scripts/riksbank_data.pyindex 934b736ee..63b6ac0e7 100644--- a/fincept-qt/scripts/riksbank_data.py+++ b/fincept-qt/scripts/riksbank_data.py@@ -124,7 +124,7 @@ class RiksbankWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/json",})diff --git a/fincept-qt/scripts/snb_data.py b/fincept-qt/scripts/snb_data.pyindex 52c60cf92..d6dce434b 100644--- a/fincept-qt/scripts/snb_data.py+++ b/fincept-qt/scripts/snb_data.py@@ -139,7 +139,7 @@ class SNBWrapper:self.lang = langself.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2 (SNB-wrapper)",+ "User-Agent": "Fincept-Terminal/4.0.1 (SNB-wrapper)","Accept": "text/csv,text/plain,*/*",})diff --git a/fincept-qt/scripts/tcmb_data.py b/fincept-qt/scripts/tcmb_data.pyindex dc6f7646f..86a3b65df 100644--- a/fincept-qt/scripts/tcmb_data.py+++ b/fincept-qt/scripts/tcmb_data.py@@ -82,7 +82,7 @@ class TCMBWrapper:def __init__(self):self.session = requests.Session()self.session.headers.update({- "User-Agent": "Fincept-Terminal/4.0.2",+ "User-Agent": "Fincept-Terminal/4.0.1","Accept": "application/xml, text/xml, */*",})diff --git a/fincept-qt/scripts/voice/deepgram_stt.py b/fincept-qt/scripts/voice/deepgram_stt.pynew file mode 100644index 000000000..ea5309408--- /dev/null+++ b/fincept-qt/scripts/voice/deepgram_stt.py@@ -0,0 +1,187 @@+#!/usr/bin/env python3+"""+deepgram_stt.py — Microphone → Deepgram live WebSocket STT → JSON stdout.++Matches the same JSON-lines protocol as speech_to_text.py so SpeechService can+parse either transparently:+ {"status": "calibrating"} — adjusting for ambient noise (no-op here)+ {"status": "listening"} — ready, waiting for speech+ {"text": "hello world"} — finalized transcription+ {"error": "..."} — recoverable error (keeps listening)+ {"fatal": "..."} — unrecoverable error (process exits)++Environment variables (injected by DeepgramSttProvider in C++):+ DEEPGRAM_API_KEY — required+ FINCEPT_STT_MODEL — default "nova-3"+ FINCEPT_STT_LANGUAGE — default "en"+ FINCEPT_STT_KEYTERMS — comma-separated boosted terms (optional)++The process runs until stdin is closed, a fatal error occurs, or it receives+SIGTERM (Windows: QProcess::kill sends taskkill which terminates anyway).+"""++import json+import os+import signal+import sys+import threading+++def emit(obj: dict) -> None:+ """Write a JSON line to stdout and flush immediately."""+ sys.stdout.write(json.dumps(obj) + "\n")+ sys.stdout.flush()+++def main() -> None:+ api_key = os.environ.get("DEEPGRAM_API_KEY", "").strip()+ if not api_key:+ emit({"fatal": "DEEPGRAM_API_KEY not set — configure it in Settings → Voice"})+ sys.exit(1)++ model = os.environ.get("FINCEPT_STT_MODEL", "nova-3").strip() or "nova-3"+ language = os.environ.get("FINCEPT_STT_LANGUAGE", "en").strip() or "en"+ keyterms_raw = os.environ.get("FINCEPT_STT_KEYTERMS", "").strip()+ keyterms = [t.strip() for t in keyterms_raw.split(",") if t.strip()]++ # Required deps — fail fast with clear install hints+ try:+ from deepgram import (+ DeepgramClient,+ DeepgramClientOptions,+ LiveOptions,+ LiveTranscriptionEvents,+ Microphone,+ )+ except ImportError as e:+ emit({"fatal": f"deepgram-sdk not installed — run: pip install deepgram-sdk ({e})"})+ sys.exit(1)++ try:+ import pyaudio # noqa: F401 — required by Microphone helper+ except ImportError:+ emit({"fatal": "PyAudio not installed — run: pip install PyAudio"})+ sys.exit(1)++ # Graceful shutdown flag+ stop_flag = threading.Event()++ def on_signal(signum, frame):+ stop_flag.set()++ if hasattr(signal, "SIGTERM"):+ try:+ signal.signal(signal.SIGTERM, on_signal)+ except (ValueError, OSError):+ pass # Not on main thread / not supported++ # Build Deepgram client — quiet the SDK's own stdout/stderr spam, which+ # would otherwise pollute our JSON-lines protocol.+ config = DeepgramClientOptions(options={"keepalive": "true"})+ client = DeepgramClient(api_key, config)+ dg_conn = client.listen.websocket.v("1")++ def on_open(_self, _open, **_kw):+ emit({"status": "listening"})++ def on_message(_self, result, **_kw):+ try:+ alt = result.channel.alternatives[0]+ transcript = (alt.transcript or "").strip()+ if not transcript:+ return+ # Only emit finalized utterances — interim partials would flood the+ # consumer which expects completed commands.+ is_final = bool(getattr(result, "is_final", False))+ speech_final = bool(getattr(result, "speech_final", False))+ if is_final and speech_final:+ emit({"text": transcript})+ except Exception as ex:+ emit({"error": f"Transcript parse failed: {ex}"})++ def on_error(_self, err, **_kw):+ emit({"error": f"Deepgram error: {err}"})++ def on_close(_self, _close, **_kw):+ stop_flag.set()++ def on_unhandled(_self, _unhandled, **_kw):+ # Deepgram emits several event types we don't care about (Metadata,+ # SpeechStarted, UtteranceEnd). Swallow them silently.+ pass++ dg_conn.on(LiveTranscriptionEvents.Open, on_open)+ dg_conn.on(LiveTranscriptionEvents.Transcript, on_message)+ dg_conn.on(LiveTranscriptionEvents.Error, on_error)+ dg_conn.on(LiveTranscriptionEvents.Close, on_close)+ dg_conn.on(LiveTranscriptionEvents.Unhandled, on_unhandled)++ live_opts = LiveOptions(+ model=model,+ language=language,+ encoding="linear16",+ sample_rate=16000,+ channels=1,+ punctuate=True,+ smart_format=True,+ interim_results=False,+ endpointing=300,+ vad_events=True,+ utterance_end_ms="1000",+ )++ # Keyword boosting — API surface depends on model.+ # Nova-3 uses `keyterm` (no weights, English-only).+ # Older models use `keywords` with optional weight.+ if keyterms:+ try:+ if model.startswith("nova-3"):+ live_opts.keyterm = keyterms+ else:+ live_opts.keywords = keyterms+ except Exception as ex: # non-fatal — continue without boosting+ emit({"error": f"Keyterm setup failed: {ex}"})++ emit({"status": "calibrating"})+ if not dg_conn.start(live_opts):+ emit({"fatal": "Failed to open Deepgram WebSocket connection"})+ sys.exit(1)++ # Start microphone → feeds binary audio to dg_conn+ try:+ microphone = Microphone(dg_conn.send)+ except Exception as ex:+ dg_conn.finish()+ emit({"fatal": f"No microphone available: {ex}"})+ sys.exit(1)++ if not microphone.start():+ dg_conn.finish()+ emit({"fatal": "Failed to start microphone"})+ sys.exit(1)++ # Block until signalled or parent closes stdin+ try:+ while not stop_flag.is_set():+ # Wake up periodically to check the flag; also exit if stdin is+ # closed (parent QProcess was killed).+ if stop_flag.wait(timeout=0.5):+ break+ if sys.stdin.closed:+ break+ except KeyboardInterrupt:+ pass+ finally:+ try:+ microphone.finish()+ except Exception:+ pass+ try:+ dg_conn.finish()+ except Exception:+ pass+ emit({"status": "stopped"})+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/src/ai_chat/AiChatBubble.cpp b/fincept-qt/src/ai_chat/AiChatBubble.cppindex 9309b3859..b10413954 100644--- a/fincept-qt/src/ai_chat/AiChatBubble.cpp+++ b/fincept-qt/src/ai_chat/AiChatBubble.cpp@@ -611,31 +611,33 @@ void AiChatBubble::add_bubble(const QString& role, const QString& text) {cvl->addWidget(role_lbl);// Bubble — use QTextEdit for consistent markdown rendering- auto* bubble_frame = new QWidget;- bubble_frame->setStyleSheet(QString("background:%1;border:1px solid %2;border-radius:0px;padding:0px;")- .arg(is_user ? "rgba(120,53,15,0.45)" : col::BG_SURFACE(),- is_user ? "rgba(217,119,6,0.28)" : col::BORDER_DIM()));-- auto* bvl = new QVBoxLayout(bubble_frame);- bvl->setContentsMargins(8, 6, 8, 6);- bvl->setSpacing(0);-auto* body = new QTextEdit;body->setReadOnly(true);body->setFrameShape(QFrame::NoFrame);body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);- body->document()->setDocumentMargin(2);+ body->document()->setDocumentMargin(0);body->document()->setDefaultStyleSheet(bubble_panel_md_css(is_user ? "#fff7ed" : col::TEXT_PRIMARY()));apply_obsidian_palette(body);body->setMarkdown(text);body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);- body->setStyleSheet(QString("QTextEdit{background:transparent;color:%1;border:none;font-size:13px;}")+ // inner_w = max bubble width minus h-padding (8px each side)+ const int inner_w = static_cast<int>(PANEL_W * 0.82) - 16;+ body->document()->setTextWidth(inner_w);+ body->setStyleSheet(QString("QTextEdit{background:transparent;color:%1;border:none;"+ "font-size:13px;padding:0px;}").arg(is_user ? "#fff7ed" : col::TEXT_PRIMARY()));- // Size to content- body->document()->setTextWidth(static_cast<int>(PANEL_W * 0.82) - 20);+ // Use ideal height — document already laid out at inner_w, no extra fudge neededconst int doc_h = static_cast<int>(body->document()->size().height());- body->setFixedHeight(qMax(doc_h + 8, 24));+ body->setFixedHeight(qMax(doc_h, 18));++ auto* bubble_frame = new QWidget;+ bubble_frame->setStyleSheet(QString("background:%1;border:1px solid %2;border-radius:0px;")+ .arg(is_user ? "rgba(120,53,15,0.45)" : col::BG_SURFACE(),+ is_user ? "rgba(217,119,6,0.28)" : col::BORDER_DIM()));+ auto* bvl = new QVBoxLayout(bubble_frame);+ bvl->setContentsMargins(8, 5, 8, 5);+ bvl->setSpacing(0);bvl->addWidget(body);cvl->addWidget(bubble_frame);@@ -670,21 +672,22 @@ QTextEdit* AiChatBubble::add_streaming_bubble() {body->setReadOnly(false);body->setFrameShape(QFrame::NoFrame);body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);- body->document()->setDocumentMargin(4);+ body->document()->setDocumentMargin(0);body->document()->setDefaultStyleSheet(bubble_panel_md_css(col::TEXT_PRIMARY()));apply_obsidian_palette(body);- body->setFixedHeight(32);+ body->setFixedHeight(20);body->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);body->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);body->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);body->setStyleSheet(QString("QTextEdit{background:%1;color:%2;border:1px solid %3;"- "border-radius:0px;padding:8px 12px;font-size:13px;}")+ "border-radius:0px;padding:5px 8px;font-size:13px;}").arg(col::BG_SURFACE(), col::TEXT_PRIMARY(), col::BORDER_DIM()));- // Dynamic height as content streams in+ // Dynamic height as content streams in — recalc at viewport width, no fudge factorconnect(body->document(), &QTextDocument::contentsChanged, body, [body, col_w, row]() {- body->document()->setTextWidth(body->viewport()->width() > 0 ? body->viewport()->width() : 300);- const int h = qMax(static_cast<int>(body->document()->size().height()) + 8, 32);+ const int vw = body->viewport()->width() > 0 ? body->viewport()->width() : (static_cast<int>(PANEL_W * 0.82) - 16);+ body->document()->setTextWidth(vw);+ const int h = qMax(static_cast<int>(body->document()->size().height()), 20);body->setFixedHeight(h);col_w->adjustSize();row->adjustSize();diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cppindex 8146144d5..ccb9311b4 100644--- a/fincept-qt/src/app/main.cpp+++ b/fincept-qt/src/app/main.cpp@@ -33,6 +33,7 @@#include "services/relationship_map/RelationshipMapService.h"#include "trading/DataStreamManager.h"#include "trading/ExchangeService.h"+#include "trading/ExchangeSessionManager.h"#include "storage/repositories/NewsArticleRepository.h"#include "storage/repositories/SettingsRepository.h"#include "storage/sqlite/CacheDatabase.h"@@ -117,8 +118,12 @@ int main(int argc, char* argv[]) {// Phase 2: register MarketDataService as the `market:quote:*` producer.fincept::datahub::register_metatypes();fincept::services::MarketDataService::instance().ensure_registered_with_hub();- // Phase 4: ExchangeService as the ws:kraken:* / ws:hyperliquid:* producer.- fincept::trading::ExchangeService::instance().ensure_registered_with_hub();+ // Phase 2 (multi-broker refactor): ExchangeSessionManager is the hub+ // producer for `ws:kraken:*` / `ws:hyperliquid:*`. Individual sessions+ // (created lazily by the manager) publish through its SessionPublisher+ // seam. ExchangeService keeps a back-compat shim but no longer registers+ // itself with the hub.+ fincept::trading::ExchangeSessionManager::instance().ensure_registered_with_hub();// Prediction Markets — multi-exchange tab (Polymarket, Kalshi, …).// PolymarketWebSocket is the hub producer for `prediction:polymarket:*`;// the adapter layer translates exchange-local types into the unified@@ -255,7 +260,7 @@ int main(int argc, char* argv[]) {log.set_tag_level(tag, lvl_map.value(level));}}- LOG_INFO("App", "Fincept Terminal v4.0.2 starting...");+ LOG_INFO("App", "Fincept Terminal v4.0.1 starting...");// Theme is applied after DB is open so saved font/theme are respected from the start.diff --git a/fincept-qt/src/core/net/NetSpeedMeter.cpp b/fincept-qt/src/core/net/NetSpeedMeter.cppnew file mode 100644index 000000000..fba69c0c7--- /dev/null+++ b/fincept-qt/src/core/net/NetSpeedMeter.cpp@@ -0,0 +1,222 @@+// src/core/net/NetSpeedMeter.cpp+#include "core/net/NetSpeedMeter.h"++#include "core/logging/Logger.h"++#include <QDateTime>++#if defined(Q_OS_WIN)+// The project defines WIN32_LEAN_AND_MEAN globally, which strips winsock from+// <windows.h>. Pull the pieces we need explicitly in the right order so+// MIB_IF_ROW2 / GetIfTable2 (declared in netioapi.h) compile cleanly.+# ifndef _WINSOCKAPI_+# define _WINSOCKAPI_ // prevent windows.h from including winsock1+# endif+# include <winsock2.h>+# include <ws2tcpip.h>+# include <windows.h>+# include <iphlpapi.h>+# include <netioapi.h>+# pragma comment(lib, "iphlpapi.lib")+#elif defined(Q_OS_MACOS)+# include <ifaddrs.h>+# include <net/if.h>+# include <net/if_dl.h>+# include <sys/socket.h>+# include <string.h>+#elif defined(Q_OS_LINUX)+# include <QFile>+# include <QRegularExpression>+# include <QTextStream>+#endif++namespace fincept::net {++NetSpeedMeter::NetSpeedMeter(QObject* parent) : QObject(parent) {+ timer_ = new QTimer(this);+ timer_->setInterval(1000);+ connect(timer_, &QTimer::timeout, this, &NetSpeedMeter::sample);+}++NetSpeedMeter::~NetSpeedMeter() = default;++void NetSpeedMeter::start(int interval_ms) {+ timer_->setInterval(interval_ms > 0 ? interval_ms : 1000);+ has_prev_ = false; // force fresh baseline on (re)start+ prev_rx_ = 0;+ prev_tx_ = 0;+ prev_tick_ms_ = 0;+ last_down_bps_ = 0;+ last_up_bps_ = 0;+ timer_->start();+ // Take the baseline sample immediately so the first delta is accurate.+ sample();+}++void NetSpeedMeter::stop() {+ if (timer_ && timer_->isActive())+ timer_->stop();+}++void NetSpeedMeter::sample() {+ quint64 rx = 0, tx = 0;+ if (!read_counters(rx, tx))+ return;++ const qint64 now_ms = QDateTime::currentMSecsSinceEpoch();++ if (!has_prev_) {+ prev_rx_ = rx;+ prev_tx_ = tx;+ prev_tick_ms_ = now_ms;+ has_prev_ = true;+ return;+ }++ const qint64 dt_ms = now_ms - prev_tick_ms_;+ if (dt_ms <= 0) {+ prev_rx_ = rx;+ prev_tx_ = tx;+ prev_tick_ms_ = now_ms;+ return;+ }++ // Guard against counter rollover / interface teardown — treat negative delta as 0.+ const quint64 drx = (rx >= prev_rx_) ? (rx - prev_rx_) : 0;+ const quint64 dtx = (tx >= prev_tx_) ? (tx - prev_tx_) : 0;++ last_down_bps_ = static_cast<qint64>((drx * 1000ULL) / static_cast<quint64>(dt_ms));+ last_up_bps_ = static_cast<qint64>((dtx * 1000ULL) / static_cast<quint64>(dt_ms));++ prev_rx_ = rx;+ prev_tx_ = tx;+ prev_tick_ms_ = now_ms;++ emit speed_changed(last_down_bps_, last_up_bps_);+}++QString NetSpeedMeter::format_bps(qint64 bps) {+ if (bps < 0) bps = 0;+ constexpr qint64 KB = 1024;+ constexpr qint64 MB = 1024 * 1024;+ constexpr qint64 GB = 1024LL * 1024LL * 1024LL;+ if (bps >= GB) return QString::number(static_cast<double>(bps) / GB, 'f', 2) + " GB/s";+ if (bps >= MB) return QString::number(static_cast<double>(bps) / MB, 'f', 2) + " MB/s";+ if (bps >= KB) return QString::number(static_cast<double>(bps) / KB, 'f', 1) + " KB/s";+ return QString::number(bps) + " B/s";+}++// ─────────────────────────────────────────────────────────────────────────────+// Platform backends+// ─────────────────────────────────────────────────────────────────────────────++#if defined(Q_OS_WIN)++bool NetSpeedMeter::read_counters(quint64& rx_bytes, quint64& tx_bytes) const {+ PMIB_IF_TABLE2 table = nullptr;+ if (GetIfTable2(&table) != NO_ERROR || !table) {+ if (table) FreeMibTable(table);+ return false;+ }++ quint64 rx = 0, tx = 0;+ for (ULONG i = 0; i < table->NumEntries; ++i) {+ const MIB_IF_ROW2& row = table->Table[i];+ // Skip loopback and tunnel pseudo-interfaces.+ if (row.Type == IF_TYPE_SOFTWARE_LOOPBACK ||+ row.Type == IF_TYPE_TUNNEL)+ continue;+ // Only count connected / operational interfaces — idle adapters still+ // report 0 deltas, but this avoids counting disabled virtual adapters.+ if (row.OperStatus != IfOperStatusUp)+ continue;++ rx += row.InOctets;+ tx += row.OutOctets;+ }++ FreeMibTable(table);+ rx_bytes = rx;+ tx_bytes = tx;+ return true;+}++#elif defined(Q_OS_MACOS)++bool NetSpeedMeter::read_counters(quint64& rx_bytes, quint64& tx_bytes) const {+ struct ifaddrs* ifap = nullptr;+ if (getifaddrs(&ifap) != 0 || !ifap)+ return false;++ quint64 rx = 0, tx = 0;+ for (struct ifaddrs* ifa = ifap; ifa != nullptr; ifa = ifa->ifa_next) {+ if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_LINK)+ continue;+ if (!ifa->ifa_name || strncmp(ifa->ifa_name, "lo", 2) == 0)+ continue;+ if (!(ifa->ifa_flags & IFF_UP))+ continue;++ const struct if_data* d = reinterpret_cast<struct if_data*>(ifa->ifa_data);+ if (!d)+ continue;+ rx += d->ifi_ibytes;+ tx += d->ifi_obytes;+ }++ freeifaddrs(ifap);+ rx_bytes = rx;+ tx_bytes = tx;+ return true;+}++#elif defined(Q_OS_LINUX)++bool NetSpeedMeter::read_counters(quint64& rx_bytes, quint64& tx_bytes) const {+ QFile f("/proc/net/dev");+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))+ return false;++ QTextStream ts(&f);+ // First two lines are headers.+ ts.readLine();+ ts.readLine();++ quint64 rx = 0, tx = 0;+ while (!ts.atEnd()) {+ const QString line = ts.readLine();+ const int colon = line.indexOf(':');+ if (colon < 0)+ continue;+ const QString iface = line.left(colon).trimmed();+ if (iface == QLatin1String("lo"))+ continue;++ const QStringList cols = line.mid(colon + 1).split(QRegularExpression("\\s+"),+ Qt::SkipEmptyParts);+ // Layout: rx_bytes, rx_packets, ..., tx_bytes at index 8, ...+ if (cols.size() < 9)+ continue;+ bool ok1 = false, ok2 = false;+ const quint64 r = cols[0].toULongLong(&ok1);+ const quint64 t = cols[8].toULongLong(&ok2);+ if (!ok1 || !ok2)+ continue;+ rx += r;+ tx += t;+ }++ rx_bytes = rx;+ tx_bytes = tx;+ return true;+}++#else++bool NetSpeedMeter::read_counters(quint64&, quint64&) const {+ return false; // unsupported platform — meter silently stays at 0+}++#endif++} // namespace fincept::netdiff --git a/fincept-qt/src/core/net/NetSpeedMeter.h b/fincept-qt/src/core/net/NetSpeedMeter.hnew file mode 100644index 000000000..afe7e6d85--- /dev/null+++ b/fincept-qt/src/core/net/NetSpeedMeter.h@@ -0,0 +1,62 @@+// src/core/net/NetSpeedMeter.h+//+// System-wide network throughput sampler.+//+// Samples OS interface counters once per second and emits bytes/sec deltas.+// Intended as a "liveness" indicator during long-running downloads (e.g. the+// first-run Python setup) — shows total machine network activity, not traffic+// from a specific process.+//+// Platform backends:+// Windows : GetIfTable2 (Iphlpapi) — sums InOctets / OutOctets over all+// non-loopback interfaces.+// macOS : getifaddrs + AF_LINK if_data — sums ifi_ibytes / ifi_obytes.+// Linux : /proc/net/dev — sums rx_bytes / tx_bytes (excludes `lo`).+//+// Thread-safety: single-threaded; sample on the owning QObject's thread.+#pragma once++#include <QObject>+#include <QTimer>+#include <cstdint>++namespace fincept::net {++class NetSpeedMeter : public QObject {+ Q_OBJECT+ public:+ explicit NetSpeedMeter(QObject* parent = nullptr);+ ~NetSpeedMeter() override;++ /// Start periodic sampling. Default 1-second cadence.+ void start(int interval_ms = 1000);++ /// Stop sampling (safe to call if not running).+ void stop();++ /// Last-measured down/up bytes per second (0 until first delta).+ qint64 down_bps() const { return last_down_bps_; }+ qint64 up_bps() const { return last_up_bps_; }++ /// Format a bytes/sec value as human-readable string, e.g. "3.2 MB/s".+ static QString format_bps(qint64 bytes_per_sec);++ signals:+ /// Fired on every sample after the first (need two samples to compute delta).+ void speed_changed(qint64 down_bps, qint64 up_bps);++ private:+ void sample();+ // Platform-specific cumulative counters; returns false on failure.+ bool read_counters(quint64& rx_bytes, quint64& tx_bytes) const;++ QTimer* timer_ = nullptr;+ bool has_prev_ = false;+ quint64 prev_rx_ = 0;+ quint64 prev_tx_ = 0;+ qint64 prev_tick_ms_ = 0;+ qint64 last_down_bps_ = 0;+ qint64 last_up_bps_ = 0;+};++} // namespace fincept::netdiff --git a/fincept-qt/src/mcp/McpClient.cpp b/fincept-qt/src/mcp/McpClient.cppindex 8cbaf762c..719b8942a 100644--- a/fincept-qt/src/mcp/McpClient.cpp+++ b/fincept-qt/src/mcp/McpClient.cpp@@ -168,7 +168,7 @@ Result<QJsonObject> McpClient::initialize() {QJsonObject client_info;client_info["name"] = "FinceptTerminal";- client_info["version"] = "4.0.2";+ client_info["version"] = "4.0.1";params["clientInfo"] = client_info;QJsonObject capabilities;diff --git a/fincept-qt/src/python/PythonSetupManager.cpp b/fincept-qt/src/python/PythonSetupManager.cppindex 464f39285..f89d7775c 100644--- a/fincept-qt/src/python/PythonSetupManager.cpp+++ b/fincept-qt/src/python/PythonSetupManager.cpp@@ -21,6 +21,7 @@#include <QThread>#include <QtConcurrent>+#include <algorithm>#include <atomic>namespace fincept::python {@@ -104,6 +105,33 @@ QString PythonSetupManager::python_path(const QString& venv_name) const {#endif}+// Shared UV env — applied to every `uv` invocation so download/install behaviour+// is consistent across platforms. See header for per-var rationale.+//+// Concurrency is clamped on both ends so the same defaults are safe on a 2-core+// / 4 GB netbook and a 32-core workstation:+// - installs: floor 2 (so single-core CPUs still parallelise I/O), ceiling 8+// (more workers don't help — install is disk-bound — but they+// do consume RAM unpacking torch/catboost wheels in parallel).+// - downloads: ceiling 8 too. UV's own default is 50; capping prevents a+// slow / metered connection on a low-end machine from opening+// dozens of TLS sockets at once.+QStringList PythonSetupManager::uv_env_extra() const {+ const QString root = install_dir();+ const int cores = QThread::idealThreadCount();+ const int installs = std::clamp(cores, 2, 8);+ const int downloads = std::clamp(cores * 2, 4, 8);+ return {+ "UV_PYTHON_INSTALL_DIR=" + root + "/python",+ "UV_CACHE_DIR=" + root + "/uv-cache",+ "UV_LINK_MODE=hardlink",+ "UV_COMPILE_BYTECODE=1",+ "UV_CONCURRENT_DOWNLOADS=" + QString::number(downloads),+ "UV_CONCURRENT_INSTALLS=" + QString::number(installs),+ "UV_HTTP_TIMEOUT=120",+ };+}+// ─────────────────────────────────────────────────────────────────────────────// Marker / hash helpers//@@ -706,10 +734,8 @@ bool PythonSetupManager::download_uv() {bool PythonSetupManager::install_python_via_uv() {emit_progress("python", 20, "UV is downloading Python 3.12...");- // Tell UV where to install Python- QStringList env = {- "UV_PYTHON_INSTALL_DIR=" + install_dir() + "/python",- };+ // Shared UV env (cache dir, hardlinks, bytecode compile, concurrency, timeout).+ QStringList env = uv_env_extra();if (!run_command(uv_path(), {"python", "install", kPythonVersion}, env)) {LOG_ERROR("PythonSetup", "uv python install failed");@@ -748,9 +774,7 @@ bool PythonSetupManager::create_venv(const QString& venv_name) {QDir(venv_path).removeRecursively();}- QStringList env = {- "UV_PYTHON_INSTALL_DIR=" + install_dir() + "/python",- };+ QStringList env = uv_env_extra();if (run_command(uv_path(), {"venv", venv_path, "--python", kPythonVersion}, env)) {LOG_INFO("PythonSetup", "Created venv: " + venv_name);@@ -793,11 +817,11 @@ bool PythonSetupManager::install_packages(const QString& venv_name, const QStrinconst QString venv_python = python_path(venv_name);- QStringList env = {- "UV_PYTHON_INSTALL_DIR=" + install_dir() + "/python",- "PEEWEE_NO_SQLITE_EXTENSIONS=1",- "PEEWEE_NO_C_EXTENSION=1",- };+ // Shared UV env + peewee build flags (peewee is a transitive dep that fails+ // to build its C extension under the embedded Python on some platforms).+ QStringList env = uv_env_extra();+ env << "PEEWEE_NO_SQLITE_EXTENSIONS=1"+ << "PEEWEE_NO_C_EXTENSION=1";// ── Pass 1: try installing everything at once (fast path) ────────────────// This succeeds on most machines and is 10-100x faster than one-by-one.diff --git a/fincept-qt/src/python/PythonSetupManager.h b/fincept-qt/src/python/PythonSetupManager.hindex a3c3dca27..836f0f3df 100644--- a/fincept-qt/src/python/PythonSetupManager.h+++ b/fincept-qt/src/python/PythonSetupManager.h@@ -80,6 +80,15 @@ class PythonSetupManager : public QObject {QString find_requirements_file(const QString& filename) const;// Helpers+ // Shared UV env vars applied to every uv invocation. Returns:+ // UV_PYTHON_INSTALL_DIR — keep Python under our install dir+ // UV_CACHE_DIR — wheels cached beside the app so reinstalls reuse them+ // UV_LINK_MODE=hardlink — hardlink wheels from cache → venv (no copy) when same FS+ // UV_COMPILE_BYTECODE=1 — pay .pyc cost once at install, not at first import+ // UV_CONCURRENT_DOWNLOADS / UV_CONCURRENT_INSTALLS — bump UV's defaults+ // UV_HTTP_TIMEOUT=120 — tolerate slow CDN edges without failing the bulk pass+ QStringList uv_env_extra() const;+bool run_command(const QString& program, const QStringList& args, const QStringList& env_vars = {}) const;// Like run_command but captures stderr — used for per-package failure diagnosis.bool run_command_capture(const QString& program, const QStringList& args, const QStringList& env_vars,diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cppindex dda6ab977..9e2547f17 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp@@ -3,6 +3,8 @@#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"+#include "datahub/DataHub.h"+#include "datahub/DataHubMetaTypes.h"#include "screens/crypto_trading/CryptoBottomPanel.h"#include "screens/crypto_trading/CryptoChart.h"#include "screens/crypto_trading/CryptoCredentials.h"@@ -37,20 +39,17 @@ static const QString TAG = "CryptoTrading";// ============================================================================CryptoTradingScreen::CryptoTradingScreen(QWidget* parent) : QWidget(parent) {+ LOG_INFO(TAG, "Constructing CryptoTradingScreen");setup_ui();setup_timers();+ LOG_INFO(TAG, "CryptoTradingScreen construction complete");}CryptoTradingScreen::~CryptoTradingScreen() {- auto& es = ExchangeService::instance();- if (ws_price_cb_id_ >= 0)- es.remove_price_callback(ws_price_cb_id_);- if (ws_ob_cb_id_ >= 0)- es.remove_orderbook_callback(ws_ob_cb_id_);- if (ws_candle_cb_id_ >= 0)- es.remove_candle_callback(ws_candle_cb_id_);- if (ws_trade_cb_id_ >= 0)- es.remove_trade_callback(ws_trade_cb_id_);+ LOG_INFO(TAG, "Destroying CryptoTradingScreen");+ // Drop hub subscriptions owned by this screen. DataHub::unsubscribe is+ // also safe if no sub exists (e.g. constructor threw before init).+ fincept::datahub::DataHub::instance().unsubscribe(this);}// ============================================================================@@ -148,8 +147,12 @@ void CryptoTradingScreen::setup_ui() {exchange_btn_->setFixedHeight(22);exchange_btn_->setCursor(Qt::PointingHandCursor);exchange_menu_ = new QMenu(exchange_btn_);- for (const auto& ex :- {"kraken", "binance", "bybit", "okx", "coinbase", "bitget", "gate", "kucoin", "mexc", "htx"}) {+ // Only exchanges registered as DataHub producers (see+ // ExchangeSessionManager::topic_patterns) can be consumed by this screen+ // post-Phase 6. Adding a new exchange here is a two-step job: add the+ // topic patterns on the manager AND register the C++ metatypes with the+ // hub, then add it to this list.+ for (const auto& ex : {"kraken", "hyperliquid"}) {exchange_menu_->addAction(ex, this, [this, ex]() { on_exchange_changed(ex); });}exchange_btn_->setMenu(exchange_menu_);@@ -295,7 +298,9 @@ void CryptoTradingScreen::setup_timers() {watchlist_timer_ = new QTimer(this);connect(watchlist_timer_, &QTimer::timeout, this, &CryptoTradingScreen::refresh_watchlist);- watchlist_timer_->setInterval(15000);+ // 10 s — the watchlist is always polled in parallel with the WS stream+ // (see apply_feed_mode) because illiquid tickers don't tick often on WS.+ watchlist_timer_->setInterval(10000);market_info_timer_ = new QTimer(this);connect(market_info_timer_, &QTimer::timeout, this, &CryptoTradingScreen::refresh_market_info);@@ -376,94 +381,176 @@ void CryptoTradingScreen::update_clock() {// Init// ============================================================================-void CryptoTradingScreen::init_exchange() {- auto& es = ExchangeService::instance();- es.set_exchange(exchange_id_);+// ============================================================================+// DataHub subscription path (the only path since Phase 6 removed the legacy+// callback fallback). Every supported exchange must be a DataHub producer+// registered via ExchangeSessionManager::topic_patterns().+// ============================================================================- if (!es.is_feed_running())- es.start_price_feed(5);+void CryptoTradingScreen::hub_subscribe_topics() {+ auto& hub = fincept::datahub::DataHub::instance();- es.start_ws_stream(selected_symbol_, watchlist_symbols_);+ // Always drop our prior subscriptions wholesale before re-subscribing —+ // cheaper than deltas and leaves no room for stale topics to leak.+ hub.unsubscribe(this);- // WS price callback → accumulate into pending buffers (flushed at 10fps by ws_flush_timer_)- // This coalesces ~50 msgs/sec into ~10 UI updates/sec.- // QPointer guard: callbacks are invoked from the WS reader thread, so the- // widget could be torn down between dispatch and our lambda body running.- QPointer<CryptoTradingScreen> self = this;- ws_price_cb_id_ = es.on_price_update([self](const QString& symbol, const TickerData& ticker) {- if (!self) return;- QMetaObject::invokeMethod(- self.data(),- [self, symbol, ticker]() {- if (!self) return;- self->pending_tickers_[symbol] = ticker; // latest wins per symbol- if (symbol == self->selected_symbol_) {- self->pending_primary_ticker_ = ticker;- self->has_pending_primary_ = true;- }- },- Qt::QueuedConnection);- });+ const QString exch = exchange_id_;+ const QString primary = selected_symbol_;- // WS orderbook callback → buffer latest; flushed at 10fps by ws_flush_timer_- ws_ob_cb_id_ = es.on_orderbook_update([self](const QString& symbol, const OrderBookData& ob) {- if (!self || symbol != self->selected_symbol_)+ // 1. Primary-symbol ticker → ticker bar + order entry + paper bookkeeping.+ // Uses the coalesced ticker policy (50 ms window).+ const QString ticker_topic = QStringLiteral("ws:") + exch + QStringLiteral(":ticker:") + primary;+ QPointer<CryptoTradingScreen> self = this;+ hub.subscribe(this, ticker_topic, [self, primary](const QVariant& v) {+ if (!self || !v.canConvert<fincept::trading::TickerData>())return;- QMetaObject::invokeMethod(- self.data(),- [self, ob]() {- if (!self) return;- self->pending_orderbook_ = ob;- self->has_pending_orderbook_ = true;- },- Qt::QueuedConnection);+ const auto t = v.value<fincept::trading::TickerData>();+ self->pending_tickers_[t.symbol.isEmpty() ? primary : t.symbol] = t;+ if (self->selected_symbol_ == primary) {+ self->pending_primary_ticker_ = t;+ self->has_pending_primary_ = true;+ }});- // WS candle callback → buffer pending candles; flushed at 10fps by ws_flush_timer_- ws_candle_cb_id_ = es.on_candle_update([self](const QString& symbol, const Candle& candle) {- if (!self || symbol != self->selected_symbol_)+ // 2. Primary-symbol orderbook.+ const QString ob_topic = QStringLiteral("ws:") + exch + QStringLiteral(":orderbook:") + primary;+ hub.subscribe(this, ob_topic, [self, primary](const QVariant& v) {+ if (!self || self->selected_symbol_ != primary)return;- QMetaObject::invokeMethod(- self.data(),- [self, candle]() {- if (!self) return;- self->pending_candles_.append(candle);- },- Qt::QueuedConnection);+ if (!v.canConvert<fincept::trading::OrderBookData>())+ return;+ self->pending_orderbook_ = v.value<fincept::trading::OrderBookData>();+ self->has_pending_orderbook_ = true;});- // WS trade callback → buffer trade entries; flushed at 10fps by ws_flush_timer_- ws_trade_cb_id_ = es.on_trade_update([self](const QString& symbol, const TradeData& trade) {- if (!self || symbol != self->selected_symbol_)+ // 3. Primary-symbol trades → time & sales + fast-path ticker update.+ const QString trades_topic = QStringLiteral("ws:") + exch + QStringLiteral(":trades:") + primary;+ hub.subscribe(this, trades_topic, [self, primary](const QVariant& v) {+ if (!self || self->selected_symbol_ != primary)return;- TradeEntry entry;- entry.side = trade.side;- entry.price = trade.price;- entry.amount = trade.amount;- QMetaObject::invokeMethod(- self.data(),- [self, entry]() {- if (!self) return;- self->pending_trades_.append(entry);- },- Qt::QueuedConnection);+ if (!v.canConvert<fincept::trading::TradeData>())+ return;+ const auto td = v.value<fincept::trading::TradeData>();+ crypto::TradeEntry e;+ e.side = td.side;+ e.price = td.price;+ e.amount = td.amount;+ self->pending_trades_.append(e);});- initialized_ = true;+ // 4. Watchlist tickers — pattern subscribe to ws:<exch>:ticker:* so new+ // symbols added to the watchlist later don't need extra wiring. The+ // pattern matches the primary topic too, but duplicate delivery is+ // harmless (pending_tickers_ is latest-wins per symbol).+ const QString ticker_pattern = QStringLiteral("ws:") + exch + QStringLiteral(":ticker:*");+ hub.subscribe_pattern(this, ticker_pattern,+ [self](const QString& /*topic*/, const QVariant& v) {+ if (!self || !v.canConvert<fincept::trading::TickerData>())+ return;+ const auto t = v.value<fincept::trading::TickerData>();+ if (t.symbol.isEmpty())+ return;+ self->pending_tickers_[t.symbol] = t;+ });++ // 5. Candles — subscribe pattern for the primary symbol across all+ // intervals (the chart's current timeframe may change during the+ // session; a pattern sub avoids having to resubscribe on every+ // timeframe change). Filter by the exact symbol in the slot.+ const QString ohlc_pattern = QStringLiteral("ws:") + exch + QStringLiteral(":ohlc:") + primary ++ QStringLiteral(":*");+ hub.subscribe_pattern(this, ohlc_pattern,+ [self, primary](const QString& /*topic*/, const QVariant& v) {+ if (!self || self->selected_symbol_ != primary)+ return;+ if (!v.canConvert<fincept::trading::Candle>())+ return;+ self->pending_candles_.append(v.value<fincept::trading::Candle>());+ });++ LOG_INFO(TAG, QString("DataHub subscriptions attached: %1 / %2").arg(exch, primary));}-void CryptoTradingScreen::load_portfolio() {- auto existing = pt_find_portfolio("Crypto Paper", exchange_id_);- if (existing) {- portfolio_ = *existing;- portfolio_id_ = portfolio_.id;+void CryptoTradingScreen::hub_unsubscribe_topics() {+ fincept::datahub::DataHub::instance().unsubscribe(this);+ LOG_INFO(TAG, "DataHub subscriptions detached");+}++void CryptoTradingScreen::init_exchange() {+ auto& es = ExchangeService::instance();+ es.set_exchange(exchange_id_);++ if (!es.is_feed_running())+ es.start_price_feed(5);++ // Phase 3: only spawn the WS subprocess if this session doesn't already+ // have one running. On switch-back to a warm exchange, the session's WS+ // is still up (ExchangeSessionManager keeps sessions warm for the app+ // lifetime) and we should just attach our callbacks to its live stream.+ if (!es.is_ws_active()) {+ const bool ws_spawned = es.start_ws_stream(selected_symbol_, watchlist_symbols_);+ if (!ws_spawned) {+ // WS failed to launch (bad paths, missing broker creds, etc.). Surface+ // the state on the status label and keep REST polling so the screen+ // still displays data via scripts.+ LOG_ERROR(TAG, "WS stream failed to start — remaining on REST polling for " + exchange_id_);+ if (ws_status_) {+ ws_status_->setText("REST");+ ws_status_->setStyleSheet(QString("color: %1;").arg(ui::colors::WARNING()));+ }+ last_ws_status_label_state_ = 0;+ }} else {- portfolio_ =- pt_create_portfolio("Crypto Paper", DEFAULT_PAPER_BALANCE, "USD", 1.0, "cross", 0.001, exchange_id_);- portfolio_id_ = portfolio_.id;+ LOG_INFO(TAG, "WS already active for " + exchange_id_ + " — attaching to warm session");}- ExchangeService::instance().watch_symbol(selected_symbol_, portfolio_id_);- refresh_portfolio();++ // Hub is the only consumer path. Every exchange shown in the dropdown+ // must have a matching producer registered on ExchangeSessionManager.+ hub_subscribe_topics();+ initialized_ = true;+ LOG_INFO(TAG, QString("Exchange initialised via hub: %1 / %2").arg(exchange_id_, selected_symbol_));+}++void CryptoTradingScreen::load_portfolio() {+ // pt_find_portfolio / pt_create_portfolio hit SQLite. Run on a worker so+ // the UI thread isn't blocked on exchange-switch or cold boot. Capture the+ // exchange id by value — if the user switches again before the worker+ // returns, the result will be applied under the *new* id, which is fine+ // because watch_symbol is called under the then-current selected_symbol_.+ QPointer<CryptoTradingScreen> self = this;+ const QString exch = exchange_id_;+ QtConcurrent::run([self, exch]() {+ if (!self)+ return;+ trading::PtPortfolio portfolio;+ try {+ auto existing = pt_find_portfolio("Crypto Paper", exch);+ if (existing) {+ portfolio = *existing;+ } else {+ portfolio = pt_create_portfolio("Crypto Paper", DEFAULT_PAPER_BALANCE, "USD", 1.0, "cross", 0.001, exch);+ }+ } catch (const std::exception& e) {+ LOG_ERROR("CryptoTradingScreen", QString("load_portfolio failed: %1").arg(e.what()));+ return;+ } catch (...) {+ LOG_ERROR("CryptoTradingScreen", "load_portfolio failed: unknown exception");+ return;+ }+ if (!self)+ return;+ QMetaObject::invokeMethod(+ self,+ [self, portfolio]() {+ if (!self)+ return;+ self->portfolio_ = portfolio;+ self->portfolio_id_ = portfolio.id;+ ExchangeService::instance().watch_symbol(self->selected_symbol_, self->portfolio_id_);+ self->refresh_portfolio();+ },+ Qt::QueuedConnection);+ });}// ============================================================================@@ -559,18 +646,18 @@ void CryptoTradingScreen::async_fetch_live_balance() {void CryptoTradingScreen::on_exchange_changed(const QString& exchange) {if (exchange == exchange_id_)return;+ LOG_INFO(TAG, QString("Exchange changed: %1 → %2").arg(exchange_id_, exchange));exchange_id_ = exchange;exchange_btn_->setText(exchange.toUpper());auto& es = ExchangeService::instance();- // Tear down current WS stream + drop stale callbacks so ticks from the- // previous exchange can't race into buffers post-switch.- es.stop_ws_stream();- if (ws_price_cb_id_ >= 0) { es.remove_price_callback(ws_price_cb_id_); ws_price_cb_id_ = -1; }- if (ws_ob_cb_id_ >= 0) { es.remove_orderbook_callback(ws_ob_cb_id_); ws_ob_cb_id_ = -1; }- if (ws_candle_cb_id_ >= 0) { es.remove_candle_callback(ws_candle_cb_id_); ws_candle_cb_id_ = -1; }- if (ws_trade_cb_id_ >= 0) { es.remove_trade_callback(ws_trade_cb_id_); ws_trade_cb_id_ = -1; }+ // Phase 3: sessions stay warm for the app lifetime. Do NOT stop the old+ // exchange's WS — `ExchangeSessionManager` keeps it running so switching+ // back is instant. Dropping our hub subscriptions is enough to stop the+ // old exchange's ticks landing in our pending_* buffers; the session+ // keeps updating its cache and publishing to the hub in the background.+ hub_unsubscribe_topics();// Clear accumulated buffers — stale data from the old exchange is useless.pending_tickers_.clear();@@ -582,14 +669,32 @@ void CryptoTradingScreen::on_exchange_changed(const QString& exchange) {pending_trades_.clear();last_ws_state_ = -1; // re-evaluate feed mode after new stream connects+ // Reset fetch guards — a prior in-flight fetch from the old exchange must+ // not suppress the first fetch against the new exchange.+ candles_fetching_.store(false);+ live_inflight_.store(0);+es.set_exchange(exchange_id_);- // Re-initialize — this re-registers all four WS callbacks + starts the stream.+ // Re-initialize — re-registers the four WS callbacks on the NEW session.+ // If that session's WS is already warm (we visited it earlier), init_exchange+ // skips the start_ws_stream() call, so there's no second handshake.initialized_ = false;init_exchange();load_portfolio();++ // Prime the screen with data from the new exchange immediately rather than+ // waiting for the WS to connect or the 3s polling timer to tick — otherwise+ // ticker / orderbook / chart stay blank for seconds after every switch.+ // On switch-back to a warm session the session's cache is already populated,+ // so refresh_ticker / refresh_orderbook hit it immediately.async_fetch_candles(selected_symbol_, chart_->current_timeframe());+ refresh_ticker();+ refresh_orderbook();+ refresh_watchlist();+ refresh_market_info();+ScreenStateManager::instance().notify_changed(this);}@@ -601,6 +706,7 @@ void CryptoTradingScreen::on_symbol_selected(const QString& symbol) {}void CryptoTradingScreen::switch_symbol(const QString& symbol) {+ LOG_INFO(TAG, QString("Symbol changed: %1 → %2").arg(selected_symbol_, symbol));auto& es = ExchangeService::instance();es.unwatch_symbol(selected_symbol_, portfolio_id_);selected_symbol_ = symbol;@@ -620,6 +726,13 @@ void CryptoTradingScreen::switch_symbol(const QString& symbol) {es.watch_symbol(selected_symbol_, portfolio_id_);es.set_ws_primary_symbol(symbol);++ // Three of the five subscriptions (ticker/orderbook/trades + ohlc+ // pattern) are primary-symbol-specific and need to be re-bound to the+ // new symbol. The watchlist ticker pattern doesn't change. Simpler to+ // resubscribe wholesale than diff.+ hub_subscribe_topics();+refresh_ticker();refresh_orderbook();async_fetch_candles(selected_symbol_, chart_->current_timeframe());@@ -653,6 +766,7 @@ void CryptoTradingScreen::on_api_clicked() {creds.secret = secret;creds.password = pw;ExchangeService::instance().set_credentials(creds);+ LOG_INFO(TAG, "Credentials saved for " + exchange_id_);});dlg->exec();dlg->deleteLater();@@ -660,6 +774,9 @@ void CryptoTradingScreen::on_api_clicked() {void CryptoTradingScreen::on_order_submitted(const QString& side, const QString& order_type, double qty, double price,double stop_price, double sl, double tp) {+ LOG_INFO(TAG, QString("Order submit: mode=%1 %2 %3 qty=%4 px=%5 stop=%6 sl=%7 tp=%8 sym=%9")+ .arg(trading_mode_ == TradingMode::Paper ? "PAPER" : "LIVE", side, order_type)+ .arg(qty).arg(price).arg(stop_price).arg(sl).arg(tp).arg(selected_symbol_));try {if (trading_mode_ == TradingMode::Paper) {auto ticker = ExchangeService::instance().get_cached_price(selected_symbol_);@@ -705,6 +822,7 @@ void CryptoTradingScreen::on_order_submitted(const QString& side, const QString&}void CryptoTradingScreen::on_cancel_order(const QString& order_id) {+ LOG_INFO(TAG, QString("Cancel order: %1 (%2)").arg(order_id, trading_mode_ == TradingMode::Paper ? "paper" : "live"));if (trading_mode_ == TradingMode::Paper) {try {pt_cancel_order(order_id);@@ -762,8 +880,16 @@ void CryptoTradingScreen::on_search_requested(const QString& filter) {// ============================================================================void CryptoTradingScreen::apply_feed_mode(bool ws_connected) {- // Called on WS-state edge transitions. When WS is live we can stop REST- // polling; when it drops we must restart so the screen keeps updating.+ // Called on WS-state edge transitions. When WS is live we can stop the+ // primary-symbol pollers (the WS ticker / orderbook stream covers them+ // at high rate); when it drops we must restart so the screen keeps+ // updating.+ //+ // The watchlist timer is an intentional exception: WS only pushes a+ // symbol's ticker when its price moves, so illiquid rows (WIF, PEPE,+ // etc.) can sit silent for minutes and display "--". Keeping the 15 s+ // REST refresh running in parallel guarantees every row in the watchlist+ // shows a price even when the market is quiet.const int desired = ws_connected ? 1 : 0;if (desired == last_ws_state_)return;@@ -772,14 +898,12 @@ void CryptoTradingScreen::apply_feed_mode(bool ws_connected) {if (ws_connected) {if (ticker_timer_ && ticker_timer_->isActive()) ticker_timer_->stop();if (ob_timer_ && ob_timer_->isActive()) ob_timer_->stop();- if (watchlist_timer_ && watchlist_timer_->isActive()) watchlist_timer_->stop();if (portfolio_timer_ && portfolio_timer_->isActive()) portfolio_timer_->stop();- LOG_INFO(TAG, "WS connected — REST polling paused");+ LOG_INFO(TAG, "WS connected — REST polling paused (watchlist poll kept running)");} else {if (isVisible()) {if (ticker_timer_ && !ticker_timer_->isActive()) ticker_timer_->start();if (ob_timer_ && !ob_timer_->isActive()) ob_timer_->start();- if (watchlist_timer_ && !watchlist_timer_->isActive()) watchlist_timer_->start();if (portfolio_timer_ && !portfolio_timer_->isActive()) portfolio_timer_->start();LOG_WARN(TAG, "WS disconnected — REST polling resumed");}@@ -909,14 +1033,44 @@ void CryptoTradingScreen::flush_ws_updates() {void CryptoTradingScreen::refresh_ticker() {if (!initialized_)return;- const auto cached = ExchangeService::instance().get_cached_price(selected_symbol_);+ auto& es = ExchangeService::instance();+ const auto cached = es.get_cached_price(selected_symbol_);if (cached.last > 0) {ticker_bar_->update_data(cached.last, cached.percentage, cached.high, cached.low, cached.base_volume,- ExchangeService::instance().is_ws_connected());+ es.is_ws_connected());if (cached.bid > 0 && cached.ask > 0)ticker_bar_->update_bid_ask(cached.bid, cached.ask, std::abs(cached.ask - cached.bid));order_entry_->set_current_price(cached.last);+ return;}++ // Cache miss + WS not connected — prime the ticker on a worker so the UI+ // doesn't stay empty waiting for the first WS tick after an exchange+ // switch or cold start. Skip if the WS is live: the tick will arrive.+ if (es.is_ws_connected())+ return;+ QPointer<CryptoTradingScreen> self = this;+ const QString symbol = selected_symbol_;+ QtConcurrent::run([self, symbol]() {+ if (!self)+ return;+ auto ticker = ExchangeService::instance().fetch_ticker(symbol);+ if (!self || ticker.last <= 0)+ return;+ QMetaObject::invokeMethod(+ self,+ [self, symbol, ticker]() {+ if (!self || self->selected_symbol_ != symbol)+ return;+ auto& es = ExchangeService::instance();+ self->ticker_bar_->update_data(ticker.last, ticker.percentage, ticker.high, ticker.low,+ ticker.base_volume, es.is_ws_connected());+ if (ticker.bid > 0 && ticker.ask > 0)+ self->ticker_bar_->update_bid_ask(ticker.bid, ticker.ask, std::abs(ticker.ask - ticker.bid));+ self->order_entry_->set_current_price(ticker.last);+ },+ Qt::QueuedConnection);+ });}void CryptoTradingScreen::refresh_orderbook() {diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.hindex d81d064cc..2d17e1b68 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h@@ -81,6 +81,12 @@ class CryptoTradingScreen : public QWidget, public IStatefulScreen {void async_set_leverage(int leverage);void async_set_margin_mode(const QString& mode);+ // ── DataHub subscription lifecycle (the only data path since Phase 6) ─+ // Only exchanges registered as DataHub producers via+ // ExchangeSessionManager::topic_patterns() can appear in the dropdown.+ void hub_subscribe_topics();+ void hub_unsubscribe_topics();+// ── Command bar widgets ──QPushButton* exchange_btn_ = nullptr;QMenu* exchange_menu_ = nullptr;@@ -116,11 +122,6 @@ class CryptoTradingScreen : public QWidget, public IStatefulScreen {QString portfolio_id_;trading::PtPortfolio portfolio_;- // WS callbacks- int ws_price_cb_id_ = -1;- int ws_ob_cb_id_ = -1;- int ws_candle_cb_id_ = -1;- int ws_trade_cb_id_ = -1;// Async fetch guardsstd::atomic<bool> candles_fetching_{false};diff --git a/fincept-qt/src/screens/markets/MarketPanel.cpp b/fincept-qt/src/screens/markets/MarketPanel.cppindex 8ce3b04f2..028745c26 100644--- a/fincept-qt/src/screens/markets/MarketPanel.cpp+++ b/fincept-qt/src/screens/markets/MarketPanel.cpp@@ -11,6 +11,7 @@#include <QMenu>#include <QPointer>#include <QResizeEvent>+#include <QStackedWidget>#include <QVBoxLayout>namespace fincept::screens {@@ -94,6 +95,7 @@ void MarketPanel::build_ui() {// causing the first panel in each column to grab disproportionate space.table_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);setup_table_columns();+ table_->setVisible(false); // hidden until first data arrivesbl->addWidget(table_);// Error state (hidden by default)@@ -111,6 +113,19 @@ void MarketPanel::build_ui() {error_widget_->setVisible(false);bl->addWidget(error_widget_);+ // Loading overlay (visible until first data)+ loading_widget_ = new QWidget(body_);+ auto* ll = new QVBoxLayout(loading_widget_);+ ll->setAlignment(Qt::AlignCenter);+ loading_label_ = new QLabel(" ⠋ LOADING");+ loading_label_->setAlignment(Qt::AlignCenter);+ ll->addWidget(loading_label_);+ bl->addWidget(loading_widget_);++ loading_timer_ = new QTimer(this);+ loading_timer_->setInterval(120);+ connect(loading_timer_, &QTimer::timeout, this, &MarketPanel::tick_loading_anim);+vl->addWidget(body_, 1);}@@ -197,6 +212,9 @@ void MarketPanel::refresh() {fetch_failed_ = false;title_label_->setText(config_.title.toUpper() + " ...");+ if (!has_data_)+ show_loading();+hub_resubscribe();}@@ -210,8 +228,11 @@ void MarketPanel::rebuild_from_cache() {}if (cached_quotes_.isEmpty())return;+ const bool first_data = !has_data_;has_data_ = true;title_label_->setText(config_.title.toUpper());+ if (first_data)+ hide_loading();show_data();}@@ -266,6 +287,29 @@ void MarketPanel::hub_unsubscribe_all() {}+void MarketPanel::show_loading() {+ loading_frame_ = 0;+ loading_widget_->setVisible(true);+ table_->setVisible(false);+ error_widget_->setVisible(false);+ loading_timer_->start();+}++void MarketPanel::hide_loading() {+ loading_timer_->stop();+ loading_widget_->setVisible(false);+}++void MarketPanel::tick_loading_anim() {+ // Braille spinner: ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏+ static const char* const kFrames[] = {+ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"+ };+ constexpr int kCount = 10;+ loading_frame_ = (loading_frame_ + 1) % kCount;+ loading_label_->setText(QString(" %1 LOADING").arg(kFrames[loading_frame_]));+}+void MarketPanel::show_data() {error_widget_->setVisible(false);table_->setVisible(true);@@ -394,6 +438,15 @@ void MarketPanel::refresh_theme() {QString("color:%1;font-size:%2px;font-family:'%3';background:transparent;").arg(ui::colors::NEGATIVE()).arg(fdata).arg(ff));+ if (loading_label_)+ loading_label_->setStyleSheet(+ QString("color:%1;font-size:%2px;font-family:'%3';background:transparent;letter-spacing:2px;")+ .arg(ui::colors::TEXT_DIM()).arg(fdata).arg(ff));++ if (loading_widget_)+ loading_widget_->setStyleSheet(+ QString("background:%1;").arg(ui::colors::BG_BASE()));+if (retry_btn_)retry_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;"diff --git a/fincept-qt/src/screens/markets/MarketPanel.h b/fincept-qt/src/screens/markets/MarketPanel.hindex e8bf45417..635a7f9a7 100644--- a/fincept-qt/src/screens/markets/MarketPanel.h+++ b/fincept-qt/src/screens/markets/MarketPanel.h@@ -7,6 +7,7 @@#include <QPushButton>#include <QSet>#include <QTableWidget>+#include <QTimer>#include <QWidget>namespace fincept::screens {@@ -51,6 +52,9 @@ class MarketPanel : public QWidget {void update_visible_rows();void show_error(const QString& msg);void show_data();+ void show_loading();+ void hide_loading();+ void tick_loading_anim();void refresh_theme();void open_cols_dropdown();@@ -76,11 +80,17 @@ class MarketPanel : public QWidget {QPushButton* delete_btn_ = nullptr;// Body: data table or error state- QWidget* body_ = nullptr;- QTableWidget* table_ = nullptr;- QWidget* error_widget_ = nullptr;- QLabel* error_label_ = nullptr;- QPushButton* retry_btn_ = nullptr;+ QWidget* body_ = nullptr;+ QTableWidget* table_ = nullptr;+ QWidget* error_widget_ = nullptr;+ QLabel* error_label_ = nullptr;+ QPushButton* retry_btn_ = nullptr;++ // Loading overlay (shown until first data arrives)+ QWidget* loading_widget_ = nullptr;+ QLabel* loading_label_ = nullptr;+ QTimer* loading_timer_ = nullptr;+ int loading_frame_ = 0;static constexpr int kHeaderH = 28;static constexpr int kColHeaderH = 22;diff --git a/fincept-qt/src/screens/polymarket/ExchangePresentation.cpp b/fincept-qt/src/screens/polymarket/ExchangePresentation.cppindex d3e34c93b..6e74f1b7d 100644--- a/fincept-qt/src/screens/polymarket/ExchangePresentation.cpp+++ b/fincept-qt/src/screens/polymarket/ExchangePresentation.cpp@@ -25,7 +25,7 @@ QString ExchangePresentation::format_price(double prob) const {}QString ExchangePresentation::format_volume(double v) const {- const QString sym = currency_symbol == QStringLiteral("$") ? QStringLiteral("$") : QStringLiteral("$");+ const QString sym = currency_symbol.isEmpty() ? QStringLiteral("$") : currency_symbol;// Currency badges like "USDC" are shown separately (account chip + stats// label) so volume formatting always uses a dollar-sign prefix; injecting// "USDC" into every cell would be noisy.@@ -46,38 +46,58 @@ ExchangePresentation::StatusBadge ExchangePresentation::status_badge(using namespace fincept::ui;- // Kalshi lifecycle is richer than Polymarket's binary active/closed.- // The adapter stashes the raw status string in extras["status"] so we- // can surface "DETERMINED" (contest over, awaiting settlement) vs- // "SETTLED" cleanly. Polymarket doesn't populate extras["status"] — we- // fall back to the active/closed bools.+ // Kalshi v2 statuses (Apr 2026): unopened, open, paused, closed, settled.+ // The adapter stashes the raw status string in extras["status"]. Polymarket+ // doesn't populate extras["status"] — fall back to the active/closed bools.const QString kalshi_status = market.extras.value(QStringLiteral("status")).toString().toLower();+ auto accent_bg = QColor(accent.red(), accent.green(), accent.blue(), 38);+if (exchange_id == QStringLiteral("kalshi") && !kalshi_status.isEmpty()) {- if (kalshi_status == QStringLiteral("settled") || kalshi_status == QStringLiteral("finalized")) {- return {QStringLiteral("SETTLED"), QColor(colors::POSITIVE()), QColor(22, 163, 74, 38)};- }- if (kalshi_status == QStringLiteral("determined")) {- return {QStringLiteral("DETERMINED"), accent, QColor(accent.red(), accent.green(), accent.blue(), 38)};+ if (kalshi_status == QStringLiteral("settled")) {+ return {QStringLiteral("SETTLED"), QColor(colors::POSITIVE()),+ QColor(22, 163, 74, 38),+ QStringLiteral("Market has been settled. Final outcome "+ "determined and payouts processed.")};}if (kalshi_status == QStringLiteral("closed")) {- return {QStringLiteral("CLOSED"), QColor(colors::TEXT_SECONDARY()), QColor(0, 0, 0, 0)};+ return {QStringLiteral("CLOSED"), accent, accent_bg,+ QStringLiteral("Trading halted. Awaiting settlement from "+ "Kalshi's source-of-truth resolution.")};+ }+ if (kalshi_status == QStringLiteral("paused")) {+ return {QStringLiteral("PAUSED"), QColor(colors::TEXT_SECONDARY()),+ QColor(0, 0, 0, 0),+ QStringLiteral("Trading temporarily halted by the exchange. "+ "Orders cannot be placed until reopened.")};}if (kalshi_status == QStringLiteral("open")) {- return {QStringLiteral("OPEN"), accent, QColor(accent.red(), accent.green(), accent.blue(), 38)};+ QString tip = QStringLiteral("Market is open for trading.");+ if (!market.end_date_iso.isEmpty())+ tip += QStringLiteral(" Closes ") + market.end_date_iso + QStringLiteral(".");+ return {QStringLiteral("OPEN"), accent, accent_bg, tip};}- if (kalshi_status == QStringLiteral("initialized")) {- return {QStringLiteral("PENDING"), QColor(colors::TEXT_DIM()), QColor(0, 0, 0, 0)};+ if (kalshi_status == QStringLiteral("unopened")) {+ QString tip = QStringLiteral("Market has not yet opened for trading.");+ if (!market.end_date_iso.isEmpty())+ tip += QStringLiteral(" Close time: ") + market.end_date_iso + QStringLiteral(".");+ return {QStringLiteral("PENDING"), QColor(colors::TEXT_DIM()),+ QColor(0, 0, 0, 0), tip};}}if (market.closed) {- return {QStringLiteral("RESOLVED"), QColor(colors::POSITIVE()), QColor(22, 163, 74, 38)};+ return {QStringLiteral("RESOLVED"), QColor(colors::POSITIVE()),+ QColor(22, 163, 74, 38),+ QStringLiteral("Market has resolved. No further trading.")};}if (market.active) {- return {QStringLiteral("ACTIVE"), accent, QColor(accent.red(), accent.green(), accent.blue(), 38)};+ return {QStringLiteral("ACTIVE"), accent, accent_bg,+ QStringLiteral("Market is accepting orders.")};}- return {QStringLiteral("INACTIVE"), QColor(colors::TEXT_DIM()), QColor(0, 0, 0, 0)};+ return {QStringLiteral("INACTIVE"), QColor(colors::TEXT_DIM()),+ QColor(0, 0, 0, 0),+ QStringLiteral("Market not currently trading.")};}// ── Factories ───────────────────────────────────────────────────────────────@@ -119,14 +139,17 @@ ExchangePresentation ExchangePresentation::for_kalshi() {p.price_style = PriceStyle::Dollars;p.price_decimal_places = 2;p.view_names = {QStringLiteral("MARKETS"), QStringLiteral("EVENTS"),- QStringLiteral("SETTLED")};+ QStringLiteral("SETTLED"), QStringLiteral("HISTORY")};p.default_view = QStringLiteral("MARKETS");// Kalshi's series catalog can exceed 100 entries — a chip row doesn't// scale. Drop into a dropdown so users can scan + filter.p.category_mode = CategoryMode::ComboBox;p.category_visible_cap = 0; // unused in combobox modep.chart_y_label = QStringLiteral("PRICE");- p.has_open_interest = false; // Kalshi REST doesn't expose OI per market+ // Kalshi exposes open_interest_fp per market — surface it. Polymarket+ // also has it via a separate data endpoint; the detail panel renders+ // both through the same OI box.+ p.has_open_interest = true;p.has_polymarket_extras = false; // no holders / comments / relatedp.has_leaderboard = false;return p;diff --git a/fincept-qt/src/screens/polymarket/ExchangePresentation.h b/fincept-qt/src/screens/polymarket/ExchangePresentation.hindex b4b7689dc..2301110a9 100644--- a/fincept-qt/src/screens/polymarket/ExchangePresentation.h+++ b/fincept-qt/src/screens/polymarket/ExchangePresentation.h@@ -71,7 +71,8 @@ struct ExchangePresentation {struct StatusBadge {QString text;QColor fg;- QColor bg; // may be transparent+ QColor bg; // may be transparent+ QString tooltip; // optional long-form description for hover};StatusBadge status_badge(const fincept::services::prediction::PredictionMarket& market) const;diff --git a/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.cpp b/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.cppindex 95384aad5..a5fb70660 100644--- a/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.cpp@@ -2,8 +2,11 @@#include "ui/theme/Theme.h"+#include <QBrush>#include <QDateTime>#include <QHeaderView>+#include <QPointer>+#include <QTimer>#include <QVBoxLayout>namespace fincept::screens::polymarket {@@ -11,6 +14,55 @@ namespace fincept::screens::polymarket {using namespace fincept::ui;using namespace fincept::services::prediction;+namespace {++constexpr int kMaxRows = 200;+constexpr int kFlashMs = 600;++void apply_row(QTableWidget* table, int row, const PredictionTrade& t, int price_decimals) {+ const QString time = QDateTime::fromMSecsSinceEpoch(t.ts_ms, Qt::UTC).toString("HH:mm:ss");+ table->setItem(row, 0, new QTableWidgetItem(time));+ table->setItem(row, 1, new QTableWidgetItem("TRADE"));++ auto* side_item = new QTableWidgetItem(t.side);+ side_item->setForeground(QColor(t.side.compare("BUY", Qt::CaseInsensitive) == 0+ ? colors::POSITIVE()+ : colors::NEGATIVE()));+ table->setItem(row, 2, side_item);++ auto* price_item = new QTableWidgetItem(QString::number(t.price, 'f', price_decimals));+ price_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ price_item->setForeground(QColor(colors::CYAN()));+ table->setItem(row, 3, price_item);++ auto* size_item = new QTableWidgetItem(QString::number(t.size, 'f', 2));+ size_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table->setItem(row, 4, size_item);+}++void flash_row(QTableWidget* table, int row, const QColor& accent) {+ if (row < 0 || row >= table->rowCount()) return;+ // Tint the row's backgrounds; clear after kFlashMs so the highlight+ // decays without needing per-row animation timers.+ QColor tint = accent;+ tint.setAlpha(90);+ for (int c = 0; c < table->columnCount(); ++c) {+ if (auto* it = table->item(row, c))+ it->setBackground(QBrush(tint));+ }+ QPointer<QTableWidget> guard = table;+ QTimer::singleShot(kFlashMs, table, [guard, row]() {+ if (!guard) return;+ if (row >= guard->rowCount()) return;+ for (int c = 0; c < guard->columnCount(); ++c) {+ if (auto* it = guard->item(row, c))+ it->setBackground(QBrush(Qt::NoBrush));+ }+ });+}++} // namespace+PolymarketActivityFeed::PolymarketActivityFeed(QWidget* parent) : QWidget(parent) {auto* vl = new QVBoxLayout(this);vl->setContentsMargins(0, 0, 0, 0);@@ -19,51 +71,67 @@ PolymarketActivityFeed::PolymarketActivityFeed(QWidget* parent) : QWidget(parenttable_->setColumnCount(5);table_->setHorizontalHeaderLabels({"TIME", "TYPE", "SIDE", "PRICE", "SIZE"});table_->horizontalHeader()->setStretchLastSection(true);+ table_->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);table_->verticalHeader()->setVisible(false);table_->setEditTriggers(QAbstractItemView::NoEditTriggers);table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setShowGrid(false);table_->setStyleSheet(- QString("QTableWidget { background: %1; color: %2; border: none; gridline-color: %3; font-size: 11px; }"- "QTableWidget::item { padding: 2px 6px; border-bottom: 1px solid %3; }"- "QHeaderView::section { background: %4; color: %5; border: none; "- " border-bottom: 1px solid %3; padding: 4px 6px; font-size: 10px; font-weight: 700; }")- .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));+ QString("QTableWidget {"+ " background: %1; color: %2; border: none; font-size: 10px;"+ "}"+ "QTableWidget::item {"+ " padding: 3px 8px; border-bottom: 1px solid %3;"+ "}"+ "QTableWidget::item:selected { background: %4; color: %2; }"+ "QHeaderView::section {"+ " background: %5; color: %6; border: none;"+ " border-bottom: 1px solid %3;"+ " padding: 5px 8px; font-size: 8px; font-weight: 700; letter-spacing: 0.5px;"+ "}"+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(),+ colors::BG_HOVER(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));vl->addWidget(table_);}void PolymarketActivityFeed::set_trades(const QVector<PredictionTrade>& trades) {last_trades_ = trades;table_->setSortingEnabled(false);- const int count = qMin(trades.size(), 200);+ const int count = qMin(trades.size(), kMaxRows);table_->setRowCount(count);const int price_decimals = qBound(0, presentation_.price_decimal_places, 6);for (int i = 0; i < count; ++i) {- const auto& t = trades[i];- // prediction::PredictionTrade uses ts_ms (milliseconds since epoch).- QString time = QDateTime::fromMSecsSinceEpoch(t.ts_ms, Qt::UTC).toString("HH:mm:ss");- table_->setItem(i, 0, new QTableWidgetItem(time));- table_->setItem(i, 1, new QTableWidgetItem("TRADE"));-- auto* side_item = new QTableWidgetItem(t.side);- side_item->setForeground(QColor(t.side.compare("BUY", Qt::CaseInsensitive) == 0- ? colors::POSITIVE()- : colors::NEGATIVE()));- table_->setItem(i, 2, side_item);-- auto* price_item = new QTableWidgetItem(QString::number(t.price, 'f', price_decimals));- price_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);- price_item->setForeground(QColor(colors::CYAN()));- table_->setItem(i, 3, price_item);-- auto* size_item = new QTableWidgetItem(QString::number(t.size, 'f', 2));- size_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);- table_->setItem(i, 4, size_item);+ apply_row(table_, i, trades[i], price_decimals);}table_->resizeColumnsToContents();table_->setSortingEnabled(true);}+void PolymarketActivityFeed::append_trade(const PredictionTrade& trade) {+ // Live WS trade — prepend to the top row, cap at kMaxRows. We disable+ // sorting while mutating so insertRow() keeps the newest on top. The+ // in-memory trade vector is also updated so set_presentation() re-renders+ // identically.+ table_->setSortingEnabled(false);+ last_trades_.prepend(trade);+ if (last_trades_.size() > kMaxRows)+ last_trades_.resize(kMaxRows);++ table_->insertRow(0);+ if (table_->rowCount() > kMaxRows)+ table_->removeRow(table_->rowCount() - 1);++ const int price_decimals = qBound(0, presentation_.price_decimal_places, 6);+ apply_row(table_, 0, trade, price_decimals);++ flash_row(table_, 0, presentation_.accent);+ table_->setSortingEnabled(true);+}+void PolymarketActivityFeed::clear() {last_trades_.clear();table_->setRowCount(0);diff --git a/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.h b/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.hindex a719f07cf..be2459da9 100644--- a/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.h+++ b/fincept-qt/src/screens/polymarket/PolymarketActivityFeed.h@@ -17,6 +17,10 @@ class PolymarketActivityFeed : public QWidget {explicit PolymarketActivityFeed(QWidget* parent = nullptr);void set_trades(const QVector<fincept::services::prediction::PredictionTrade>& trades);+ /// Prepend a live trade (e.g. from a WebSocket feed). Keeps the cap at+ /// 200 rows; older trades fall off the bottom. Flashes the new row+ /// briefly in the exchange accent to draw the eye.+ void append_trade(const fincept::services::prediction::PredictionTrade& trade);void clear();/// Per-exchange number formatting (decimals on the price column).diff --git a/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp b/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cppindex e4f4c663a..dfdf1a604 100644--- a/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.cpp@@ -21,47 +21,94 @@ PolymarketBrowsePanel::PolymarketBrowsePanel(QWidget* parent) : QWidget(parent)vl->setContentsMargins(0, 0, 0, 0);vl->setSpacing(0);- header_ = new QLabel("MARKETS");- header_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700; "- "letter-spacing: 0.5px; background: transparent; "- "padding: 6px 8px; border-bottom: 1px solid %2;")- .arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM()));- vl->addWidget(header_);+ // ── Header bar ───────────────────────────────────────────────────────+ auto* header_bar = new QWidget(this);+ header_bar->setFixedHeight(30);+ header_bar->setStyleSheet(+ QString("background: %1; border-bottom: 1px solid %2;")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));+ auto* hbl = new QHBoxLayout(header_bar);+ hbl->setContentsMargins(12, 0, 8, 0);+ hbl->setSpacing(6);+ header_ = new QLabel("MARKETS");+ header_->setStyleSheet(+ QString("color: %1; font-size: 9px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;")+ .arg(colors::TEXT_SECONDARY()));+ hbl->addWidget(header_);+ hbl->addStretch(1);+ vl->addWidget(header_bar);++ // ── List view ─────────────────────────────────────────────────────────list_view_ = new QListView;list_view_->setModel(model_);list_view_->setItemDelegate(delegate_);list_view_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);list_view_->setSelectionMode(QAbstractItemView::SingleSelection);- list_view_->setStyleSheet(QString("QListView { background: %1; border: none; outline: none; }"- "QListView::item { border: none; }")- .arg(colors::BG_BASE()));+ list_view_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ list_view_->setStyleSheet(+ QString("QListView {"+ " background: %1;"+ " border: none;"+ " outline: none;"+ "}"+ "QListView::item { border: none; }"+ "QScrollBar:vertical {"+ " background: %2;"+ " width: 4px;"+ " border: none;"+ "}"+ "QScrollBar::handle:vertical {"+ " background: %3;"+ " min-height: 20px;"+ "}"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::BG_SURFACE(), colors::BORDER_BRIGHT()));connect(list_view_, &QListView::clicked, this, &PolymarketBrowsePanel::on_item_clicked);vl->addWidget(list_view_, 1);- // Pagination+ // ── Pagination bar ────────────────────────────────────────────────────auto* page_bar = new QWidget(this);- page_bar->setFixedHeight(30);+ page_bar->setFixedHeight(32);page_bar->setStyleSheet(- QString("background: %1; border-top: 1px solid %2;").arg(colors::BG_SURFACE(), colors::BORDER_DIM()));+ QString("background: %1; border-top: 1px solid %2;")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));+auto* phl = new QHBoxLayout(page_bar);phl->setContentsMargins(8, 0, 8, 0);- phl->setSpacing(6);-- prev_btn_ = new QPushButton("PREV");- prev_btn_->setStyleSheet(QString("background: %1; color: %2; border: 1px solid %3; "- "padding: 3px 10px; font-size: 9px; font-weight: 700;")- .arg(colors::BG_SURFACE(), colors::TEXT_SECONDARY(), colors::BORDER_DIM()));+ phl->setSpacing(4);++ const QString nav_btn_css =+ QString("QPushButton {"+ " background: transparent;"+ " color: %1;"+ " border: 1px solid %2;"+ " padding: 3px 12px;"+ " font-size: 9px;"+ " font-weight: 700;"+ "}"+ "QPushButton:hover { color: %3; border-color: %4; }"+ "QPushButton:disabled { color: %5; border-color: %2; }")+ .arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM(),+ colors::TEXT_PRIMARY(), colors::BORDER_BRIGHT(),+ colors::TEXT_DIM());++ prev_btn_ = new QPushButton("◀");+ prev_btn_->setStyleSheet(nav_btn_css);+ prev_btn_->setFixedSize(30, 22);prev_btn_->setCursor(Qt::PointingHandCursor);connect(prev_btn_, &QPushButton::clicked, this, &PolymarketBrowsePanel::on_prev);- page_label_ = new QLabel("Page 1");+ page_label_ = new QLabel("1 / 1");page_label_->setStyleSheet(- QString("color: %1; font-size: 9px; background: transparent;").arg(colors::TEXT_SECONDARY()));+ QString("color: %1; font-size: 9px; background: transparent; min-width: 40px;")+ .arg(colors::TEXT_SECONDARY()));page_label_->setAlignment(Qt::AlignCenter);- next_btn_ = new QPushButton("NEXT");- next_btn_->setStyleSheet(prev_btn_->styleSheet());+ next_btn_ = new QPushButton("▶");+ next_btn_->setStyleSheet(nav_btn_css);+ next_btn_->setFixedSize(30, 22);next_btn_->setCursor(Qt::PointingHandCursor);connect(next_btn_, &QPushButton::clicked, this, &PolymarketBrowsePanel::on_next);@@ -74,25 +121,32 @@ PolymarketBrowsePanel::PolymarketBrowsePanel(QWidget* parent) : QWidget(parent)}void PolymarketBrowsePanel::set_markets(const QVector<PredictionMarket>& markets) {+ events_mode_ = false;current_page_ = 0;model_->set_markets(markets);- header_->setText(QString("MARKETS (%1)").arg(markets.size()));+ header_->setText(QString("MARKETS %1").arg(markets.size()));update_page();}void PolymarketBrowsePanel::set_events(const QVector<PredictionEvent>& events) {+ events_mode_ = true;current_page_ = 0;model_->set_events(events);- header_->setText(QString("EVENTS (%1)").arg(events.size()));+ header_->setText(QString("EVENTS %1").arg(events.size()));update_page();}void PolymarketBrowsePanel::set_loading(bool loading) {- if (loading)+ if (loading) {header_->setText("LOADING...");+ } else {+ const int total = model_->rowCount();+ header_->setText(QString("%1 %2").arg(events_mode_ ? "EVENTS" : "MARKETS").arg(total));+ }}void PolymarketBrowsePanel::clear() {+ events_mode_ = false;model_->set_markets({});header_->setText("MARKETS");current_page_ = 0;@@ -103,6 +157,10 @@ void PolymarketBrowsePanel::set_presentation(const ExchangePresentation& p) {if (model_) model_->set_presentation(p);}+void PolymarketBrowsePanel::update_market_row(const PredictionMarket& market) {+ if (model_) model_->update_market(market);+}+void PolymarketBrowsePanel::on_item_clicked(const QModelIndex& index) {if (!index.isValid())return;@@ -139,7 +197,7 @@ void PolymarketBrowsePanel::on_next() {void PolymarketBrowsePanel::update_page() {int total = model_->rowCount();int pages = qMax(1, (total + PAGE_SIZE - 1) / PAGE_SIZE);- page_label_->setText(QString("Page %1 / %2").arg(current_page_ + 1).arg(pages));+ page_label_->setText(QString("%1 / %2").arg(current_page_ + 1).arg(pages));prev_btn_->setEnabled(current_page_ > 0);next_btn_->setEnabled(current_page_ + 1 < pages);}diff --git a/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.h b/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.hindex 03230d103..23e30f9d2 100644--- a/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.h+++ b/fincept-qt/src/screens/polymarket/PolymarketBrowsePanel.h@@ -26,6 +26,10 @@ class PolymarketBrowsePanel : public QWidget {void set_loading(bool loading);void clear();+ /// Replace a single market row in place (e.g. after a Kalshi lifecycle+ /// event refetched one market). No-op if the ticker isn't in the list.+ void update_market_row(const fincept::services::prediction::PredictionMarket& market);+/// Forwarded to the model so the delegate paints with the active/// exchange's accent and price formatter.void set_presentation(const ExchangePresentation& p);@@ -51,6 +55,7 @@ class PolymarketBrowsePanel : public QWidget {QLabel* page_label_ = nullptr;int current_page_ = 0;+ bool events_mode_ = false;static constexpr int PAGE_SIZE = 20;};diff --git a/fincept-qt/src/screens/polymarket/PolymarketCommandBar.cpp b/fincept-qt/src/screens/polymarket/PolymarketCommandBar.cppindex 629aa7b39..f5136a72d 100644--- a/fincept-qt/src/screens/polymarket/PolymarketCommandBar.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketCommandBar.cpp@@ -14,7 +14,7 @@ static const QStringList SORT_KEYS = {"volume", "liquidity", "startDate"};PolymarketCommandBar::PolymarketCommandBar(QWidget* parent) : QWidget(parent) {setObjectName("polyCommandBar");- setFixedHeight(72);+ setFixedHeight(48);build_ui();apply_accent();rebuild_view_pills();@@ -29,138 +29,228 @@ static QString accent_css_rgba(const QColor& c, double a) {void PolymarketCommandBar::apply_accent() {const QString accent = accent_css_rgb(presentation_.accent);- const QString accent_bg = accent_css_rgba(presentation_.accent, 0.15);+ const QString accent_dim = accent_css_rgba(presentation_.accent, 0.18);+ const QString accent_border = accent_css_rgba(presentation_.accent, 0.50);- // The bar uses object-name-scoped styling so the accent can swap live- // on exchange change without a full stylesheet rebuild further down the- // tree. Any descendant that also needs the accent (tab underline in the- // detail panel, outcome row left-border, etc.) picks it up via its own- // set_presentation() call.const QString css =- QStringLiteral("#polyCommandBar { background: %1; border-bottom: 2px solid %2; }"- "#polyCmdTitle { color: %3; font-size: 12px; font-weight: 700; background: transparent; }"- "#polyViewBtn { background: transparent; color: %4; border: 1px solid %5; "- " font-size: 9px; font-weight: 700; padding: 4px 12px; }"- "#polyViewBtn:hover { color: %3; }"- "#polyViewBtn[active=\"true\"] { background: %2; color: %6; border-color: %2; }"- "#polyCatBtn { background: transparent; color: %4; border: 1px solid %5; "- " font-size: 8px; font-weight: 600; padding: 2px 8px; }"- "#polyCatBtn:hover { color: %3; }"- "#polyCatBtn[active=\"true\"] { background: %7; color: %2; border-color: %2; }"- "#polySearchInput { background: %6; color: %3; border: 1px solid %5; "- " padding: 4px 8px; font-size: 11px; }"- "#polySearchInput:focus { border-color: %8; }"- "#polyRefreshBtn { background: %9; color: %4; border: 1px solid %5; "- " padding: 4px 10px; font-size: 9px; font-weight: 700; }"- "#polyRefreshBtn:hover { color: %3; }"- "#polyWsIndicator { font-size: 8px; font-weight: 700; padding: 2px 6px; }"- "#polyCountLabel { color: %4; font-size: 9px; background: transparent; }")- .arg(colors::BG_RAISED()) // %1- .arg(accent) // %2- .arg(colors::TEXT_PRIMARY()) // %3- .arg(colors::TEXT_SECONDARY()) // %4- .arg(colors::BORDER_DIM()) // %5- .arg(colors::BG_BASE()) // %6- .arg(accent_bg) // %7- .arg(colors::BORDER_BRIGHT()) // %8- .arg(colors::BG_SURFACE()); // %9+ QStringLiteral(+ "#polyCommandBar {"+ " background: %1;"+ " border-bottom: 1px solid %2;"+ "}"+ // Exchange combo+ "QComboBox#polyExchangeCombo {"+ " background: %3;"+ " color: %4;"+ " border: 1px solid %5;"+ " font-size: 10px;"+ " font-weight: 700;"+ " padding: 3px 8px;"+ " min-width: 110px;"+ "}"+ "QComboBox#polyExchangeCombo::drop-down { border: none; width: 18px; }"+ "QComboBox#polyExchangeCombo QAbstractItemView {"+ " background: %3; color: %4; border: 1px solid %5;"+ " selection-background-color: %6;"+ "}"+ // Separator+ "#polyCmdSep { background: %2; }"+ // View tabs+ "#polyViewBtn {"+ " background: transparent;"+ " color: %7;"+ " border: none;"+ " border-bottom: 2px solid transparent;"+ " font-size: 10px;"+ " font-weight: 700;"+ " padding: 0 14px;"+ " letter-spacing: 0.5px;"+ "}"+ "#polyViewBtn:hover { color: %4; border-bottom-color: %5; }"+ "#polyViewBtn[active=\"true\"] { color: %8; border-bottom-color: %8; }"+ // Category chips+ "#polyCatBtn {"+ " background: transparent;"+ " color: %7;"+ " border: 1px solid %5;"+ " font-size: 9px;"+ " font-weight: 600;"+ " padding: 2px 10px;"+ " letter-spacing: 0.3px;"+ "}"+ "#polyCatBtn:hover { color: %4; border-color: %9; }"+ "#polyCatBtn[active=\"true\"] { background: %6; color: %8; border-color: %8; }"+ // Search+ "#polySearchInput {"+ " background: %3;"+ " color: %4;"+ " border: 1px solid %5;"+ " padding: 4px 10px;"+ " font-size: 10px;"+ "}"+ "#polySearchInput:focus { border-color: %8; }"+ // Sort+ "QComboBox#polySortCombo {"+ " background: %3;"+ " color: %7;"+ " border: 1px solid %5;"+ " padding: 3px 6px;"+ " font-size: 9px;"+ " font-weight: 600;"+ "}"+ "QComboBox#polySortCombo::drop-down { border: none; width: 14px; }"+ "QComboBox#polySortCombo QAbstractItemView {"+ " background: %3; color: %4; border: 1px solid %5;"+ "}"+ // Refresh+ "#polyRefreshBtn {"+ " background: transparent;"+ " color: %7;"+ " border: 1px solid %5;"+ " padding: 3px 10px;"+ " font-size: 9px;"+ " font-weight: 700;"+ "}"+ "#polyRefreshBtn:hover { color: %4; border-color: %9; }"+ "#polyRefreshBtn:disabled { color: %10; }"+ // WS indicator+ "#polyWsIndicator { font-size: 9px; font-weight: 700; padding: 2px 8px; }"+ // Count label+ "#polyCountLabel { color: %7; font-size: 9px; background: transparent; padding: 0 4px; }"+ // Account chip+ "#polyAccountChip {"+ " background: transparent;"+ " color: %7;"+ " border: 1px solid %5;"+ " font-size: 9px;"+ " font-weight: 700;"+ " padding: 3px 10px;"+ "}"+ "#polyAccountChip:hover { color: %4; border-color: %9; }"+ )+ .arg(colors::BG_RAISED()) // %1+ .arg(colors::BORDER_DIM()) // %2+ .arg(colors::BG_BASE()) // %3+ .arg(colors::TEXT_PRIMARY()) // %4+ .arg(colors::BORDER_MED()) // %5+ .arg(accent_dim) // %6+ .arg(colors::TEXT_SECONDARY()) // %7+ .arg(accent) // %8+ .arg(colors::BORDER_BRIGHT()) // %9+ .arg(colors::TEXT_DIM()); // %10+setStyleSheet(css);}void PolymarketCommandBar::build_ui() {- auto* vl = new QVBoxLayout(this);- vl->setContentsMargins(16, 6, 16, 6);- vl->setSpacing(4);-- // Row 1: title + count + refresh + WS status- auto* row1 = new QHBoxLayout;- row1->setSpacing(8);- title_label_ = new QLabel(tr("PREDICTION MARKETS"));- title_label_->setObjectName("polyCmdTitle");- row1->addWidget(title_label_);- row1->addStretch(1);-- count_label_ = new QLabel;- count_label_->setObjectName("polyCountLabel");- row1->addWidget(count_label_);-- refresh_btn_ = new QPushButton(tr("REFRESH"));- refresh_btn_->setObjectName("polyRefreshBtn");- refresh_btn_->setCursor(Qt::PointingHandCursor);- connect(refresh_btn_, &QPushButton::clicked, this, &PolymarketCommandBar::refresh_clicked);- row1->addWidget(refresh_btn_);-- ws_indicator_ = new QLabel(tr("DISCONNECTED"));- ws_indicator_->setObjectName("polyWsIndicator");- set_ws_status(false);- row1->addWidget(ws_indicator_);- vl->addLayout(row1);-- // Row 2: exchange dropdown + view pills + categories + search + sort- auto* row2 = new QHBoxLayout;- row2->setSpacing(4);+ auto* hl = new QHBoxLayout(this);+ hl->setContentsMargins(12, 0, 12, 0);+ hl->setSpacing(0);+ // ── Exchange selector ─────────────────────────────────────────────────exchange_combo_ = new QComboBox;- exchange_combo_->setFixedWidth(130);- exchange_combo_->setToolTip(tr("Select prediction-market exchange"));+ exchange_combo_->setObjectName("polyExchangeCombo");+ exchange_combo_->setToolTip(tr("Switch prediction market exchange"));+ exchange_combo_->setFixedHeight(26);connect(exchange_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int idx) {if (idx < 0) return;const QString id = exchange_combo_->itemData(idx).toString();if (!id.isEmpty()) emit exchange_changed(id);});- row2->addWidget(exchange_combo_);+ hl->addWidget(exchange_combo_);++ hl->addSpacing(8);- account_chip_ = new QPushButton(tr("⚪ No account"), this);+ // ── Account chip ──────────────────────────────────────────────────────+ account_chip_ = new QPushButton(tr("CONNECT"), this);account_chip_->setObjectName("polyAccountChip");+ account_chip_->setFixedHeight(26);account_chip_->setCursor(Qt::PointingHandCursor);- account_chip_->setToolTip(tr("Connect a Polymarket or Kalshi account to place orders"));- account_chip_->setStyleSheet(QString("#polyAccountChip { background: transparent; color: %1; "- "border: 1px solid %2; font-size: 9px; font-weight: 700; "- "padding: 4px 10px; } #polyAccountChip:hover { color: %3; }")- .arg(colors::TEXT_DIM())- .arg(colors::BORDER_DIM())- .arg(colors::TEXT_PRIMARY()));+ account_chip_->setToolTip(tr("Connect a trading account"));connect(account_chip_, &QPushButton::clicked, this, &PolymarketCommandBar::account_clicked);- row2->addWidget(account_chip_);+ hl->addWidget(account_chip_);- row2->addSpacing(8);+ // ── Left separator ────────────────────────────────────────────────────+ auto* sep1 = new QWidget;+ sep1->setObjectName("polyCmdSep");+ sep1->setFixedSize(1, 28);+ hl->addSpacing(10);+ hl->addWidget(sep1);+ hl->addSpacing(2);- // View pills — rebuilt dynamically from presentation.view_names.+ // ── View tabs (fills available width) ────────────────────────────────view_pills_container_ = new QWidget(this);+ view_pills_container_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);auto* pl = new QHBoxLayout(view_pills_container_);pl->setContentsMargins(0, 0, 0, 0);- pl->setSpacing(4);- row2->addWidget(view_pills_container_);-- row2->addSpacing(8);-+ pl->setSpacing(0);+ hl->addWidget(view_pills_container_);++ // ── Right separator ───────────────────────────────────────────────────+ auto* sep2 = new QWidget;+ sep2->setObjectName("polyCmdSep");+ sep2->setFixedSize(1, 28);+ hl->addSpacing(2);+ hl->addWidget(sep2);+ hl->addSpacing(8);++ // ── Category row ──────────────────────────────────────────────────────category_container_ = new QWidget(this);+ category_container_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);auto* ccl = new QHBoxLayout(category_container_);ccl->setContentsMargins(0, 0, 0, 0);- ccl->setSpacing(2);- // Populated by rebuild_categories() per presentation mode.- row2->addWidget(category_container_);+ ccl->setSpacing(4);+ hl->addWidget(category_container_, 1);- row2->addSpacing(8);+ hl->addSpacing(8);+ // ── Search ────────────────────────────────────────────────────────────search_input_ = new QLineEdit;search_input_->setObjectName("polySearchInput");- search_input_->setPlaceholderText(tr("SEARCH..."));- search_input_->setFixedWidth(180);+ search_input_->setPlaceholderText(tr("Search markets..."));+ search_input_->setFixedSize(170, 26);connect(search_input_, &QLineEdit::returnPressed, this,[this]() { emit search_submitted(search_input_->text().trimmed()); });- row2->addWidget(search_input_);+ hl->addWidget(search_input_);++ hl->addSpacing(6);+ // ── Sort ──────────────────────────────────────────────────────────────sort_combo_ = new QComboBox;- sort_combo_->addItems({tr("VOLUME"), tr("LIQUIDITY"), tr("RECENT")});- sort_combo_->setFixedWidth(90);+ sort_combo_->setObjectName("polySortCombo");+ sort_combo_->addItems({tr("VOLUME"), tr("LIQUIDITY"), tr("DATE")});+ sort_combo_->setFixedSize(88, 26);connect(sort_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int idx) {if (idx >= 0 && idx < SORT_KEYS.size()) emit sort_changed(SORT_KEYS[idx]);});- row2->addWidget(sort_combo_);+ hl->addWidget(sort_combo_);++ hl->addSpacing(6);++ // ── Count ─────────────────────────────────────────────────────────────+ count_label_ = new QLabel;+ count_label_->setObjectName("polyCountLabel");+ hl->addWidget(count_label_);++ hl->addSpacing(6);- row2->addStretch(1);- vl->addLayout(row2);+ // ── Refresh ───────────────────────────────────────────────────────────+ refresh_btn_ = new QPushButton(tr("↻"));+ refresh_btn_->setObjectName("polyRefreshBtn");+ refresh_btn_->setFixedSize(28, 26);+ refresh_btn_->setCursor(Qt::PointingHandCursor);+ refresh_btn_->setToolTip(tr("Refresh"));+ connect(refresh_btn_, &QPushButton::clicked, this, &PolymarketCommandBar::refresh_clicked);+ hl->addWidget(refresh_btn_);++ hl->addSpacing(8);++ // ── WS indicator ──────────────────────────────────────────────────────+ ws_indicator_ = new QLabel;+ ws_indicator_->setObjectName("polyWsIndicator");+ ws_indicator_->setFixedWidth(52);+ set_ws_status(false);+ hl->addWidget(ws_indicator_);}// ── Presentation ────────────────────────────────────────────────────────────@@ -171,7 +261,6 @@ void PolymarketCommandBar::set_presentation(const ExchangePresentation& p) {const bool category_mode_changed = p.category_mode != presentation_.category_mode;presentation_ = p;- title_label_->setText(tr("%1 · PREDICTION MARKETS").arg(p.display_name.toUpper()));if (accent_changed) apply_accent();if (views_changed || view_btns_.isEmpty()) {@@ -197,6 +286,7 @@ void PolymarketCommandBar::rebuild_view_pills() {auto* btn = new QPushButton(name);btn->setObjectName("polyViewBtn");btn->setCursor(Qt::PointingHandCursor);+ btn->setFixedHeight(48); // full bar height for flush underlinebtn->setProperty("active", name == active_view_);connect(btn, &QPushButton::clicked, this, [this, name]() { emit view_changed(name); });layout->addWidget(btn);@@ -223,24 +313,22 @@ void PolymarketCommandBar::rebuild_categories() {category_combo_ = nullptr;if (presentation_.category_mode == ExchangePresentation::CategoryMode::ComboBox) {- // Kalshi-style: hundreds of series tickers — a dropdown with a- // type-ahead is the only layout that scales.category_combo_ = new QComboBox;category_combo_->setEditable(true);category_combo_->setInsertPolicy(QComboBox::NoInsert);- category_combo_->setFixedWidth(200);+ category_combo_->setFixedSize(190, 26);category_combo_->setStyleSheet(QString("QComboBox { background: %1; color: %2; border: 1px solid %3; "- "padding: 3px 8px; font-size: 10px; }"- "QComboBox QAbstractItemView { background: %1; color: %2; selection-background-color: %4; }")- .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(),- QString("rgba(%1,%2,%3,0.2)")- .arg(presentation_.accent.red())- .arg(presentation_.accent.green())- .arg(presentation_.accent.blue())));- category_combo_->addItem(tr("ALL"), QStringLiteral("ALL"));+ "padding: 3px 8px; font-size: 9px; font-weight: 600; }"+ "QComboBox::drop-down { border: none; width: 14px; }"+ "QComboBox QAbstractItemView { background: %1; color: %2; border: 1px solid %3; "+ "selection-background-color: rgba(%4,%5,%6,0.2); }")+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_MED())+ .arg(presentation_.accent.red())+ .arg(presentation_.accent.green())+ .arg(presentation_.accent.blue()));+ category_combo_->addItem(tr("ALL SERIES"), QStringLiteral("ALL"));for (const QString& t : current_tags_) category_combo_->addItem(t, t);- // Restore selection.const int idx = qMax(0, category_combo_->findData(active_category_));{QSignalBlocker b(category_combo_);@@ -255,9 +343,10 @@ void PolymarketCommandBar::rebuild_categories() {return;}- // Chip row (Polymarket default).+ // Chip row (Polymarket default) — compact pillsauto* all_btn = new QPushButton(tr("ALL"));all_btn->setObjectName("polyCatBtn");+ all_btn->setFixedHeight(22);all_btn->setCursor(Qt::PointingHandCursor);all_btn->setProperty("active", active_category_ == "ALL");connect(all_btn, &QPushButton::clicked, this, [this]() { emit category_changed("ALL"); });@@ -268,11 +357,13 @@ void PolymarketCommandBar::rebuild_categories() {const QString& slug = current_tags_[i];auto* btn = new QPushButton(slug.toUpper());btn->setObjectName("polyCatBtn");+ btn->setFixedHeight(22);btn->setCursor(Qt::PointingHandCursor);btn->setProperty("active", active_category_ == slug);connect(btn, &QPushButton::clicked, this, [this, slug]() { emit category_changed(slug); });layout->addWidget(btn);}+ layout->addStretch(1);}// ── Active-state tracking ───────────────────────────────────────────────────@@ -308,44 +399,47 @@ void PolymarketCommandBar::set_active_category(const QString& cat) {void PolymarketCommandBar::set_loading(bool loading) {refresh_btn_->setEnabled(!loading);- refresh_btn_->setText(loading ? tr("LOADING...") : tr("REFRESH"));+ refresh_btn_->setText(loading ? tr("…") : tr("↻"));}void PolymarketCommandBar::set_ws_status(bool connected) {if (connected) {- ws_indicator_->setText(tr("LIVE"));- ws_indicator_->setStyleSheet(QString("color: %1; background: rgba(22,163,74,0.2); "- "font-size: 8px; font-weight: 700; padding: 2px 6px;")- .arg(colors::POSITIVE()));+ ws_indicator_->setText(tr("● LIVE"));+ ws_indicator_->setStyleSheet(+ QString("color: %1; background: rgba(22,163,74,0.15); font-size: 9px; "+ "font-weight: 700; padding: 2px 8px; border: 1px solid rgba(22,163,74,0.40);")+ .arg(colors::POSITIVE()));} else {- ws_indicator_->setText(tr("OFFLINE"));- ws_indicator_->setStyleSheet(QString("color: %1; background: transparent; "- "font-size: 8px; font-weight: 700; padding: 2px 6px;")- .arg(colors::TEXT_DIM()));+ ws_indicator_->setText(tr("○ OFF"));+ ws_indicator_->setStyleSheet(+ QString("color: %1; background: transparent; font-size: 9px; "+ "font-weight: 700; padding: 2px 8px; border: 1px solid %2;")+ .arg(colors::TEXT_DIM(), colors::BORDER_DIM()));}}void PolymarketCommandBar::set_market_count(int count) {- count_label_->setText(QString::number(count) + " markets");+ count_label_->setText(QString::number(count));}void PolymarketCommandBar::set_account_status(bool connected, const QString& label) {if (!account_chip_) return;if (connected) {- account_chip_->setText(QString("🟢 %1").arg(label.isEmpty() ? tr("Connected") : label));- account_chip_->setStyleSheet(QString("#polyAccountChip { background: rgba(22,163,74,0.12); "- "color: %1; border: 1px solid %1; font-size: 9px; "- "font-weight: 700; padding: 4px 10px; }")- .arg(colors::POSITIVE()));+ account_chip_->setText(QString("✓ %1").arg(label.isEmpty() ? tr("Account") : label));+ account_chip_->setStyleSheet(+ QString("#polyAccountChip { background: rgba(22,163,74,0.12); color: %1; "+ "border: 1px solid rgba(22,163,74,0.40); font-size: 9px; "+ "font-weight: 700; padding: 3px 10px; }"+ "#polyAccountChip:hover { background: rgba(22,163,74,0.22); }")+ .arg(colors::POSITIVE()));} else {- account_chip_->setText(tr("⚪ No account"));- account_chip_->setStyleSheet(QString("#polyAccountChip { background: transparent; "- "color: %1; border: 1px solid %2; font-size: 9px; "- "font-weight: 700; padding: 4px 10px; } "- "#polyAccountChip:hover { color: %3; }")- .arg(colors::TEXT_DIM())- .arg(colors::BORDER_DIM())- .arg(colors::TEXT_PRIMARY()));+ account_chip_->setText(tr("CONNECT"));+ account_chip_->setStyleSheet(+ QString("#polyAccountChip { background: transparent; color: %1; "+ "border: 1px solid %2; font-size: 9px; font-weight: 700; padding: 3px 10px; }"+ "#polyAccountChip:hover { color: %3; border-color: %4; }")+ .arg(colors::TEXT_DIM(), colors::BORDER_DIM(),+ colors::TEXT_PRIMARY(), colors::BORDER_BRIGHT()));}}diff --git a/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h b/fincept-qt/src/screens/polymarket/PolymarketCommandBar.hindex 8e5e8f10e..c26ad6bea 100644--- a/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h+++ b/fincept-qt/src/screens/polymarket/PolymarketCommandBar.h@@ -33,6 +33,7 @@ class PolymarketCommandBar : public QWidget {void set_loading(bool loading);void set_ws_status(bool connected);void set_market_count(int count);+ void set_search_text(const QString& text) { if (search_input_) search_input_->setText(text); }/// Populate the exchange dropdown. `ids` are adapter ids from/// PredictionExchangeRegistry (e.g. ["polymarket", "kalshi"]); `labels`diff --git a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cppindex cbcd81e17..94db8af2b 100644--- a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.cpp@@ -5,9 +5,11 @@#include "screens/polymarket/PolymarketPriceChart.h"#include "ui/theme/Theme.h"+#include <QComboBox>#include <QDateTime>#include <QHBoxLayout>#include <QHeaderView>+#include <QLineEdit>#include <QScrollArea>#include <QVBoxLayout>@@ -17,11 +19,10 @@ using namespace fincept::ui;namespace pmx = fincept::services::polymarket;using namespace fincept::services::prediction;-static const QStringList TAB_NAMES = {"OVERVIEW", "ORDER BOOK", "CHART", "TRADES", "HOLDERS", "COMMENTS", "RELATED"};-// Fallback outcome palette used when the first two slots (green/red) don't-// cover a multi-outcome Polymarket market. The first two entries are-// overridden at paint time by the presentation's accent-aware colors.-static const QStringList OUTCOME_COLORS = {"#00D66F", "#FF3B3B", "#FF8800", "#4F8EF7", "#A855F7"};+static const QStringList TAB_NAMES = {+ "OVERVIEW", "ORDER BOOK", "CHART", "TRADE", "TRADES", "HOLDERS", "COMMENTS", "RELATED"+};+static const char* OUTCOME_COLORS[] = {"#00D66F", "#FF3B3B", "#FF8800", "#4F8EF7", "#A855F7"};PolymarketDetailPanel::PolymarketDetailPanel(QWidget* parent) : QWidget(parent) {setObjectName("polyDetailPanel");@@ -33,13 +34,16 @@ void PolymarketDetailPanel::build_ui() {vl->setContentsMargins(0, 0, 0, 0);vl->setSpacing(0);- // Tab bar+ // ── Tab bar ───────────────────────────────────────────────────────────auto* tab_bar = new QWidget(this);- tab_bar->setFixedHeight(32);+ tab_bar->setObjectName("polyDetailTabBar");+ tab_bar->setFixedHeight(34);tab_bar->setStyleSheet(- QString("background: %1; border-bottom: 1px solid %2;").arg(colors::BG_RAISED(), colors::BORDER_DIM()));+ QString("QWidget#polyDetailTabBar { background: %1; border-bottom: 1px solid %2; }")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));+auto* thl = new QHBoxLayout(tab_bar);- thl->setContentsMargins(8, 0, 8, 0);+ thl->setContentsMargins(0, 0, 0, 0);thl->setSpacing(0);for (int i = 0; i < TAB_NAMES.size(); ++i) {@@ -54,7 +58,7 @@ void PolymarketDetailPanel::build_ui() {vl->addWidget(tab_bar);apply_accent_to_tabs();- // Stacked pages+ // ── Stacked pages ─────────────────────────────────────────────────────stack_ = new QStackedWidget;stack_->addWidget(create_overview_page()); // 0@@ -62,16 +66,20 @@ void PolymarketDetailPanel::build_ui() {stack_->addWidget(orderbook_); // 1price_chart_ = new PolymarketPriceChart;- connect(price_chart_, &PolymarketPriceChart::interval_changed, this, &PolymarketDetailPanel::interval_changed);- connect(price_chart_, &PolymarketPriceChart::outcome_changed, this, &PolymarketDetailPanel::outcome_changed);+ connect(price_chart_, &PolymarketPriceChart::interval_changed,+ this, &PolymarketDetailPanel::interval_changed);+ connect(price_chart_, &PolymarketPriceChart::outcome_changed,+ this, &PolymarketDetailPanel::outcome_changed);stack_->addWidget(price_chart_); // 2+ stack_->addWidget(create_trade_page()); // 3+activity_feed_ = new PolymarketActivityFeed;- stack_->addWidget(activity_feed_); // 3+ stack_->addWidget(activity_feed_); // 4- stack_->addWidget(create_holders_page()); // 4- stack_->addWidget(create_comments_page()); // 5- stack_->addWidget(create_related_page()); // 6+ stack_->addWidget(create_holders_page()); // 5+ stack_->addWidget(create_comments_page()); // 6+ stack_->addWidget(create_related_page()); // 7vl->addWidget(stack_, 1);}@@ -79,69 +87,130 @@ void PolymarketDetailPanel::build_ui() {QWidget* PolymarketDetailPanel::create_overview_page() {auto* scroll = new QScrollArea;scroll->setWidgetResizable(true);- scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }");- auto* page = new QWidget(this);+ scroll->setStyleSheet(+ QString("QScrollArea { border: none; background: %1; }"+ "QScrollBar:vertical { background: %2; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::BG_SURFACE(), colors::BORDER_BRIGHT()));++ auto* page = new QWidget;+ page->setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));auto* vl = new QVBoxLayout(page);- vl->setContentsMargins(16, 16, 16, 16);- vl->setSpacing(12);+ vl->setContentsMargins(16, 14, 16, 16);+ vl->setSpacing(0);+ // ── Market question / title ───────────────────────────────────────────question_label_ = new QLabel("Select a market to view details");question_label_->setStyleSheet(- QString("color: %1; font-size: 14px; font-weight: 700; background: transparent;").arg(colors::TEXT_PRIMARY()));+ QString("color: %1; font-size: 13px; font-weight: 700; background: transparent; "+ "line-height: 1.4;")+ .arg(colors::TEXT_PRIMARY()));question_label_->setWordWrap(true);+ question_label_->setMinimumHeight(36);vl->addWidget(question_label_);- // Stats grid- auto* stats = new QWidget(this);- auto* sgl = new QHBoxLayout(stats);- sgl->setContentsMargins(0, 0, 0, 0);- sgl->setSpacing(16);+ vl->addSpacing(10);- auto lbl_style =- QString("color: %1; font-size: 9px; font-weight: 700; letter-spacing: 0.5px; background: transparent;")- .arg(colors::TEXT_SECONDARY());- auto val_style =- QString("color: %1; font-size: 13px; font-weight: 700; background: transparent;").arg(colors::CYAN());+ // ── Status row (badge + outcome labels) ───────────────────────────────+ auto* status_row = new QWidget;+ status_row->setStyleSheet("background: transparent;");+ auto* srl = new QHBoxLayout(status_row);+ srl->setContentsMargins(0, 0, 0, 0);+ srl->setSpacing(6);- auto make_stat = [&](const QString& label, QLabel*& val_lbl, QWidget** out_box = nullptr) {- auto* box = new QWidget(this);+ status_label_ = new QLabel;+ srl->addWidget(status_label_);+ srl->addStretch(1);+ vl->addWidget(status_row);++ vl->addSpacing(12);++ // ── Stats: two rows of 3-4 cells each ────────────────────────────────+ // Row 1 of stats+ auto* stats_row1 = new QWidget;+ stats_row1->setStyleSheet(+ QString("background: %1; border: 1px solid %2; border-bottom: none;")+ .arg(colors::BG_SURFACE(), colors::BORDER_DIM()));+ auto* sr1l = new QHBoxLayout(stats_row1);+ sr1l->setContentsMargins(0, 0, 0, 0);+ sr1l->setSpacing(0);++ auto make_stat_in = [&](QWidget* parent_row, QHBoxLayout* row_layout,+ const QString& lbl, QLabel*& val,+ bool last = false, QWidget** box_out = nullptr) {+ auto* box = new QWidget(parent_row);+ box->setStyleSheet(+ last ? QString("background: transparent;")+ : QString("background: transparent; border-right: 1px solid %1;")+ .arg(colors::BORDER_DIM()));auto* bvl = new QVBoxLayout(box);- bvl->setContentsMargins(0, 0, 0, 0);- bvl->setSpacing(1);- auto* lbl = new QLabel(label);- lbl->setStyleSheet(lbl_style);- val_lbl = new QLabel("--");- val_lbl->setStyleSheet(val_style);- bvl->addWidget(lbl);- bvl->addWidget(val_lbl);- sgl->addWidget(box);- if (out_box) *out_box = box;+ bvl->setContentsMargins(12, 8, 12, 8);+ bvl->setSpacing(3);++ auto* lbl_w = new QLabel(lbl, box);+ lbl_w->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;")+ .arg(colors::TEXT_SECONDARY()));++ val = new QLabel("—", box);+ val->setStyleSheet(+ QString("color: %1; font-size: 12px; font-weight: 700; background: transparent;")+ .arg(colors::TEXT_PRIMARY()));++ bvl->addWidget(lbl_w);+ bvl->addWidget(val);+ row_layout->addWidget(box, 1);+ if (box_out) *box_out = box;};- make_stat("VOLUME", volume_label_);- make_stat("LIQUIDITY", liquidity_label_);- make_stat("END DATE", end_date_label_);- make_stat("MIDPOINT", midpoint_label_);- make_stat("SPREAD", spread_label_);- make_stat("LAST TRADE", last_trade_label_);- make_stat("OPEN INT", oi_label_, &oi_box_);-- status_label_ = new QLabel;- sgl->addWidget(status_label_);- sgl->addStretch(1);- vl->addWidget(stats);-- // Outcomes- outcome_container_ = new QWidget(this);+ make_stat_in(stats_row1, sr1l, "VOLUME", volume_label_);+ make_stat_in(stats_row1, sr1l, "LIQUIDITY", liquidity_label_);+ make_stat_in(stats_row1, sr1l, "OPEN INT", oi_label_, false, &oi_box_);+ make_stat_in(stats_row1, sr1l, "END DATE", end_date_label_, true);+ vl->addWidget(stats_row1);++ // Row 2 of stats+ auto* stats_row2 = new QWidget;+ stats_row2->setStyleSheet(+ QString("background: %1; border: 1px solid %2;")+ .arg(colors::BG_SURFACE(), colors::BORDER_DIM()));+ auto* sr2l = new QHBoxLayout(stats_row2);+ sr2l->setContentsMargins(0, 0, 0, 0);+ sr2l->setSpacing(0);++ make_stat_in(stats_row2, sr2l, "MIDPOINT", midpoint_label_);+ make_stat_in(stats_row2, sr2l, "SPREAD", spread_label_);+ make_stat_in(stats_row2, sr2l, "LAST TRADE", last_trade_label_, true);+ vl->addWidget(stats_row2);++ vl->addSpacing(14);++ // ── Outcome probability bars ──────────────────────────────────────────+ auto* outcomes_header = new QLabel("OUTCOMES");+ outcomes_header->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;")+ .arg(colors::TEXT_SECONDARY()));+ vl->addWidget(outcomes_header);+ vl->addSpacing(6);++ outcome_container_ = new QWidget;+ outcome_container_->setStyleSheet("background: transparent;");auto* ocl = new QVBoxLayout(outcome_container_);ocl->setContentsMargins(0, 0, 0, 0);- ocl->setSpacing(2);+ ocl->setSpacing(6);vl->addWidget(outcome_container_);- // Description+ vl->addSpacing(14);++ // ── Description ───────────────────────────────────────────────────────description_label_ = new QLabel;description_label_->setStyleSheet(- QString("color: %1; font-size: 11px; background: transparent;").arg(colors::TEXT_SECONDARY()));+ QString("color: %1; font-size: 10px; line-height: 1.5; background: transparent; "+ "border-top: 1px solid %2; padding-top: 12px;")+ .arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM()));description_label_->setWordWrap(true);vl->addWidget(description_label_);@@ -150,6 +219,293 @@ QWidget* PolymarketDetailPanel::create_overview_page() {return scroll;}+QWidget* PolymarketDetailPanel::create_trade_page() {+ // Two-state stack: 0 = no-account placeholder, 1 = ticket form.+ ticket_stack_ = new QStackedWidget;++ // ── State 0: no account connected ────────────────────────────────────────+ auto* no_acct = new QWidget;+ no_acct->setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));+ auto* nal = new QVBoxLayout(no_acct);+ nal->setAlignment(Qt::AlignCenter);+ nal->setSpacing(8);+ auto* icon_lbl = new QLabel("🔒");+ icon_lbl->setAlignment(Qt::AlignCenter);+ icon_lbl->setStyleSheet("font-size: 28px; background: transparent;");+ auto* msg_lbl = new QLabel("Connect an account\nto place orders");+ msg_lbl->setAlignment(Qt::AlignCenter);+ msg_lbl->setStyleSheet(+ QString("color: %1; font-size: 11px; background: transparent;").arg(colors::TEXT_DIM()));+ nal->addWidget(icon_lbl);+ nal->addWidget(msg_lbl);+ ticket_stack_->addWidget(no_acct); // index 0++ // ── State 1: ticket form ─────────────────────────────────────────────────+ auto* form = new QWidget;+ form->setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));+ auto* fl = new QVBoxLayout(form);+ fl->setContentsMargins(16, 14, 16, 14);+ fl->setSpacing(10);++ // Balance + position header+ auto* hdr = new QWidget;+ hdr->setStyleSheet(+ QString("background: %1; border: 1px solid %2; border-radius: 3px;")+ .arg(colors::BG_SURFACE(), colors::BORDER_DIM()));+ auto* hdrl = new QHBoxLayout(hdr);+ hdrl->setContentsMargins(10, 7, 10, 7);+ hdrl->setSpacing(0);++ auto* bal_col = new QVBoxLayout;+ bal_col->setSpacing(2);+ auto* bal_lbl = new QLabel("AVAILABLE");+ bal_lbl->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;").arg(colors::TEXT_SECONDARY()));+ ticket_balance_lbl_ = new QLabel("—");+ ticket_balance_lbl_->setStyleSheet(+ QString("color: %1; font-size: 12px; font-weight: 700; background: transparent;")+ .arg(colors::TEXT_PRIMARY()));+ bal_col->addWidget(bal_lbl);+ bal_col->addWidget(ticket_balance_lbl_);++ auto* pos_col = new QVBoxLayout;+ pos_col->setSpacing(2);+ pos_col->setAlignment(Qt::AlignRight);+ auto* pos_lbl = new QLabel("POSITION");+ pos_lbl->setAlignment(Qt::AlignRight);+ pos_lbl->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;").arg(colors::TEXT_SECONDARY()));+ ticket_position_lbl_ = new QLabel("—");+ ticket_position_lbl_->setAlignment(Qt::AlignRight);+ ticket_position_lbl_->setStyleSheet(+ QString("color: %1; font-size: 12px; font-weight: 700; background: transparent;")+ .arg(colors::TEXT_PRIMARY()));+ pos_col->addWidget(pos_lbl);+ pos_col->addWidget(ticket_position_lbl_);++ hdrl->addLayout(bal_col);+ hdrl->addStretch(1);+ hdrl->addLayout(pos_col);+ fl->addWidget(hdr);++ // Side selector: BUY / SELL+ auto* side_row = new QWidget;+ side_row->setStyleSheet("background: transparent;");+ auto* srl = new QHBoxLayout(side_row);+ srl->setContentsMargins(0, 0, 0, 0);+ srl->setSpacing(0);++ ticket_buy_btn_ = new QPushButton("BUY");+ ticket_sell_btn_ = new QPushButton("SELL");+ for (auto* b : {ticket_buy_btn_, ticket_sell_btn_}) {+ b->setFixedHeight(32);+ b->setCursor(Qt::PointingHandCursor);+ b->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);+ }+ connect(ticket_buy_btn_, &QPushButton::clicked, this, [this]() {+ ticket_side_ = "BUY";+ refresh_ticket_side_style();+ });+ connect(ticket_sell_btn_, &QPushButton::clicked, this, [this]() {+ ticket_side_ = "SELL";+ refresh_ticket_side_style();+ });+ srl->addWidget(ticket_buy_btn_);+ srl->addWidget(ticket_sell_btn_);+ fl->addWidget(side_row);++ // Outcome selector+ auto make_label = [&](const QString& text) -> QLabel* {+ auto* l = new QLabel(text);+ l->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;").arg(colors::TEXT_SECONDARY()));+ return l;+ };+ const QString input_ss =+ QString("QComboBox, QLineEdit {"+ " background: %1; color: %2; border: 1px solid %3;"+ " border-radius: 2px; padding: 4px 8px; font-size: 11px;"+ "}"+ "QComboBox::drop-down { border: none; }"+ "QComboBox QAbstractItemView {"+ " background: %1; color: %2; border: 1px solid %3; selection-background-color: %4;"+ "}")+ .arg(colors::BG_SURFACE(), colors::TEXT_PRIMARY(), colors::BORDER_MED(), colors::BG_HOVER());++ fl->addWidget(make_label("OUTCOME"));+ ticket_outcome_cb_ = new QComboBox;+ ticket_outcome_cb_->setStyleSheet(input_ss);+ fl->addWidget(ticket_outcome_cb_);++ // Price + Size row+ auto* ps_row = new QWidget;+ ps_row->setStyleSheet("background: transparent;");+ auto* psl = new QHBoxLayout(ps_row);+ psl->setContentsMargins(0, 0, 0, 0);+ psl->setSpacing(8);++ auto* price_col = new QVBoxLayout;+ price_col->setSpacing(4);+ price_col->addWidget(make_label("PRICE (0–1)"));+ ticket_price_edit_ = new QLineEdit;+ ticket_price_edit_->setPlaceholderText("0.50");+ ticket_price_edit_->setStyleSheet(input_ss);+ price_col->addWidget(ticket_price_edit_);++ auto* size_col = new QVBoxLayout;+ size_col->setSpacing(4);+ size_col->addWidget(make_label("SIZE"));+ ticket_size_edit_ = new QLineEdit;+ ticket_size_edit_->setPlaceholderText("10");+ ticket_size_edit_->setStyleSheet(input_ss);+ size_col->addWidget(ticket_size_edit_);++ psl->addLayout(price_col);+ psl->addLayout(size_col);+ fl->addWidget(ps_row);++ // Order type+ fl->addWidget(make_label("ORDER TYPE"));+ ticket_type_cb_ = new QComboBox;+ ticket_type_cb_->addItems({"GTC", "FOK", "FAK"});+ ticket_type_cb_->setStyleSheet(input_ss);+ fl->addWidget(ticket_type_cb_);++ // Submit button+ ticket_submit_btn_ = new QPushButton("PLACE ORDER");+ ticket_submit_btn_->setFixedHeight(34);+ ticket_submit_btn_->setCursor(Qt::PointingHandCursor);+ connect(ticket_submit_btn_, &QPushButton::clicked, this, &PolymarketDetailPanel::on_submit_clicked);+ fl->addWidget(ticket_submit_btn_);++ // Status label (feedback)+ ticket_status_lbl_ = new QLabel;+ ticket_status_lbl_->setAlignment(Qt::AlignCenter);+ ticket_status_lbl_->setWordWrap(true);+ ticket_status_lbl_->setStyleSheet(+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::TEXT_DIM()));+ fl->addWidget(ticket_status_lbl_);++ fl->addStretch(1);+ ticket_stack_->addWidget(form); // index 1++ refresh_ticket_side_style();+ return ticket_stack_;+}++void PolymarketDetailPanel::refresh_ticket_side_style() {+ if (!ticket_buy_btn_ || !ticket_sell_btn_ || !ticket_submit_btn_) return;+ const bool is_buy = (ticket_side_ == "BUY");+ const QString active_bg = is_buy ? colors::POSITIVE() : colors::NEGATIVE();+ const QString inactive_bg = colors::BG_RAISED();+ const QString active_text = "#0A0A0A";+ const QString inactive_text = colors::TEXT_DIM();++ ticket_buy_btn_->setStyleSheet(+ QString("QPushButton { background: %1; color: %2; border: none; "+ "font-size: 11px; font-weight: 700; }"+ "QPushButton:hover { opacity: 0.9; }")+ .arg(is_buy ? active_bg : inactive_bg,+ is_buy ? active_text : inactive_text));+ ticket_sell_btn_->setStyleSheet(+ QString("QPushButton { background: %1; color: %2; border: none; "+ "font-size: 11px; font-weight: 700; }"+ "QPushButton:hover { opacity: 0.9; }")+ .arg(!is_buy ? active_bg : inactive_bg,+ !is_buy ? active_text : inactive_text));+ ticket_submit_btn_->setStyleSheet(+ QString("QPushButton { background: %1; color: %2; border: none; "+ "border-radius: 2px; font-size: 12px; font-weight: 700; }"+ "QPushButton:hover { background: %3; }"+ "QPushButton:disabled { background: %4; color: %5; }")+ .arg(active_bg, active_text,+ QColor(active_bg).lighter(115).name(),+ colors::BG_RAISED(), colors::TEXT_DIM()));+}++void PolymarketDetailPanel::on_submit_clicked() {+ if (!has_last_market_) return;+ bool price_ok = false, size_ok = false;+ const double price = ticket_price_edit_->text().toDouble(&price_ok);+ const double size = ticket_size_edit_->text().toDouble(&size_ok);+ if (!price_ok || price <= 0.0 || price >= 1.0) {+ ticket_status_lbl_->setStyleSheet(+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));+ ticket_status_lbl_->setText("Invalid price — enter a value between 0 and 1");+ return;+ }+ if (!size_ok || size <= 0.0) {+ ticket_status_lbl_->setStyleSheet(+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));+ ticket_status_lbl_->setText("Invalid size — must be > 0");+ return;+ }++ const int outcome_idx = ticket_outcome_cb_->currentIndex();+ const QString asset_id = (outcome_idx >= 0 && outcome_idx < last_market_.outcomes.size())+ ? last_market_.outcomes[outcome_idx].asset_id+ : QString{};++ OrderRequest req;+ req.key = last_market_.key;+ req.asset_id = asset_id;+ req.side = ticket_side_;+ req.order_type = ticket_type_cb_->currentText();+ req.price = price;+ req.size = size;++ ticket_status_lbl_->setStyleSheet(+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::TEXT_DIM()));+ ticket_status_lbl_->setText("Submitting…");+ ticket_submit_btn_->setEnabled(false);+ emit place_order(req);+}++void PolymarketDetailPanel::set_balance(const AccountBalance& balance) {+ if (!ticket_balance_lbl_) return;+ ticket_balance_lbl_->setText(+ QString("%1 %2").arg(balance.available, 0, 'f', 2).arg(balance.currency));+}++void PolymarketDetailPanel::set_positions(const QVector<PredictionPosition>& positions) {+ if (!ticket_position_lbl_ || !has_last_market_) return;+ // Find the position matching the currently-displayed market.+ double total_size = 0.0;+ for (const auto& p : positions) {+ if (p.market_id == last_market_.key.market_id)+ total_size += p.size;+ }+ ticket_position_lbl_->setText(total_size > 0.0+ ? QString("%1 shares").arg(total_size, 0, 'f', 2)+ : "No position");+}++void PolymarketDetailPanel::on_order_result(const OrderResult& result) {+ if (!ticket_status_lbl_ || !ticket_submit_btn_) return;+ ticket_submit_btn_->setEnabled(true);+ if (result.ok) {+ ticket_status_lbl_->setStyleSheet(+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::POSITIVE()));+ ticket_status_lbl_->setText(+ QString("Order placed ✓ ID: %1").arg(result.order_id.left(12)));+ ticket_price_edit_->clear();+ ticket_size_edit_->clear();+ } else {+ ticket_status_lbl_->setStyleSheet(+ QString("color: %1; font-size: 10px; background: transparent;").arg(colors::NEGATIVE()));+ ticket_status_lbl_->setText(+ result.error_message.isEmpty() ? result.error_code : result.error_message);+ }+}++void PolymarketDetailPanel::set_trading_enabled(bool enabled) {+ if (!ticket_stack_) return;+ ticket_stack_->setCurrentIndex(enabled ? 1 : 0);+}+QWidget* PolymarketDetailPanel::create_holders_page() {holders_table_ = new QTableWidget;holders_table_->setColumnCount(4);@@ -158,25 +514,41 @@ QWidget* PolymarketDetailPanel::create_holders_page() {holders_table_->verticalHeader()->setVisible(false);holders_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);holders_table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ holders_table_->setShowGrid(false);holders_table_->setStyleSheet(- QString("QTableWidget { background: %1; color: %2; border: none; gridline-color: %3; font-size: 11px; }"- "QTableWidget::item { padding: 2px 6px; border-bottom: 1px solid %3; }"- "QHeaderView::section { background: %4; color: %5; border: none; "- " border-bottom: 1px solid %3; padding: 4px 6px; font-size: 10px; font-weight: 700; }")- .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));+ QString("QTableWidget { background: %1; color: %2; border: none; font-size: 10px; }"+ "QTableWidget::item { padding: 4px 8px; border-bottom: 1px solid %3; }"+ "QTableWidget::item:selected { background: %4; color: %2; }"+ "QHeaderView::section {"+ " background: %5; color: %6; border: none;"+ " border-bottom: 1px solid %3;"+ " padding: 5px 8px; font-size: 8px; font-weight: 700; letter-spacing: 0.5px;"+ "}"+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(),+ colors::BG_HOVER(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));return holders_table_;}QWidget* PolymarketDetailPanel::create_comments_page() {auto* scroll = new QScrollArea;scroll->setWidgetResizable(true);- scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }");- comments_container_ = new QWidget(this);+ scroll->setStyleSheet(+ QString("QScrollArea { border: none; background: %1; }"+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %2; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::BORDER_BRIGHT()));+ comments_container_ = new QWidget;+ comments_container_->setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));auto* vl = new QVBoxLayout(comments_container_);- vl->setContentsMargins(8, 8, 8, 8);- vl->setSpacing(4);+ vl->setContentsMargins(16, 16, 16, 16);+ vl->setSpacing(8);auto* empty = new QLabel("No comments yet");- empty->setStyleSheet(QString("color: %1; font-size: 13px; background: transparent;").arg(colors::TEXT_DIM()));+ empty->setStyleSheet(+ QString("color: %1; font-size: 12px; background: transparent;").arg(colors::TEXT_DIM()));empty->setAlignment(Qt::AlignCenter);vl->addWidget(empty);vl->addStretch(1);@@ -187,13 +559,20 @@ QWidget* PolymarketDetailPanel::create_comments_page() {QWidget* PolymarketDetailPanel::create_related_page() {auto* scroll = new QScrollArea;scroll->setWidgetResizable(true);- scroll->setStyleSheet("QScrollArea { border: none; background: transparent; }");- related_container_ = new QWidget(this);+ scroll->setStyleSheet(+ QString("QScrollArea { border: none; background: %1; }"+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %2; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::BORDER_BRIGHT()));+ related_container_ = new QWidget;+ related_container_->setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));auto* vl = new QVBoxLayout(related_container_);- vl->setContentsMargins(8, 8, 8, 8);- vl->setSpacing(4);+ vl->setContentsMargins(16, 16, 16, 16);+ vl->setSpacing(6);auto* empty = new QLabel("No related markets");- empty->setStyleSheet(QString("color: %1; font-size: 13px; background: transparent;").arg(colors::TEXT_DIM()));+ empty->setStyleSheet(+ QString("color: %1; font-size: 12px; background: transparent;").arg(colors::TEXT_DIM()));empty->setAlignment(Qt::AlignCenter);vl->addWidget(empty);vl->addStretch(1);@@ -221,53 +600,104 @@ void PolymarketDetailPanel::set_market(const PredictionMarket& market) {volume_label_->setText(presentation_.format_volume(market.volume));liquidity_label_->setText(presentation_.format_liquidity(market.liquidity));end_date_label_->setText(market.end_date_iso.left(10));- midpoint_label_->setText("--");- spread_label_->setText("--");- last_trade_label_->setText("--");- oi_label_->setText("--");+ midpoint_label_->setText("—");+ spread_label_->setText("—");+ last_trade_label_->setText("—");+ oi_label_->setText("—");render_status_badge(market);- // Outcomes- auto* layout = outcome_container_->layout();+ // ── Populate ticket outcome combo ─────────────────────────────────────+ if (ticket_outcome_cb_) {+ ticket_outcome_cb_->clear();+ for (const auto& o : market.outcomes)+ ticket_outcome_cb_->addItem(o.name);+ }+ if (ticket_status_lbl_) ticket_status_lbl_->clear();+ if (ticket_submit_btn_) ticket_submit_btn_->setEnabled(true);+ if (ticket_position_lbl_) ticket_position_lbl_->setText("—");++ // ── Rebuild outcome probability bars ──────────────────────────────────+ auto* layout = qobject_cast<QVBoxLayout*>(outcome_container_->layout());while (layout->count() > 0) {auto* item = layout->takeAt(0);- if (item->widget())- item->widget()->deleteLater();+ if (item->widget()) item->widget()->deleteLater();delete item;}for (int i = 0; i < market.outcomes.size(); ++i) {const auto& outcome = market.outcomes[i];- auto* row = new QWidget(this);- // Slot 0 tracks the exchange accent (Polymarket amber / Kalshi teal)- // so the primary outcome is visually tied to the current exchange.- // Slots 1+ fall back to the static palette.- QString color;- if (i == 0) color = presentation_.accent.name();- else if (i < OUTCOME_COLORS.size()) color = OUTCOME_COLORS[i];- else color = colors::TEXT_SECONDARY();- row->setStyleSheet(QString("background: %1; border-left: 3px solid %2; padding: 4px 8px; margin: 2px 0;")- .arg(colors::BG_RAISED(), color));- auto* rl = new QHBoxLayout(row);- rl->setContentsMargins(8, 4, 8, 4);- rl->setSpacing(8);-- auto* name = new QLabel(outcome.name);- name->setStyleSheet(QString("color: %1; font-size: 11px; font-weight: 700; background: transparent;")- .arg(colors::TEXT_PRIMARY()));- auto* price = new QLabel(presentation_.format_price(outcome.price));- price->setStyleSheet(- QString("color: %1; font-size: 13px; font-weight: 700; background: transparent;").arg(color));- rl->addWidget(name);- rl->addStretch(1);- rl->addWidget(price);+ const double pct = qBound(0.0, outcome.price, 1.0);+ const int pct_int = qRound(pct * 100.0);++ QColor bar_color;+ if (i == 0) bar_color = presentation_.accent;+ else if (i < 5) bar_color = QColor(OUTCOME_COLORS[i]);+ else bar_color = QColor(colors::TEXT_SECONDARY());++ // Outcome row: name + bar + price+ auto* row = new QWidget(outcome_container_);+ row->setStyleSheet("background: transparent;");+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0);+ rl->setSpacing(3);++ // Top line: name + percentage+ auto* top_line = new QWidget(row);+ top_line->setStyleSheet("background: transparent;");+ auto* tll = new QHBoxLayout(top_line);+ tll->setContentsMargins(0, 0, 0, 0);+ tll->setSpacing(6);++ auto* name_lbl = new QLabel(outcome.name, top_line);+ name_lbl->setStyleSheet(+ QString("color: %1; font-size: 10px; font-weight: 600; background: transparent;")+ .arg(colors::TEXT_PRIMARY()));++ auto* pct_lbl = new QLabel(QString("%1%").arg(pct_int), top_line);+ pct_lbl->setStyleSheet(+ QString("color: %1; font-size: 11px; font-weight: 700; background: transparent;")+ .arg(bar_color.name()));++ // Full formatted price (right side)+ auto* price_lbl = new QLabel(presentation_.format_price(pct), top_line);+ price_lbl->setStyleSheet(+ QString("color: %1; font-size: 10px; font-weight: 600; background: transparent;")+ .arg(colors::TEXT_SECONDARY()));++ tll->addWidget(name_lbl);+ tll->addStretch(1);+ tll->addWidget(pct_lbl);+ tll->addSpacing(8);+ tll->addWidget(price_lbl);+ rl->addWidget(top_line);++ // Progress bar — a simple fixed-height widget+ auto* bar_track = new QWidget(row);+ bar_track->setFixedHeight(6);+ bar_track->setStyleSheet(+ QString("background: %1; border-radius: 0px;").arg(colors::BG_RAISED()));+ // Fill widget sits inside the track with proportional width — use+ // a layout that we stretch manually via resize.+ auto* bar_fill = new QWidget(bar_track);+ bar_fill->setStyleSheet(+ QString("background: %1; border-radius: 0px;").arg(bar_color.name()));+ // Store pct on the fill widget so it can be re-sized on layout.+ bar_fill->setProperty("fill_pct", pct);++ // We need the fill to track the track width — use a nested layout.+ auto* bar_layout = new QHBoxLayout(bar_track);+ bar_layout->setContentsMargins(0, 0, 0, 0);+ bar_layout->setSpacing(0);+ bar_layout->addWidget(bar_fill, qRound(pct * 1000));+ if (pct < 1.0) bar_layout->addStretch(qRound((1.0 - pct) * 1000));++ rl->addWidget(bar_track);layout->addWidget(row);}- description_label_->setText(market.description.left(500));+ description_label_->setText(market.description.left(600));- // Outcome labels for chart — dynamic, read from prediction::Outcome::name.QStringList labels;labels.reserve(market.outcomes.size());for (const auto& o : market.outcomes)@@ -304,135 +734,149 @@ void PolymarketDetailPanel::set_top_holders(const QVector<pmx::TopHolder>& holderank->setTextAlignment(Qt::AlignCenter);holders_table_->setItem(i, 0, rank);holders_table_->setItem(i, 1, new QTableWidgetItem(h.display_name));- auto* size = new QTableWidgetItem(QString::number(h.position_size, 'f', 2));- size->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);- holders_table_->setItem(i, 2, size);- auto* price = new QTableWidgetItem(QString::number(h.entry_price, 'f', 4));- price->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);- holders_table_->setItem(i, 3, price);+ auto* size_item = new QTableWidgetItem(QString::number(h.position_size, 'f', 2));+ size_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ holders_table_->setItem(i, 2, size_item);+ auto* price_item = new QTableWidgetItem(QString::number(h.entry_price, 'f', 4));+ price_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ holders_table_->setItem(i, 3, price_item);+ if (i % 2 == 1) {+ for (int c = 0; c < 4; ++c) {+ if (auto* it = holders_table_->item(i, c))+ it->setBackground(QColor(colors::ROW_ALT()));+ }+ }}holders_table_->resizeColumnsToContents();holders_table_->setSortingEnabled(true);}void PolymarketDetailPanel::set_comments(const QVector<pmx::Comment>& comments) {- auto* layout = comments_container_->layout();- while (layout->count() > 0) {- auto* item = layout->takeAt(0);- if (item->widget())- item->widget()->deleteLater();+ auto* vl = qobject_cast<QVBoxLayout*>(comments_container_->layout());+ while (vl->count() > 0) {+ auto* item = vl->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();delete item;}if (comments.isEmpty()) {auto* empty = new QLabel("No comments yet");- empty->setStyleSheet(QString("color: %1; font-size: 13px; background: transparent;").arg(colors::TEXT_DIM()));+ empty->setStyleSheet(+ QString("color: %1; font-size: 12px; background: transparent;").arg(colors::TEXT_DIM()));empty->setAlignment(Qt::AlignCenter);- layout->addWidget(empty);+ vl->addWidget(empty);} else {for (const auto& c : comments) {- auto* card = new QWidget(this);- card->setStyleSheet(QString("background: %1; padding: 8px; margin: 2px 0; "- "border-left: 2px solid %2;")- .arg(colors::BG_RAISED(), colors::BORDER_MED()));+ auto* card = new QWidget(comments_container_);+ card->setStyleSheet(+ QString("background: %1; border: 1px solid %2; border-left: 2px solid %3;")+ .arg(colors::BG_SURFACE(), colors::BORDER_DIM(), colors::AMBER()));auto* cvl = new QVBoxLayout(card);- cvl->setContentsMargins(8, 4, 8, 4);- cvl->setSpacing(2);+ cvl->setContentsMargins(10, 8, 10, 8);+ cvl->setSpacing(4);- auto* author = new QLabel(c.author.isEmpty() ? c.author_address.left(10) + "..." : c.author);+ auto* author = new QLabel(c.author.isEmpty() ? c.author_address.left(12) + "…" : c.author);author->setStyleSheet(- QString("color: %1; font-size: 10px; font-weight: 700; background: transparent;").arg(colors::AMBER()));- cvl->addWidget(author);+ QString("color: %1; font-size: 9px; font-weight: 700; background: transparent;")+ .arg(colors::AMBER()));- auto* body = new QLabel(c.body.left(300));+ auto* body = new QLabel(c.body.left(280));body->setStyleSheet(- QString("color: %1; font-size: 11px; background: transparent;").arg(colors::TEXT_PRIMARY()));+ QString("color: %1; font-size: 10px; background: transparent; line-height: 1.4;")+ .arg(colors::TEXT_PRIMARY()));body->setWordWrap(true);- cvl->addWidget(body);- auto* meta = new QLabel(QDateTime::fromSecsSinceEpoch(c.created_at, Qt::UTC).toString("yyyy-MM-dd HH:mm") +- (c.likes > 0 ? QString(" %1 likes").arg(c.likes) : ""));- meta->setStyleSheet(QString("color: %1; font-size: 9px; background: transparent;").arg(colors::TEXT_DIM()));- cvl->addWidget(meta);+ auto* meta = new QLabel(+ QDateTime::fromSecsSinceEpoch(c.created_at, Qt::UTC).toString("yyyy-MM-dd HH:mm") ++ (c.likes > 0 ? QString(" · %1 likes").arg(c.likes) : ""));+ meta->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent;").arg(colors::TEXT_DIM()));- layout->addWidget(card);+ cvl->addWidget(author);+ cvl->addWidget(body);+ cvl->addWidget(meta);+ vl->addWidget(card);}}-- // Add stretch at end- static_cast<QVBoxLayout*>(layout)->addStretch(1);+ vl->addStretch(1);}void PolymarketDetailPanel::set_related_markets(const QVector<PredictionMarket>& markets) {- auto* layout = related_container_->layout();- while (layout->count() > 0) {- auto* item = layout->takeAt(0);- if (item->widget())- item->widget()->deleteLater();+ auto* vl = qobject_cast<QVBoxLayout*>(related_container_->layout());+ while (vl->count() > 0) {+ auto* item = vl->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();delete item;}if (markets.isEmpty()) {auto* empty = new QLabel("No related markets");- empty->setStyleSheet(QString("color: %1; font-size: 13px; background: transparent;").arg(colors::TEXT_DIM()));+ empty->setStyleSheet(+ QString("color: %1; font-size: 12px; background: transparent;").arg(colors::TEXT_DIM()));empty->setAlignment(Qt::AlignCenter);- layout->addWidget(empty);+ vl->addWidget(empty);} else {for (const auto& m : markets) {- auto* card = new QPushButton;- card->setText(m.question.left(60) + "\n" + presentation_.format_volume(m.volume));- card->setStyleSheet(QString("QPushButton { background: %1; color: %2; border: 1px solid %3; "- " text-align: left; padding: 8px; font-size: 11px; }"- "QPushButton:hover { background: %4; color: %5; }")- .arg(colors::BG_RAISED(), colors::TEXT_SECONDARY(), colors::BORDER_DIM(),- colors::BG_HOVER(), colors::TEXT_PRIMARY()));+ auto* card = new QPushButton(related_container_);+ card->setStyleSheet(+ QString("QPushButton {"+ " background: %1;"+ " color: %2;"+ " border: 1px solid %3;"+ " text-align: left;"+ " padding: 8px 12px;"+ " font-size: 10px;"+ " font-weight: 600;"+ "}"+ "QPushButton:hover { background: %4; color: %5; border-color: %6; }")+ .arg(colors::BG_SURFACE(), colors::TEXT_SECONDARY(), colors::BORDER_DIM(),+ colors::BG_HOVER(), colors::TEXT_PRIMARY(), colors::BORDER_BRIGHT()));+ card->setText(m.question.left(70) + (m.question.size() > 70 ? "…" : ""));card->setCursor(Qt::PointingHandCursor);connect(card, &QPushButton::clicked, this, [this, m]() { emit related_market_clicked(m); });- layout->addWidget(card);+ vl->addWidget(card);}}-- static_cast<QVBoxLayout*>(layout)->addStretch(1);+ vl->addStretch(1);}void PolymarketDetailPanel::set_open_interest(double oi) {oi_label_->setText(presentation_.format_volume(oi));}+void PolymarketDetailPanel::set_series_tooltip(const QString& tooltip) {+ if (question_label_) question_label_->setToolTip(tooltip);+}+void PolymarketDetailPanel::set_polymarket_extras_enabled(bool enabled) {- // The Holders / Comments / Related tabs exist only for Polymarket.- // When the active exchange doesn't offer them, hide the tab buttons and- // wipe any lingering content so stale Polymarket data is never shown- // under a Kalshi market.const int extra_tabs[] = {kTabHolders, kTabComments, kTabRelated};for (int idx : extra_tabs) {if (idx >= 0 && idx < tab_btns_.size())tab_btns_[idx]->setVisible(enabled);}if (!enabled) {- if (holders_table_) {- holders_table_->setRowCount(0);- }- auto clear_container = [this](QWidget* container, const QString& empty_msg) {+ if (holders_table_) holders_table_->setRowCount(0);++ auto clear_container = [this](QWidget* container, const QString& msg) {if (!container) return;- auto* layout = container->layout();- while (layout->count() > 0) {- auto* item = layout->takeAt(0);- if (item->widget())- item->widget()->deleteLater();+ auto* vl = qobject_cast<QVBoxLayout*>(container->layout());+ if (!vl) return;+ while (vl->count() > 0) {+ auto* item = vl->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();delete item;}- auto* empty = new QLabel(empty_msg);+ auto* empty = new QLabel(msg);empty->setStyleSheet(- QString("color: %1; font-size: 13px; background: transparent;").arg(colors::TEXT_DIM()));+ QString("color: %1; font-size: 12px; background: transparent;")+ .arg(colors::TEXT_DIM()));empty->setAlignment(Qt::AlignCenter);- layout->addWidget(empty);- static_cast<QVBoxLayout*>(layout)->addStretch(1);+ vl->addWidget(empty);+ vl->addStretch(1);};- clear_container(comments_container_, tr("Comments are a Polymarket-only feature"));- clear_container(related_container_, tr("Related markets are a Polymarket-only feature"));- // If the user is currently sitting on a Polymarket-only tab, bounce- // them back to Overview so they don't stare at a hidden tab.+ clear_container(comments_container_, tr("Comments are Polymarket-only"));+ clear_container(related_container_, tr("Related markets are Polymarket-only"));+const int current = stack_ ? stack_->currentIndex() : 0;if (current == kTabHolders || current == kTabComments || current == kTabRelated)set_active_tab(0);@@ -443,17 +887,26 @@ void PolymarketDetailPanel::clear() {has_last_market_ = false;last_market_ = {};question_label_->setText("Select a market to view details");- volume_label_->setText("--");- liquidity_label_->setText("--");- end_date_label_->setText("--");- midpoint_label_->setText("--");- spread_label_->setText("--");- last_trade_label_->setText("--");- oi_label_->setText("--");+ volume_label_->setText("—");+ liquidity_label_->setText("—");+ end_date_label_->setText("—");+ midpoint_label_->setText("—");+ spread_label_->setText("—");+ last_trade_label_->setText("—");+ oi_label_->setText("—");status_label_->clear();description_label_->clear();orderbook_->clear();activity_feed_->clear();++ // Clear outcomes+ if (auto* vl = qobject_cast<QVBoxLayout*>(outcome_container_->layout())) {+ while (vl->count() > 0) {+ auto* item = vl->takeAt(0);+ if (item->widget()) item->widget()->deleteLater();+ delete item;+ }+ }}// ── Presentation wiring ─────────────────────────────────────────────────────@@ -469,23 +922,44 @@ void PolymarketDetailPanel::set_presentation(const ExchangePresentation& p) {if (oi_changed) apply_presentation_to_stats();if (extras_changed) set_polymarket_extras_enabled(p.has_polymarket_extras);- // Re-render the currently-selected market so volume / price / status- // pick up the new formatters. If no market is selected yet, the next- // set_market() will apply the profile automatically.if (has_last_market_) set_market(last_market_);}void PolymarketDetailPanel::apply_accent_to_tabs() {const QColor& a = presentation_.accent;- const QString accent_css =+ const QString accent_str =QStringLiteral("rgba(%1,%2,%3,1.0)").arg(a.red()).arg(a.green()).arg(a.blue());+ const QString accent_bg =+ QStringLiteral("rgba(%1,%2,%3,0.12)").arg(a.red()).arg(a.green()).arg(a.blue());+const QString css =- QStringLiteral("QPushButton { background: transparent; color: %1; border: none; "- " font-size: 9px; font-weight: 700; padding: 6px 10px; "- " border-bottom: 2px solid transparent; }"- "QPushButton:hover { color: %2; }"- "QPushButton[active=\"true\"] { color: %2; border-bottom-color: %3; }")- .arg(colors::TEXT_SECONDARY(), colors::TEXT_PRIMARY(), accent_css);+ QStringLiteral(+ "QPushButton {"+ " background: transparent;"+ " color: %1;"+ " border: none;"+ " border-bottom: 2px solid transparent;"+ " font-size: 9px;"+ " font-weight: 700;"+ " letter-spacing: 0.5px;"+ " padding: 0 14px;"+ " min-height: 34px;"+ "}"+ "QPushButton:hover {"+ " color: %2;"+ " border-bottom-color: %3;"+ "}"+ "QPushButton[active=\"true\"] {"+ " color: %4;"+ " border-bottom-color: %4;"+ " background: %5;"+ "}")+ .arg(colors::TEXT_SECONDARY()) // inactive text+ .arg(colors::TEXT_PRIMARY()) // hover text+ .arg(colors::BORDER_BRIGHT()) // hover underline+ .arg(accent_str) // active text + underline+ .arg(accent_bg); // active background tint+for (auto* btn : tab_btns_) {btn->setStyleSheet(css);btn->style()->unpolish(btn);@@ -500,15 +974,18 @@ void PolymarketDetailPanel::apply_presentation_to_stats() {void PolymarketDetailPanel::render_status_badge(const PredictionMarket& market) {const auto badge = presentation_.status_badge(market);status_label_->setText(badge.text);+ status_label_->setToolTip(badge.tooltip);const QString bg_css = badge.bg.alpha() > 0? QStringLiteral("rgba(%1,%2,%3,%4)").arg(badge.bg.red()).arg(badge.bg.green()).arg(badge.bg.blue()).arg(badge.bg.alphaF(), 0, 'f', 2): QStringLiteral("transparent");+status_label_->setStyleSheet(- QString("color: %1; background: %2; font-size: 9px; font-weight: 700; padding: 2px 6px;")- .arg(badge.fg.name(), bg_css));+ QString("color: %1; background: %2; font-size: 8px; font-weight: 700; "+ "padding: 2px 8px; border: 1px solid %3; letter-spacing: 0.5px;")+ .arg(badge.fg.name(), bg_css, badge.fg.name()));}} // namespace fincept::screens::polymarketdiff --git a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.hindex 5626486e5..30eb71cc6 100644--- a/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h+++ b/fincept-qt/src/screens/polymarket/PolymarketDetailPanel.h@@ -4,7 +4,9 @@#include "services/polymarket/PolymarketTypes.h"#include "services/prediction/PredictionTypes.h"+#include <QComboBox>#include <QLabel>+#include <QLineEdit>#include <QPushButton>#include <QStackedWidget>#include <QTableWidget>@@ -40,6 +42,15 @@ class PolymarketDetailPanel : public QWidget {void set_price_history(const fincept::services::prediction::PriceHistory& history);void set_trades(const QVector<fincept::services::prediction::PredictionTrade>& trades);+ // Trading ticket setters — wired from adapter balance_ready / positions_ready.+ void set_balance(const fincept::services::prediction::AccountBalance& balance);+ void set_positions(const QVector<fincept::services::prediction::PredictionPosition>& positions);+ void on_order_result(const fincept::services::prediction::OrderResult& result);++ /// Called when credentials state changes so ticket can show/hide the+ /// "connect account" placeholder vs the actual ticket form.+ void set_trading_enabled(bool enabled);+// Polymarket-only enrichment setters — guarded by active_id at the caller.void set_price_summary(const fincept::services::polymarket::PriceSummary& summary);void set_top_holders(const QVector<fincept::services::polymarket::TopHolder>& holders);@@ -47,6 +58,11 @@ class PolymarketDetailPanel : public QWidget {void set_related_markets(const QVector<fincept::services::prediction::PredictionMarket>& markets);void set_open_interest(double oi);+ /// Attach a long-form tooltip (e.g. series fee info) to the market+ /// question label. Pass an empty string to clear. Used by Kalshi to+ /// surface per-series fee_type + fee_multiplier on hover.+ void set_series_tooltip(const QString& tooltip);+/// Hide/disable the Polymarket-only tabs (Holders/Comments/Related) and/// clear their contents. Called when the active exchange changes to a/// provider that does not support those enrichments.@@ -59,10 +75,12 @@ class PolymarketDetailPanel : public QWidget {void interval_changed(const QString& interval);void outcome_changed(int index);void related_market_clicked(const fincept::services::prediction::PredictionMarket& market);+ void place_order(const fincept::services::prediction::OrderRequest& req);private:void build_ui();QWidget* create_overview_page();+ QWidget* create_trade_page();QWidget* create_holders_page();QWidget* create_comments_page();QWidget* create_related_page();@@ -71,6 +89,8 @@ class PolymarketDetailPanel : public QWidget {void apply_accent_to_tabs();void apply_presentation_to_stats(); // show/hide OPEN INT cell, re-labelvoid render_status_badge(const fincept::services::prediction::PredictionMarket& market);+ void refresh_ticket_side_style();+ void on_submit_clicked();QList<QPushButton*> tab_btns_;QStackedWidget* stack_ = nullptr;@@ -93,6 +113,20 @@ class PolymarketDetailPanel : public QWidget {PolymarketPriceChart* price_chart_ = nullptr;PolymarketActivityFeed* activity_feed_ = nullptr;+ // Trade ticket+ QStackedWidget* ticket_stack_ = nullptr; // 0=no-account, 1=ticket+ QLabel* ticket_balance_lbl_ = nullptr;+ QLabel* ticket_position_lbl_= nullptr;+ QComboBox* ticket_outcome_cb_ = nullptr;+ QPushButton* ticket_buy_btn_ = nullptr;+ QPushButton* ticket_sell_btn_ = nullptr;+ QLineEdit* ticket_price_edit_ = nullptr;+ QLineEdit* ticket_size_edit_ = nullptr;+ QComboBox* ticket_type_cb_ = nullptr;+ QPushButton* ticket_submit_btn_ = nullptr;+ QLabel* ticket_status_lbl_ = nullptr;+ QString ticket_side_ = "BUY";+// HoldersQTableWidget* holders_table_ = nullptr;@@ -116,10 +150,12 @@ class PolymarketDetailPanel : public QWidget {fincept::services::prediction::PredictionMarket last_market_;bool has_last_market_ = false;- // Polymarket-only tab button indices (for enable/disable).- static constexpr int kTabHolders = 4;- static constexpr int kTabComments = 5;- static constexpr int kTabRelated = 6;+ // Tab indices.+ static constexpr int kTabTrade = 3;+ static constexpr int kTabTrades = 4;+ static constexpr int kTabHolders = 5;+ static constexpr int kTabComments = 6;+ static constexpr int kTabRelated = 7;};} // namespace fincept::screens::polymarketdiff --git a/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp b/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cppindex 9b9c4d5aa..d18ea6fe2 100644--- a/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketLeaderboard.cpp@@ -3,6 +3,7 @@#include "ui/theme/Theme.h"#include <QHeaderView>+#include <QHBoxLayout>#include <QLabel>#include <QVBoxLayout>@@ -25,26 +26,43 @@ PolymarketLeaderboard::PolymarketLeaderboard(QWidget* parent) : QWidget(parent)vl->setContentsMargins(0, 0, 0, 0);vl->setSpacing(0);+ auto* header_bar = new QWidget;+ header_bar->setFixedHeight(30);+ header_bar->setStyleSheet(+ QString("background: %1; border-bottom: 1px solid %2;")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));+ auto* hbl = new QHBoxLayout(header_bar);+ hbl->setContentsMargins(12, 0, 8, 0);auto* header = new QLabel("LEADERBOARD");- header->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700; "- "letter-spacing: 0.5px; background: transparent; "- "padding: 6px 8px; border-bottom: 1px solid %2;")- .arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM()));- vl->addWidget(header);+ header->setStyleSheet(+ QString("color: %1; font-size: 9px; font-weight: 700; letter-spacing: 0.8px; "+ "background: transparent;")+ .arg(colors::TEXT_SECONDARY()));+ hbl->addWidget(header);+ hbl->addStretch(1);+ vl->addWidget(header_bar);table_ = new QTableWidget;table_->setColumnCount(5);table_->setHorizontalHeaderLabels({"#", "TRADER", "PNL", "VOLUME", "TRADES"});table_->horizontalHeader()->setStretchLastSection(true);+ table_->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);table_->verticalHeader()->setVisible(false);table_->setEditTriggers(QAbstractItemView::NoEditTriggers);table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setShowGrid(false);table_->setStyleSheet(- QString("QTableWidget { background: %1; color: %2; border: none; gridline-color: %3; font-size: 11px; }"- "QTableWidget::item { padding: 2px 6px; border-bottom: 1px solid %3; }"- "QHeaderView::section { background: %4; color: %5; border: none; "- " border-bottom: 1px solid %3; padding: 4px 6px; font-size: 10px; font-weight: 700; }")- .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));+ QString("QTableWidget { background: %1; color: %2; border: none; font-size: 10px; }"+ "QTableWidget::item { padding: 3px 8px; border-bottom: 1px solid %3; }"+ "QTableWidget::item:selected { background: %4; color: %2; }"+ "QHeaderView::section { background: %5; color: %6; border: none;"+ " border-bottom: 1px solid %3; padding: 5px 8px;"+ " font-size: 8px; font-weight: 700; letter-spacing: 0.5px; }"+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(),+ colors::BG_HOVER(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));vl->addWidget(table_, 1);}diff --git a/fincept-qt/src/screens/polymarket/PolymarketMarketCard.cpp b/fincept-qt/src/screens/polymarket/PolymarketMarketCard.cppindex 9de985abd..cd12275de 100644--- a/fincept-qt/src/screens/polymarket/PolymarketMarketCard.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketMarketCard.cpp@@ -9,9 +9,6 @@ namespace fincept::screens::polymarket {using namespace fincept::ui;using namespace fincept::services::prediction;-// Outcome palette for multi-outcome markets. Slots 0–1 are the primary-// yes/no pair and are accent-colored dynamically at paint time; slots 2+-// are fallbacks used only for 3+-way Polymarket markets.static const char* OUTCOME_BAR_COLORS[] = {"#00D66F", "#FF3B3B", "#FF8800", "#4F8EF7", "#A855F7"};static QChar outcome_initial(const QString& name) {@@ -60,9 +57,6 @@ void PolymarketMarketCardModel::set_view_mode(const QString& mode) {void PolymarketMarketCardModel::set_presentation(const ExchangePresentation& p) {presentation_ = p;- // Full reset — the delegate re-paints from scratch and picks up the- // new accent/formatter. A targeted dataChanged(0..N) would be cheaper- // but the list is bounded (20/page) so the difference is invisible.beginResetModel();endResetModel();}@@ -73,6 +67,19 @@ const PredictionMarket* PolymarketMarketCardModel::market_at(int row) const {return nullptr;}+bool PolymarketMarketCardModel::update_market(const PredictionMarket& market) {+ if (view_mode_ != QStringLiteral("markets")) return false;+ for (int i = 0; i < markets_.size(); ++i) {+ if (markets_[i].key.market_id == market.key.market_id) {+ markets_[i] = market;+ const auto idx = index(i);+ emit dataChanged(idx, idx);+ return true;+ }+ }+ return false;+}+const PredictionEvent* PolymarketMarketCardModel::event_at(int row) const {if (view_mode_ == "events" && row >= 0 && row < events_.size())return &events_[row];@@ -81,10 +88,11 @@ const PredictionEvent* PolymarketMarketCardModel::event_at(int row) const {// ── Delegate ────────────────────────────────────────────────────────────────-PolymarketMarketCardDelegate::PolymarketMarketCardDelegate(QObject* parent) : QStyledItemDelegate(parent) {}+PolymarketMarketCardDelegate::PolymarketMarketCardDelegate(QObject* parent)+ : QStyledItemDelegate(parent) {}QSize PolymarketMarketCardDelegate::sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const {- return {280, 86};+ return {280, 80};}void PolymarketMarketCardDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,@@ -92,51 +100,63 @@ void PolymarketMarketCardDelegate::paint(QPainter* painter, const QStyleOptionVipainter->save();painter->setRenderHint(QPainter::Antialiasing, false);- QRect r = option.rect;- bool selected = option.state & QStyle::State_Selected;- bool hovered = option.state & QStyle::State_MouseOver;+ QColor accent(colors::AMBER());+ if (const auto* m = qobject_cast<const PolymarketMarketCardModel*>(index.model()))+ accent = m->presentation().accent;+ const QRect r = option.rect;+ const bool selected = option.state & QStyle::State_Selected;+ const bool hovered = option.state & QStyle::State_MouseOver;++ // ── Background ────────────────────────────────────────────────────────if (selected) {- painter->fillRect(r, QColor(colors::AMBER()).darker(400));- painter->setPen(QPen(QColor(colors::AMBER()), 2));- painter->drawLine(r.left(), r.top(), r.left(), r.bottom());+ // Selected: deep tinted background, left accent rail+ QColor sel_bg = accent;+ sel_bg.setAlphaF(0.10);+ painter->fillRect(r, sel_bg);+ // Left accent rail (3px)+ painter->fillRect(r.left(), r.top(), 3, r.height(), accent);} else if (hovered) {painter->fillRect(r, QColor(colors::BG_HOVER()));} else {painter->fillRect(r, QColor(colors::BG_BASE()));}+ // Bottom dividerpainter->setPen(QColor(colors::BORDER_DIM()));- painter->drawLine(r.left(), r.bottom(), r.right(), r.bottom());+ painter->drawLine(r.left() + (selected ? 3 : 0), r.bottom(), r.right(), r.bottom());auto* model = qobject_cast<const PolymarketMarketCardModel*>(index.model());- if (!model) {- painter->restore();- return;- }+ if (!model) { painter->restore(); return; }const auto& pres = model->presentation();- int row = index.row();- int x = r.left() + 10;- int y = r.top() + 8;- int w = r.width() - 20;+ const int left_pad = selected ? r.left() + 10 : r.left() + 10;+ int x = left_pad;+ int y = r.top() + 10;+ const int w = r.right() - 12 - x;- const PredictionMarket* mkt = model->market_at(row);- const PredictionEvent* evt = model->event_at(row);+ const PredictionMarket* mkt = model->market_at(index.row());+ const PredictionEvent* evt = model->event_at(index.row());QString title;double vol = 0;QVector<Outcome> outcomes;int sub_market_count = 0;+ bool is_active = true;+ bool is_closed = false;if (mkt) {- title = mkt->question;- vol = mkt->volume;- outcomes = mkt->outcomes;+ title = mkt->question;+ vol = mkt->volume;+ outcomes = mkt->outcomes;+ is_active = mkt->active;+ is_closed = mkt->closed;} else if (evt) {- title = evt->title;- vol = evt->volume;+ title = evt->title;+ vol = evt->volume;sub_market_count = evt->markets.size();+ is_active = evt->active;+ is_closed = evt->closed;if (!evt->markets.isEmpty())outcomes = evt->markets[0].outcomes;} else {@@ -144,55 +164,79 @@ void PolymarketMarketCardDelegate::paint(QPainter* painter, const QStyleOptionVireturn;}- // Title (2 lines max). Selected row gets painted in the exchange accent.- QFont font(fonts::DATA_FAMILY, 11);- font.setWeight(QFont::Bold);- painter->setFont(font);- painter->setPen(QColor(selected ? pres.accent : QColor(colors::TEXT_PRIMARY())));- QRect title_rect(x, y, w, 30);- painter->drawText(title_rect, Qt::AlignLeft | Qt::TextWordWrap, title.left(80));- y += 32;-- // Dynamic outcome bars — read names/prices from prediction::Outcome so- // Polymarket (Yes/No), Kalshi (yes/no), and custom multi-outcome markets- // all render without code changes. Render up to 2 rows. Price labels- // are formatted by the presentation (cents suffix on Polymarket,- // dollars on Kalshi).+ // ── Title ─────────────────────────────────────────────────────────────+ QFont title_font(fonts::DATA_FAMILY, 10);+ title_font.setWeight(QFont::DemiBold);+ painter->setFont(title_font);++ QColor title_color = selected ? accent : QColor(colors::TEXT_PRIMARY());+ if (is_closed) title_color = QColor(colors::TEXT_DIM());+ painter->setPen(title_color);++ const QRect title_rect(x, y, w, 28);+ painter->drawText(title_rect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap,+ title.left(90));+ y += 30;++ // ── Outcome probability bars ──────────────────────────────────────────const int bars_to_draw = qMin(2, outcomes.size());- if (bars_to_draw >= 2) {- const int bar_w = w - 80; // wider right gutter for "$0.52" vs "Y 52¢"- const int bar_h = 14;- QFont small_font(fonts::DATA_FAMILY, 9);- small_font.setWeight(QFont::Bold);+ if (bars_to_draw >= 1) {+ const int bar_w = w - 62; // leave space for price label+ const int bar_h = 8;+ const int gap = 4;++ QFont price_font(fonts::DATA_FAMILY, 9);+ price_font.setWeight(QFont::Bold);for (int i = 0; i < bars_to_draw; ++i) {- const auto& o = outcomes[i];+ const auto& o = outcomes[i];const double pct = qBound(0.0, o.price, 1.0);const int filled = static_cast<int>(bar_w * pct);- // Slot 0 tracks the exchange accent; slot 1 stays red so the- // primary/secondary outcome split remains readable even when- // the accent itself shifts.+QColor bar_color = (i == 0) ? pres.accent : QColor(OUTCOME_BAR_COLORS[qMin(i, 4)]);- painter->fillRect(x, y, filled, bar_h, bar_color);- painter->fillRect(x + filled, y, bar_w - filled, bar_h, QColor(colors::BG_RAISED()));-- painter->setFont(small_font);- painter->setPen(QColor(colors::TEXT_PRIMARY()));- painter->drawText(x + bar_w + 4, y, 72, bar_h, Qt::AlignLeft | Qt::AlignVCenter,- QString("%1 %2").arg(outcome_initial(o.name)).arg(pres.format_price(pct)));- y += bar_h + 2;+ if (is_closed) bar_color = QColor(colors::BORDER_BRIGHT());++ // Track (background)+ painter->fillRect(x, y, bar_w, bar_h, QColor(colors::BG_RAISED()));+ // Fill+ if (filled > 0)+ painter->fillRect(x, y, filled, bar_h, bar_color);++ // Price label (right-aligned to bar gutter)+ painter->setFont(price_font);+ painter->setPen(is_closed ? QColor(colors::TEXT_DIM()) : bar_color);+ const QString price_str = pres.format_price(pct);+ painter->drawText(x + bar_w + 4, y - 1, 56, bar_h + 2,+ Qt::AlignLeft | Qt::AlignVCenter, price_str);++ y += bar_h + gap;}} else {- QFont small_font(fonts::DATA_FAMILY, 10);- painter->setFont(small_font);+ // Single-outcome or no-outcome: show volume+ QFont meta_font(fonts::DATA_FAMILY, 9);+ painter->setFont(meta_font);painter->setPen(QColor(colors::TEXT_SECONDARY()));- painter->drawText(x, y, w, 16, Qt::AlignLeft | Qt::AlignVCenter, pres.format_volume(vol));+ painter->drawText(x, y, w, 14, Qt::AlignLeft | Qt::AlignVCenter,+ pres.format_volume(vol));if (evt && sub_market_count > 0) {- painter->drawText(x + 80, y, w - 80, 16, Qt::AlignLeft | Qt::AlignVCenter,- QString("%1 markets").arg(sub_market_count));+ painter->drawText(x + 80, y, w - 80, 14, Qt::AlignLeft | Qt::AlignVCenter,+ QString("%1 mkts").arg(sub_market_count));}}+ // ── Status dot (top-right corner) ─────────────────────────────────────+ const int dot_x = r.right() - 10;+ const int dot_y = r.top() + 10;+ if (is_closed) {+ painter->setPen(Qt::NoPen);+ painter->setBrush(QColor(colors::TEXT_DIM()));+ painter->drawEllipse(dot_x, dot_y, 5, 5);+ } else if (is_active) {+ painter->setPen(Qt::NoPen);+ painter->setBrush(QColor(colors::POSITIVE()));+ painter->drawEllipse(dot_x, dot_y, 5, 5);+ }+painter->restore();}diff --git a/fincept-qt/src/screens/polymarket/PolymarketMarketCard.h b/fincept-qt/src/screens/polymarket/PolymarketMarketCard.hindex fe1e5afa6..1c23f663e 100644--- a/fincept-qt/src/screens/polymarket/PolymarketMarketCard.h+++ b/fincept-qt/src/screens/polymarket/PolymarketMarketCard.h@@ -25,6 +25,10 @@ class PolymarketMarketCardModel : public QAbstractListModel {void set_view_mode(const QString& mode); // "markets" or "events"void set_presentation(const ExchangePresentation& p);+ /// Replace a single market by key.market_id without rebuilding the+ /// whole list. Returns true if the row existed and was updated.+ bool update_market(const fincept::services::prediction::PredictionMarket& market);+const fincept::services::prediction::PredictionMarket* market_at(int row) const;const fincept::services::prediction::PredictionEvent* event_at(int row) const;const ExchangePresentation& presentation() const { return presentation_; }diff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cpp b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cppnew file mode 100644index 000000000..eb1244a44--- /dev/null+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.cpp@@ -0,0 +1,268 @@+#include "screens/polymarket/PolymarketOrderBlotter.h"++#include "ui/theme/Theme.h"++#include <QHBoxLayout>+#include <QHeaderView>+#include <QInputDialog>+#include <QLabel>+#include <QPushButton>+#include <QVBoxLayout>++namespace fincept::screens::polymarket {++using namespace fincept::ui;+using namespace fincept::services::prediction;++namespace {++// Column indices — kept as an enum so the row-build and cell-update paths+// stay in lockstep when we add a column.+enum Column : int {+ ColTime = 0,+ ColMarket,+ ColSide,+ ColOutcome,+ ColType,+ ColPrice,+ ColSize,+ ColFilled,+ ColStatus,+ ColActions,+ ColCount,+};++QString col_label(int c) {+ switch (c) {+ case ColTime: return QStringLiteral("TIME");+ case ColMarket: return QStringLiteral("MARKET");+ case ColSide: return QStringLiteral("SIDE");+ case ColOutcome: return QStringLiteral("OUTCOME");+ case ColType: return QStringLiteral("TYPE");+ case ColPrice: return QStringLiteral("PRICE");+ case ColSize: return QStringLiteral("SIZE");+ case ColFilled: return QStringLiteral("FILLED");+ case ColStatus: return QStringLiteral("STATUS");+ case ColActions: return QStringLiteral("ACTIONS");+ }+ return {};+}++} // namespace++PolymarketOrderBlotter::PolymarketOrderBlotter(QWidget* parent) : QWidget(parent) {+ setObjectName("polyOrderBlotter");+ auto* vl = new QVBoxLayout(this);+ vl->setContentsMargins(0, 0, 0, 0);+ vl->setSpacing(0);++ auto* header_bar = new QWidget(this);+ header_bar->setFixedHeight(30);+ header_bar->setStyleSheet(+ QString("background: %1; border-bottom: 1px solid %2;")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));+ auto* hhl = new QHBoxLayout(header_bar);+ hhl->setContentsMargins(12, 0, 8, 0);+ hhl->setSpacing(8);++ auto* title = new QLabel(QStringLiteral("OPEN ORDERS"), header_bar);+ title->setStyleSheet(+ QString("color: %1; font-size: 9px; font-weight: 700; background: transparent; "+ "letter-spacing: 0.8px;")+ .arg(colors::TEXT_SECONDARY()));+ hhl->addWidget(title);+ hhl->addStretch(1);++ auto* cancel_all_btn = new QPushButton(QStringLiteral("CANCEL ALL"), header_bar);+ cancel_all_btn->setObjectName("orderBlotterCancelAll");+ cancel_all_btn->setCursor(Qt::PointingHandCursor);+ cancel_all_btn->setStyleSheet(+ QString("QPushButton { background: transparent; color: %1; "+ " border: 1px solid %1; padding: 2px 8px; font-size: 9px; font-weight: 700; }"+ "QPushButton:hover { background: rgba(239,68,68,0.15); }"+ "QPushButton:disabled { color: %2; border-color: %2; }")+ .arg(colors::NEGATIVE(), colors::TEXT_DIM()));+ connect(cancel_all_btn, &QPushButton::clicked, this,+ &PolymarketOrderBlotter::on_cancel_all_clicked);+ hhl->addWidget(cancel_all_btn);+ vl->addWidget(header_bar);++ table_ = new QTableWidget(this);+ table_->setColumnCount(ColCount);+ QStringList headers;+ for (int c = 0; c < ColCount; ++c) headers << col_label(c);+ table_->setHorizontalHeaderLabels(headers);+ table_->verticalHeader()->setVisible(false);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers); // double-click drives amend+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setSelectionMode(QAbstractItemView::SingleSelection);+ table_->horizontalHeader()->setStretchLastSection(false);+ table_->horizontalHeader()->setSectionResizeMode(ColMarket, QHeaderView::Stretch);+ table_->setShowGrid(false);+ table_->setStyleSheet(+ QString("QTableWidget { background: %1; color: %2; border: none; font-size: 10px; }"+ "QTableWidget::item { padding: 3px 8px; border-bottom: 1px solid %3; }"+ "QTableWidget::item:selected { background: %4; color: %2; }"+ "QHeaderView::section { background: %5; color: %6; border: none;"+ " border-bottom: 1px solid %3; padding: 5px 8px;"+ " font-size: 8px; font-weight: 700; letter-spacing: 0.5px; }"+ "QScrollBar:vertical { background: %1; width: 4px; border: none; }"+ "QScrollBar::handle:vertical { background: %3; min-height: 20px; }"+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(),+ colors::BG_HOVER(), colors::BG_RAISED(), colors::TEXT_SECONDARY()));+ connect(table_, &QTableWidget::cellDoubleClicked, this,+ &PolymarketOrderBlotter::on_cell_double_clicked);+ vl->addWidget(table_, 1);+}++void PolymarketOrderBlotter::set_orders(const QVector<OpenOrder>& orders) {+ orders_ = orders;+ rebuild_rows();+}++void PolymarketOrderBlotter::update_order(const OpenOrder& order) {+ for (int i = 0; i < orders_.size(); ++i) {+ if (orders_[i].order_id == order.order_id) {+ orders_[i] = order;+ rebuild_rows();+ return;+ }+ }+ orders_.push_back(order);+ rebuild_rows();+}++void PolymarketOrderBlotter::clear() {+ orders_.clear();+ rebuild_rows();+}++void PolymarketOrderBlotter::set_presentation(const ExchangePresentation& p) {+ presentation_ = p;+ rebuild_rows();+}++void PolymarketOrderBlotter::set_capabilities(bool supports_amend, bool supports_batch_cancel) {+ supports_amend_ = supports_amend;+ supports_batch_cancel_ = supports_batch_cancel;+ rebuild_rows();+}++void PolymarketOrderBlotter::rebuild_rows() {+ table_->setSortingEnabled(false);+ table_->setRowCount(orders_.size());+ const int price_decimals = qBound(0, presentation_.price_decimal_places, 6);++ for (int i = 0; i < orders_.size(); ++i) {+ const auto& o = orders_[i];+ table_->setItem(i, ColTime,+ new QTableWidgetItem(QString::number(o.expires_ms))); // placeholder: expiry+ table_->setItem(i, ColMarket, new QTableWidgetItem(o.market_id));++ auto* side_item = new QTableWidgetItem(o.side);+ side_item->setForeground(QColor(o.side.compare("BUY", Qt::CaseInsensitive) == 0+ ? colors::POSITIVE()+ : colors::NEGATIVE()));+ table_->setItem(i, ColSide, side_item);++ table_->setItem(i, ColOutcome, new QTableWidgetItem(o.outcome));+ table_->setItem(i, ColType, new QTableWidgetItem(o.order_type));++ auto* price_item = new QTableWidgetItem(QString::number(o.price, 'f', price_decimals));+ price_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ price_item->setForeground(presentation_.accent);+ // The double-click-to-amend affordance: mark the cell enabled only+ // when the adapter supports amend. Leaves the cell display-only on+ // Polymarket so users don't double-click expecting behaviour.+ if (supports_amend_) {+ price_item->setFlags(price_item->flags() | Qt::ItemIsEnabled);+ price_item->setToolTip(QStringLiteral("Double-click to amend price"));+ }+ table_->setItem(i, ColPrice, price_item);++ auto* size_item = new QTableWidgetItem(QString::number(o.size, 'f', 2));+ size_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table_->setItem(i, ColSize, size_item);++ auto* filled_item = new QTableWidgetItem(QString::number(o.filled, 'f', 2));+ filled_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ table_->setItem(i, ColFilled, filled_item);++ table_->setItem(i, ColStatus, new QTableWidgetItem(o.status));++ install_row_controls(i, o);+ }++ table_->resizeColumnsToContents();+ table_->horizontalHeader()->setSectionResizeMode(ColMarket, QHeaderView::Stretch);++ // "Cancel All" enable state — only meaningful when there's at least+ // one row and the adapter supports either single- or batch-cancel.+ if (auto* btn = findChild<QPushButton*>(QStringLiteral("orderBlotterCancelAll"))) {+ btn->setEnabled(!orders_.isEmpty());+ }+}++void PolymarketOrderBlotter::install_row_controls(int row, const OpenOrder& order) {+ auto* host = new QWidget(table_);+ auto* rhl = new QHBoxLayout(host);+ rhl->setContentsMargins(4, 0, 4, 0);+ rhl->setSpacing(4);++ auto* refresh_btn = new QPushButton(QStringLiteral("↻"), host);+ refresh_btn->setFixedSize(22, 20);+ refresh_btn->setCursor(Qt::PointingHandCursor);+ refresh_btn->setToolTip(QStringLiteral("Refresh order state"));+ refresh_btn->setStyleSheet(+ QString("QPushButton { background: transparent; color: %1; border: 1px solid %2; "+ "font-size: 11px; } QPushButton:hover { color: %3; border-color: %3; }")+ .arg(colors::TEXT_SECONDARY(), colors::BORDER_DIM(),+ presentation_.accent.name()));+ const QString oid = order.order_id;+ connect(refresh_btn, &QPushButton::clicked, this,+ [this, oid]() { emit refresh_order(oid); });+ rhl->addWidget(refresh_btn);++ auto* cancel_btn = new QPushButton(QStringLiteral("✕"), host);+ cancel_btn->setFixedSize(22, 20);+ cancel_btn->setCursor(Qt::PointingHandCursor);+ cancel_btn->setToolTip(QStringLiteral("Cancel order"));+ cancel_btn->setStyleSheet(+ QString("QPushButton { background: transparent; color: %1; border: 1px solid %1; "+ "font-size: 11px; } QPushButton:hover { background: rgba(239,68,68,0.15); }")+ .arg(colors::NEGATIVE()));+ connect(cancel_btn, &QPushButton::clicked, this,+ [this, oid]() { emit cancel_order(oid); });+ rhl->addWidget(cancel_btn);++ rhl->addStretch(1);+ table_->setCellWidget(row, ColActions, host);+}++void PolymarketOrderBlotter::on_cell_double_clicked(int row, int column) {+ if (column != ColPrice || !supports_amend_) return;+ if (row < 0 || row >= orders_.size()) return;+ const auto& o = orders_[row];+ bool ok = false;+ // The Kalshi limit-price domain is 1-99 cents — we constrain the input+ // dialog to the valid range so users can't submit an order that the+ // exchange will reject.+ const double new_price = QInputDialog::getDouble(+ this, QStringLiteral("Amend price"),+ QStringLiteral("New limit price (0.01 – 0.99):"),+ o.price, 0.01, 0.99, 2, &ok);+ if (!ok) return;+ emit amend_order(o.order_id, o.side.toLower(), new_price);+}++void PolymarketOrderBlotter::on_cancel_all_clicked() {+ if (orders_.isEmpty()) return;+ QStringList ids;+ ids.reserve(orders_.size());+ for (const auto& o : orders_)+ if (!o.order_id.isEmpty()) ids.push_back(o.order_id);+ if (!ids.isEmpty()) emit cancel_all(ids);+}++} // namespace fincept::screens::polymarketdiff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.h b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.hnew file mode 100644index 000000000..d1ce35f3c--- /dev/null+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBlotter.h@@ -0,0 +1,65 @@+#pragma once++#include "screens/polymarket/ExchangePresentation.h"+#include "services/prediction/PredictionTypes.h"++#include <QTableWidget>+#include <QVector>+#include <QWidget>++namespace fincept::screens::polymarket {++/// Open-orders blotter with inline controls (amend price / refresh / cancel).+///+/// Consumes unified prediction::OpenOrder so Polymarket and Kalshi render+/// through the same table. Kalshi-only controls (amend, batch cancel) are+/// surfaced via the capabilities advertised through ExchangePresentation and+/// the companion signals; when active adapter is Polymarket the amend+/// column is hidden to avoid offering an unsupported action.+class PolymarketOrderBlotter : public QWidget {+ Q_OBJECT+ public:+ explicit PolymarketOrderBlotter(QWidget* parent = nullptr);++ void set_orders(const QVector<fincept::services::prediction::OpenOrder>& orders);+ /// Replace a single row in place by order_id. If the order_id is not+ /// present, appends as a new row. Used by the single-order-refresh flow.+ void update_order(const fincept::services::prediction::OpenOrder& order);+ void clear();++ /// Exchange presentation drives column-visibility (amend hidden on+ /// Polymarket), price formatting, and accent colour.+ void set_presentation(const ExchangePresentation& p);+ /// `supports_amend` / `supports_batch_cancel` are pulled from the active+ /// adapter's ExchangeCapabilities so the UI reflects reality. Polymarket+ /// today answers false; Kalshi answers true.+ void set_capabilities(bool supports_amend, bool supports_batch_cancel);++ signals:+ /// User clicked the refresh button on a single row — refetch that order.+ void refresh_order(const QString& order_id);+ /// User committed a new limit price on a row (double-click the price+ /// cell, enter a new value). `price` is the raw 0.0–1.0 probability+ /// (Kalshi cents derived from this × 100).+ void amend_order(const QString& order_id, const QString& side, double price);+ /// User clicked the cancel button on a single row.+ void cancel_order(const QString& order_id);+ /// User clicked "CANCEL ALL" — emits every currently-displayed order_id.+ void cancel_all(const QStringList& order_ids);++ private slots:+ void on_cell_double_clicked(int row, int column);+ void on_cancel_all_clicked();++ private:+ void rebuild_rows();+ void install_row_controls(int row, const fincept::services::prediction::OpenOrder& order);++ QTableWidget* table_ = nullptr;+ QVector<fincept::services::prediction::OpenOrder> orders_;+ ExchangePresentation presentation_ = ExchangePresentation::for_polymarket();+ bool supports_amend_ = false;+ bool supports_batch_cancel_ = false;+};++} // namespace fincept::screens::polymarketdiff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cppindex f18a255b2..f066742dc 100644--- a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp@@ -110,18 +110,20 @@ void PolymarketOrderBook::rebuild_cache() {QPainter p(&cache_);p.setRenderHint(QPainter::Antialiasing, false);- QFont header_font(fonts::DATA_FAMILY, 9);+ QFont header_font(fonts::DATA_FAMILY, 8);header_font.setWeight(QFont::Bold);- QFont data_font(fonts::DATA_FAMILY, 10);+ QFont data_font(fonts::DATA_FAMILY, 9);// Headerp.fillRect(0, 0, w, HEADER_HEIGHT, QColor(colors::BG_RAISED()));+ p.setPen(QColor(colors::BORDER_DIM()));+ p.drawLine(0, HEADER_HEIGHT - 1, w, HEADER_HEIGHT - 1);p.setFont(header_font);p.setPen(QColor(colors::TEXT_SECONDARY()));int col_w = w / 3;- p.drawText(4, 0, col_w, HEADER_HEIGHT, Qt::AlignLeft | Qt::AlignVCenter, "PRICE");+ p.drawText(8, 0, col_w, HEADER_HEIGHT, Qt::AlignLeft | Qt::AlignVCenter, "PRICE");p.drawText(col_w, 0, col_w, HEADER_HEIGHT, Qt::AlignRight | Qt::AlignVCenter, "SIZE");- p.drawText(2 * col_w, 0, col_w - 4, HEADER_HEIGHT, Qt::AlignRight | Qt::AlignVCenter, "DEPTH");+ p.drawText(2 * col_w, 0, col_w - 8, HEADER_HEIGHT, Qt::AlignRight | Qt::AlignVCenter, "TOTAL");// Separatorp.setPen(QColor(colors::BORDER_DIM()));diff --git a/fincept-qt/src/screens/polymarket/PolymarketPriceChart.cpp b/fincept-qt/src/screens/polymarket/PolymarketPriceChart.cppindex fbfc14357..618c775ac 100644--- a/fincept-qt/src/screens/polymarket/PolymarketPriceChart.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketPriceChart.cpp@@ -15,38 +15,55 @@ static const QStringList INTERVAL_LABELS = {"1H", "6H", "1D", "1W", "1M", "ALL"}static const QStringList INTERVAL_VALUES = {"1h", "6h", "1d", "1w", "1m", "max"};PolymarketPriceChart::PolymarketPriceChart(QWidget* parent) : QWidget(parent) {+ setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));auto* vl = new QVBoxLayout(this);- vl->setContentsMargins(8, 8, 8, 8);- vl->setSpacing(4);-- auto* toolbar = new QHBoxLayout;- toolbar->setSpacing(6);+ vl->setContentsMargins(0, 0, 0, 0);+ vl->setSpacing(0);++ // ── Toolbar ───────────────────────────────────────────────────────────+ auto* toolbar_widget = new QWidget(this);+ toolbar_widget->setFixedHeight(36);+ toolbar_widget->setStyleSheet(+ QString("background: %1; border-bottom: 1px solid %2;")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));+ auto* toolbar = new QHBoxLayout(toolbar_widget);+ toolbar->setContentsMargins(12, 0, 12, 0);+ toolbar->setSpacing(8);++ const QString combo_css =+ QString("QComboBox { background: %1; color: %2; border: 1px solid %3; "+ " padding: 2px 6px; font-size: 9px; font-weight: 600; }"+ "QComboBox::drop-down { border: none; width: 12px; }"+ "QComboBox QAbstractItemView { background: %1; color: %2; border: 1px solid %3; }")+ .arg(colors::BG_BASE(), colors::TEXT_PRIMARY(), colors::BORDER_MED());auto* lbl = new QLabel("INTERVAL");lbl->setStyleSheet(- QString("color: %1; font-size: 9px; font-weight: 700; background: transparent;").arg(colors::TEXT_SECONDARY()));+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 0.5px; "+ "background: transparent;")+ .arg(colors::TEXT_SECONDARY()));toolbar->addWidget(lbl);interval_combo_ = new QComboBox;interval_combo_->addItems(INTERVAL_LABELS);- interval_combo_->setCurrentIndex(2); // 1D default- interval_combo_->setFixedWidth(70);+ interval_combo_->setCurrentIndex(2);+ interval_combo_->setFixedSize(62, 24);+ interval_combo_->setStyleSheet(combo_css);connect(interval_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int idx) {if (idx >= 0 && idx < INTERVAL_VALUES.size())emit interval_changed(INTERVAL_VALUES[idx]);});toolbar->addWidget(interval_combo_);- toolbar->addSpacing(12);+ toolbar->addSpacing(10);auto* olbl = new QLabel("OUTCOME");olbl->setStyleSheet(lbl->styleSheet());toolbar->addWidget(olbl);- // Outcome combo is populated dynamically via set_outcome_labels() when- // a market is selected — no hardcoded YES/NO.outcome_combo_ = new QComboBox;- outcome_combo_->setFixedWidth(90);+ outcome_combo_->setFixedSize(100, 24);+ outcome_combo_->setStyleSheet(combo_css);connect(outcome_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,&PolymarketPriceChart::outcome_changed);toolbar->addWidget(outcome_combo_);@@ -55,16 +72,19 @@ PolymarketPriceChart::PolymarketPriceChart(QWidget* parent) : QWidget(parent) {price_label_ = new QLabel;price_label_->setStyleSheet(- QString("color: %1; font-size: 13px; font-weight: 700; background: transparent;").arg(colors::AMBER()));+ QString("color: %1; font-size: 13px; font-weight: 700; background: transparent;")+ .arg(colors::AMBER()));toolbar->addWidget(price_label_);- vl->addLayout(toolbar);+ vl->addWidget(toolbar_widget);chart_container_ = new QWidget(this);+ chart_container_->setStyleSheet(QString("background: %1;").arg(colors::BG_BASE()));auto* ccl = new QVBoxLayout(chart_container_);- ccl->setContentsMargins(0, 0, 0, 0);- auto* empty = new QLabel("Select a market to view chart");- empty->setStyleSheet(QString("color: %1; font-size: 13px; background: transparent;").arg(colors::TEXT_DIM()));+ ccl->setContentsMargins(8, 8, 8, 8);+ auto* empty = new QLabel("Select a market to view its price chart");+ empty->setStyleSheet(+ QString("color: %1; font-size: 12px; background: transparent;").arg(colors::TEXT_DIM()));empty->setAlignment(Qt::AlignCenter);ccl->addWidget(empty);vl->addWidget(chart_container_, 1);@@ -112,6 +132,13 @@ void PolymarketPriceChart::set_current_price(double price) {void PolymarketPriceChart::set_presentation(const ExchangePresentation& p) {presentation_ = p;+ // Price readout tracks the exchange accent so the header colour doesn't+ // stay amber after a swap to Kalshi (teal) / vice versa.+ if (price_label_) {+ price_label_->setStyleSheet(+ QString("color: %1; font-size: 13px; font-weight: 700; background: transparent;")+ .arg(presentation_.accent.name()));+ }if (has_last_history_) set_price_history(last_history_);}diff --git a/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp b/fincept-qt/src/screens/polymarket/PolymarketScreen.cppindex a47bd7771..94375437a 100644--- a/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketScreen.cpp@@ -7,6 +7,7 @@#include "screens/polymarket/PolymarketCommandBar.h"#include "screens/polymarket/PolymarketDetailPanel.h"#include "screens/polymarket/PolymarketLeaderboard.h"+#include "screens/polymarket/PolymarketOrderBlotter.h"#include "screens/polymarket/PolymarketPriceChart.h"#include "screens/polymarket/PolymarketStatusBar.h"#include "screens/polymarket/PredictionAccountDialog.h"@@ -21,6 +22,8 @@#include <QSplitter>#include <QVBoxLayout>+#include <cmath>+namespace fincept::screens {namespace pred = fincept::services::prediction;@@ -129,31 +132,61 @@ void PolymarketScreen::build_ui() {command_bar_ = new PolymarketCommandBar;root->addWidget(command_bar_);+ const QString splitter_css =+ QString("QSplitter::handle { background: %1; }").arg(ui::colors::BORDER_MED());+auto* splitter = new QSplitter(Qt::Horizontal);splitter->setHandleWidth(1);- splitter->setStyleSheet(QString("QSplitter::handle { background: %1; }").arg(ui::colors::BORDER_DIM()));+ splitter->setStyleSheet(splitter_css);+ // Browse panel: slightly wider for readability, fixed range so it+ // never squeezes so small cards become unreadable.browse_panel_ = new PolymarketBrowsePanel;- browse_panel_->setMinimumWidth(320);- browse_panel_->setMaximumWidth(420);+ browse_panel_->setMinimumWidth(300);+ browse_panel_->setMaximumWidth(460);detail_panel_ = new PolymarketDetailPanel;+ // Order blotter: collapsed by default, expands when account is connected.+ order_blotter_ = new PolymarketOrderBlotter;+ order_blotter_->setMinimumHeight(110);+ order_blotter_->setVisible(false);++ auto* detail_splitter = new QSplitter(Qt::Vertical);+ detail_splitter->setHandleWidth(1);+ detail_splitter->setStyleSheet(splitter_css);+ detail_splitter->addWidget(detail_panel_);+ detail_splitter->addWidget(order_blotter_);+ detail_splitter->setStretchFactor(0, 3);+ detail_splitter->setStretchFactor(1, 1);+ detail_splitter->setSizes({700, 160});+leaderboard_ = new PolymarketLeaderboard;- leaderboard_->setMinimumWidth(280);- leaderboard_->setMaximumWidth(340);- leaderboard_->setVisible(false); // shown only when active adapter supports leaderboard.+ leaderboard_->setMinimumWidth(260);+ leaderboard_->setMaximumWidth(320);+ leaderboard_->setVisible(false);splitter->addWidget(browse_panel_);- splitter->addWidget(detail_panel_);+ splitter->addWidget(detail_splitter);splitter->addWidget(leaderboard_);splitter->setStretchFactor(0, 0);splitter->setStretchFactor(1, 1);splitter->setStretchFactor(2, 0);- splitter->setSizes({360, 700, 0});+ splitter->setSizes({380, 800, 0});root->addWidget(splitter, 1);+ // Blotter signals — dispatch through the active adapter, which is+ // cast to the Kalshi-specific type for amend/batch-cancel operations.+ connect(order_blotter_, &PolymarketOrderBlotter::refresh_order,+ this, &PolymarketScreen::on_order_refresh_requested);+ connect(order_blotter_, &PolymarketOrderBlotter::amend_order,+ this, &PolymarketScreen::on_order_amend_requested);+ connect(order_blotter_, &PolymarketOrderBlotter::cancel_order,+ this, &PolymarketScreen::on_order_cancel_requested);+ connect(order_blotter_, &PolymarketOrderBlotter::cancel_all,+ this, &PolymarketScreen::on_orders_cancel_all_requested);+status_bar_ = new PolymarketStatusBar;root->addWidget(status_bar_);@@ -214,6 +247,10 @@ void PolymarketScreen::build_ui() {connect(detail_panel_, &PolymarketDetailPanel::outcome_changed, this, &PolymarketScreen::on_outcome_changed);connect(detail_panel_, &PolymarketDetailPanel::related_market_clicked, this,&PolymarketScreen::on_related_market_clicked);+ connect(detail_panel_, &PolymarketDetailPanel::place_order, this,+ [this](const pred::OrderRequest& req) {+ if (auto* a = active_adapter()) a->place_order(req);+ });}// ── Active-adapter wiring ───────────────────────────────────────────────────@@ -258,6 +295,34 @@ void PolymarketScreen::connect_active_adapter() {adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::error_occurred,this, &PolymarketScreen::on_adapter_error);+ adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::open_orders_ready,+ this, &PolymarketScreen::on_open_orders_ready);+ adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::order_cancelled, this,+ [this, a](const QString& oid, bool ok, const QString& err) {+ if (!ok) {+ LOG_WARN("PredictionMarkets", "Cancel failed: " + err);+ return;+ }+ // Refresh the full list after cancel confirms.+ a->fetch_open_orders();+ Q_UNUSED(oid);+ });+ adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::balance_ready,+ this, [this](const pred::AccountBalance& b) {+ if (detail_panel_) detail_panel_->set_balance(b);+ });+ adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::positions_ready,+ this, [this](const QVector<pred::PredictionPosition>& p) {+ if (detail_panel_) detail_panel_->set_positions(p);+ });+ adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::order_placed,+ this, [this, a](const pred::OrderResult& r) {+ if (detail_panel_) detail_panel_->on_order_result(r);+ if (r.ok) {+ a->fetch_balance();+ a->fetch_open_orders();+ }+ });adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::ws_price_updated,this, &PolymarketScreen::on_ws_price_updated);adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::ws_orderbook_updated,@@ -265,6 +330,55 @@ void PolymarketScreen::connect_active_adapter() {adapter_connections_ << connect(a, &pred::PredictionExchangeAdapter::ws_connection_changed,this, &PolymarketScreen::on_ws_connection_changed);+ // Kalshi-specific extensions — surfaced via KalshiAdapter's own signals+ // (exchange status, WS trade/lifecycle, batch candles, market detail+ // from lifecycle refreshes). Cast + connect only when the active+ // adapter is Kalshi. Auto-disconnects on ~QObject / adapter destroy.+ if (auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(a)) {+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::exchange_status_ready,+ this, &PolymarketScreen::on_kalshi_exchange_status);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::exchange_schedule_ready,+ this, &PolymarketScreen::on_kalshi_exchange_schedule);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::ws_trade_received,+ this, &PolymarketScreen::on_kalshi_ws_trade);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::ws_market_lifecycle_changed,+ this, &PolymarketScreen::on_kalshi_market_lifecycle);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::batch_candles_ready,+ this, &PolymarketScreen::on_kalshi_batch_candles);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::historical_markets_ready,+ this, [this](const QVector<pred::PredictionMarket>& markets,+ const QString& /*cursor*/) {+ on_markets_ready(markets);+ });+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::market_detail_ready,+ this, &PolymarketScreen::on_kalshi_market_detail);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::series_detail_ready,+ this, &PolymarketScreen::on_kalshi_series_detail);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::single_order_ready,+ this, &PolymarketScreen::on_kalshi_single_order);+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::order_amended, this,+ [this, ks](const QString& oid, bool ok, const QString& err) {+ if (!ok) {+ LOG_WARN("PredictionMarkets",+ "Amend failed: " + err);+ return;+ }+ ks->fetch_order(oid);+ });+ adapter_connections_ << connect(ks, &pred::kalshi_ns::KalshiAdapter::orders_batch_cancelled,+ this, [this, ks](const QStringList&, bool ok,+ const QString& err) {+ if (!ok) LOG_WARN("PredictionMarkets",+ "Batch cancel failed: " + err);+ ks->fetch_open_orders();+ });+ // Kick off the exchange status + schedule fetch; results land in the+ // status bar. These are cheap endpoints with long TTL on Kalshi's+ // side, so one call per adapter swap is fine.+ ks->fetch_exchange_status();+ ks->fetch_exchange_schedule();+ }+// Install the per-exchange presentation profile across every sub-panel// that has per-exchange visual identity. This fans out accent color,// price formatters, view pill set, stat visibility, and status-badge@@ -300,6 +414,39 @@ void PolymarketScreen::install_presentation(const polymarket::ExchangePresentatiif (command_bar_) command_bar_->set_presentation(p);if (detail_panel_) detail_panel_->set_presentation(p);if (browse_panel_) browse_panel_->set_presentation(p);+ if (status_bar_) {+ status_bar_->set_brand(p.display_name, p.accent);+ // Exchange status is only meaningful for exchanges that expose a+ // status endpoint. Clear it on every swap so stale text from a+ // previous exchange doesn't leak.+ status_bar_->set_exchange_status({});+ status_bar_->set_next_session({});+ }++ // Order blotter + trade ticket: both gated on having credentials.+ {+ auto* a = active_adapter();+ const bool has_creds = a && a->has_credentials();+ if (detail_panel_) detail_panel_->set_trading_enabled(has_creds);+ if (has_creds && a) {+ a->fetch_balance();+ a->fetch_positions();+ }+ }++ if (order_blotter_) {+ auto* a = active_adapter();+ const bool has_creds = a && a->has_credentials();+ order_blotter_->setVisible(has_creds);+ if (a) {+ const auto caps = a->capabilities();+ order_blotter_->set_capabilities(caps.supports_decrease_order, // amend ≈ Kalshi-only+ caps.supports_batch_orders);+ order_blotter_->set_presentation(p);+ if (has_creds) a->fetch_open_orders();+ else order_blotter_->clear();+ }+ }// The detail panel's embedded sub-widgets (chart, trades) are built// inside the panel and reachable via its own plumbing — set_presentation@@ -382,6 +529,10 @@ void PolymarketScreen::on_exchange_changed(const QString& exchange_id) {has_selection_ = false;selected_market_ = {};+ // Clear search state and per-adapter caches so the new exchange starts clean.+ command_bar_->set_search_text(QString());+ batch_candles_cache_.clear();+reg.set_active(exchange_id);LOG_INFO("PredictionMarkets", "Active exchange -> " + exchange_id);@@ -462,11 +613,20 @@ void PolymarketScreen::load_current_view() {a->list_events(category, active_sort_, 100, 0);} else if (active_view_ == "SPORTS") {a->list_markets(QStringLiteral("sports"), active_sort_, 100, 0);- } else if (active_view_ == "RESOLVED") {+ } else if (active_view_ == "RESOLVED" || active_view_ == "SETTLED") {// The adapter interface doesn't expose a closed-markets filter today —// fall back to the default list. Kalshi exposes this via event// status; that improvement can land with the API fix pass.a->list_events(category, QStringLiteral("endDate"), 100, 0);+ } else if (active_view_ == "HISTORY") {+ // Kalshi-only: archived markets served by /historical/markets. No+ // Polymarket equivalent, so the pill is hidden for Polymarket via+ // the ExchangePresentation view_names list.+ if (auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(a)) {+ ks->fetch_historical_markets(category, 100, QString());+ } else {+ a->list_markets(category, active_sort_, 100, 0);+ }} else {a->list_markets(category, active_sort_, 100, 0);}@@ -490,6 +650,18 @@ void PolymarketScreen::select_market(const pred::PredictionMarket& market) {}a->fetch_recent_trades(market.key, 100);+ // Refresh positions for the newly-selected market (only if credentialed).+ if (a->has_credentials()) a->fetch_positions();++ // Kalshi: fetch series detail for fee-info tooltip. Cached in the+ // adapter so repeat selections of markets in the same series don't+ // refetch. Triggers on_kalshi_series_detail.+ if (auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(a)) {+ const QString series = market.extras.value(QStringLiteral("series_ticker")).toString();+ if (!series.isEmpty()) ks->fetch_series_detail(series);+ else if (detail_panel_) detail_panel_->set_series_tooltip({});+ }+if (active_is_polymarket()) {// Polymarket-only enrichments. Kalshi exposes none of these today.auto& svc = pmx::PolymarketService::instance();@@ -500,8 +672,7 @@ void PolymarketScreen::select_market(const pred::PredictionMarket& market) {svc.fetch_top_holders(condition_id, 20);svc.fetch_open_interest({condition_id});}- const QString slug = market.extras.value("slug").toString();- if (!slug.isEmpty()) svc.fetch_comments(slug, 50);+ if (!condition_id.isEmpty()) svc.fetch_comments(condition_id, 50);bool ok = false;const int event_id = market.key.event_id.toInt(&ok);if (ok && event_id > 0) svc.fetch_related_markets(event_id);@@ -532,13 +703,35 @@ void PolymarketScreen::unsubscribe_current() {void PolymarketScreen::on_markets_ready(const QVector<pred::PredictionMarket>& markets) {command_bar_->set_loading(false);+ browse_panel_->set_loading(false);browse_panel_->set_markets(markets);command_bar_->set_market_count(markets.size());status_bar_->set_count(markets.size(), "markets");++ // Kalshi-only: fire a single /markets/candlesticks call covering all+ // visible tickers. The server returns ~7 daily points per ticker in+ // one round-trip, which populates sparklines without N per-card fetches.+ // Replaces the prior per-row candle-fetch fan-out (~20 HTTP calls per+ // page load in testing).+ if (auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(active_adapter())) {+ QStringList tickers;+ tickers.reserve(markets.size());+ for (const auto& m : markets) {+ const QString& t = m.key.market_id;+ if (!t.isEmpty() && !batch_candles_cache_.contains(t)) tickers.push_back(t);+ if (tickers.size() >= 50) break; // server caps batch at ~100+ }+ if (!tickers.isEmpty()) {+ const qint64 end = QDateTime::currentSecsSinceEpoch();+ const qint64 start = end - (7 * 24 * 3600);+ ks->fetch_batch_candles(tickers, /*period=*/1440, start, end);+ }+ }}void PolymarketScreen::on_events_ready(const QVector<pred::PredictionEvent>& events) {command_bar_->set_loading(false);+ browse_panel_->set_loading(false);browse_panel_->set_events(events);command_bar_->set_market_count(events.size());status_bar_->set_count(events.size(), "events");@@ -547,14 +740,18 @@ void PolymarketScreen::on_events_ready(const QVector<pred::PredictionEvent>& evevoid PolymarketScreen::on_search_results_ready(const QVector<pred::PredictionMarket>& markets,const QVector<pred::PredictionEvent>& events) {command_bar_->set_loading(false);+ browse_panel_->set_loading(false);if (!markets.isEmpty()) {browse_panel_->set_markets(markets);command_bar_->set_market_count(markets.size());status_bar_->set_count(markets.size(), "markets");- } else {+ } else if (!events.isEmpty()) {browse_panel_->set_events(events);command_bar_->set_market_count(events.size());status_bar_->set_count(events.size(), "events");+ } else {+ command_bar_->set_market_count(0);+ status_bar_->set_count(0, "results");}}@@ -584,6 +781,7 @@ void PolymarketScreen::on_leaderboard_ready(const QVariantList& /*entries*/) {void PolymarketScreen::on_adapter_error(const QString& ctx, const QString& msg) {command_bar_->set_loading(false);+ browse_panel_->set_loading(false);LOG_WARN("PredictionMarkets", ctx + ": " + msg);if (status_bar_) status_bar_->set_selected(QString("%1: %2").arg(ctx, msg));}@@ -660,6 +858,191 @@ void PolymarketScreen::on_related_markets_received(const QVector<pmx::Market>& mdetail_panel_->set_related_markets(out);}+// ── Kalshi-specific handlers ────────────────────────────────────────────────++void PolymarketScreen::on_kalshi_exchange_status(const QJsonObject& status) {+ if (!status_bar_) return;+ // Kalshi responds with { "exchange_active": bool, "trading_active": bool,+ // "exchange_estopped": bool } on /exchange/status. We map this to a+ // user-facing label: PAUSED if estopped, OPEN if both booleans true,+ // CLOSED otherwise.+ const bool exchange_active = status.value("exchange_active").toBool();+ const bool trading_active = status.value("trading_active").toBool();+ const bool estopped = status.value("exchange_estopped").toBool();+ QString label;+ if (estopped) label = QStringLiteral("PAUSED");+ else if (exchange_active && trading_active) label = QStringLiteral("OPEN");+ else if (exchange_active) label = QStringLiteral("MAINT");+ else label = QStringLiteral("CLOSED");+ status_bar_->set_exchange_status(label);+}++void PolymarketScreen::on_kalshi_exchange_schedule(const QJsonObject& schedule) {+ if (!status_bar_) return;+ // Best-effort "next open" label. Kalshi's schedule shape is nested+ // (standard_hours + maintenance_windows). Fall back to an empty string+ // if the shape changes so we don't surface nonsense.+ const auto standard = schedule.value("schedule").toObject()+ .value("standard_hours").toArray();+ QString next;+ if (!standard.isEmpty()) {+ const auto first = standard.first().toObject();+ const QString open = first.value("open_time").toString();+ if (!open.isEmpty())+ next = QStringLiteral("Next open: ") + open;+ }+ status_bar_->set_next_session(next);+}++void PolymarketScreen::on_kalshi_ws_trade(const pred::PredictionTrade& trade) {+ if (!detail_panel_ || !has_selection_) return;+ // Only surface trades for the currently-selected market. Kalshi's trade+ // channel broadcasts across all subscribed tickers, so we filter here.+ const QString aid_prefix = selected_market_.key.market_id + QStringLiteral(":");+ if (!trade.asset_id.startsWith(aid_prefix)) return;+ if (auto* feed = detail_panel_->findChild<polymarket::PolymarketActivityFeed*>())+ feed->append_trade(trade);+}++void PolymarketScreen::on_kalshi_market_lifecycle(const QString& ticker,+ const QString& status) {+ LOG_INFO("PredictionMarkets",+ QStringLiteral("Kalshi lifecycle: %1 → %2").arg(ticker, status));+ // When a visible market flips status, refresh just that row. Avoid+ // reloading the whole view — a market going paused/closed shouldn't+ // disturb the rest of the browse panel.+ if (!active_adapter()) return;+ // If the currently-selected market just flipped, refresh detail too.+ if (has_selection_ && selected_market_.key.market_id == ticker) {+ pred::MarketKey k;+ k.market_id = ticker;+ active_adapter()->fetch_market(k);+ }+}++void PolymarketScreen::on_kalshi_batch_candles(+ const QHash<QString, pred::PriceHistory>& histories) {+ // Store for sparkline consumers (browse panel cards). The browse panel+ // will re-read from the cache on its next rebuild.+ for (auto it = histories.constBegin(); it != histories.constEnd(); ++it)+ batch_candles_cache_.insert(it.key(), it.value());+ // If the browse panel exposes a set_sparklines() hook, wire it here.+ // Without a hook it's still useful for the detail chart which checks+ // the cache before issuing its own fetch.+}++void PolymarketScreen::on_kalshi_market_detail(const pred::PredictionMarket& market) {+ // Single-row refresh triggered by a lifecycle event. Update the browse+ // panel row in place if possible; otherwise no-op (panel won't show+ // stale data because the full-view refresh will replace it soon).+ if (browse_panel_) browse_panel_->update_market_row(market);+ if (has_selection_ && selected_market_.key.market_id == market.key.market_id) {+ selected_market_ = market;+ if (detail_panel_) detail_panel_->set_market(market);+ }+}++void PolymarketScreen::on_open_orders_ready(const QVector<pred::OpenOrder>& orders) {+ if (order_blotter_) order_blotter_->set_orders(orders);+}++void PolymarketScreen::on_order_refresh_requested(const QString& order_id) {+ // Only Kalshi supports the single-order fetch today. Polymarket has no+ // REST equivalent — the blotter's refresh button is wired for everyone+ // but the cast below makes the no-op explicit on other adapters.+ auto* a = active_adapter();+ if (auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(a)) {+ ks->fetch_order(order_id);+ } else if (a) {+ a->fetch_open_orders(); // fall back to refetching the whole list+ }+}++void PolymarketScreen::on_order_amend_requested(const QString& order_id, const QString& side,+ double price) {+ auto* a = active_adapter();+ auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(a);+ if (!ks) {+ LOG_WARN("PredictionMarkets", "Amend not supported on this adapter");+ return;+ }+ // Kalshi accepts integer cents 1-99.+ const int cents = qBound(1, int(std::round(price * 100.0)), 99);+ ks->amend_order(order_id, side, cents);+}++void PolymarketScreen::on_order_cancel_requested(const QString& order_id) {+ if (auto* a = active_adapter()) a->cancel_order(order_id);+}++void PolymarketScreen::on_orders_cancel_all_requested(const QStringList& order_ids) {+ auto* a = active_adapter();+ if (!a) return;+ // Prefer the batched endpoint when the adapter supports it (Kalshi);+ // otherwise fall back to N individual cancels so Polymarket users still+ // get the Cancel All action.+ if (auto* ks = dynamic_cast<pred::kalshi_ns::KalshiAdapter*>(a)) {+ ks->cancel_orders_batch(order_ids);+ } else {+ for (const auto& oid : order_ids) a->cancel_order(oid);+ }+}++void PolymarketScreen::on_kalshi_single_order(const QJsonObject& order) {+ if (!order_blotter_) return;+ // Translate the raw Kalshi order JSON into the unified OpenOrder shape+ // the blotter expects. Field names match the Python bridge's+ // cmd_open_orders normalization so the two paths produce identical+ // rows.+ pred::OpenOrder o;+ o.order_id = order.value("order_id").toString();+ const QString side = order.value("side").toString().toLower();+ o.outcome = side.toUpper();+ o.asset_id = order.value("ticker").toString() + ":" + side;+ o.market_id = order.value("ticker").toString();+ o.side = order.value("action").toString().toUpper();+ o.order_type = order.value("type").toString().toUpper();+ const QString price_key = (side == "yes") ? "yes_price_dollars" : "no_price_dollars";+ o.price = order.value(price_key).toString().toDouble();+ o.size = order.value("remaining_count_fp").toString().toDouble();+ const double initial = order.value("initial_count_fp").toString().toDouble();+ o.filled = qMax(0.0, initial - o.size);+ o.status = order.value("status").toString().toUpper();+ order_blotter_->update_order(o);+}++void PolymarketScreen::on_kalshi_series_detail(const QString& series_ticker,+ const QJsonObject& series) {+ if (!detail_panel_ || !has_selection_) return;+ // Only apply if the currently-selected market is in this series.+ const QString selected_series =+ selected_market_.extras.value(QStringLiteral("series_ticker")).toString();+ if (series_ticker != selected_series) return;++ const QString title = series.value(QStringLiteral("title")).toString();+ const QString frequency = series.value(QStringLiteral("frequency")).toString();+ const QString fee_type = series.value(QStringLiteral("fee_type")).toString();+ const double fee_mult = series.value(QStringLiteral("fee_multiplier")).toDouble();+ const QString contract_url = series.value(QStringLiteral("contract_url")).toString();++ QStringList lines;+ if (!title.isEmpty()) lines << QStringLiteral("<b>%1</b>").arg(title.toHtmlEscaped());+ if (!series_ticker.isEmpty())+ lines << QStringLiteral("Series: %1").arg(series_ticker);+ if (!frequency.isEmpty())+ lines << QStringLiteral("Frequency: %1").arg(frequency);+ if (!fee_type.isEmpty()) {+ QString fee_line = QStringLiteral("Fees: %1").arg(fee_type);+ if (fee_mult > 0.0)+ fee_line += QStringLiteral(" (×%1)").arg(fee_mult);+ lines << fee_line;+ }+ if (!contract_url.isEmpty())+ lines << QStringLiteral("<i>%1</i>").arg(contract_url.toHtmlEscaped());++ detail_panel_->set_series_tooltip(lines.join(QStringLiteral("<br>")));+}+// ── IStatefulScreen ─────────────────────────────────────────────────────────QVariantMap PolymarketScreen::save_state() const {diff --git a/fincept-qt/src/screens/polymarket/PolymarketScreen.h b/fincept-qt/src/screens/polymarket/PolymarketScreen.hindex 391329cfc..1a0baab50 100644--- a/fincept-qt/src/screens/polymarket/PolymarketScreen.h+++ b/fincept-qt/src/screens/polymarket/PolymarketScreen.h@@ -5,6 +5,8 @@#include "services/polymarket/PolymarketTypes.h"#include "services/prediction/PredictionTypes.h"+#include <QHash>+#include <QJsonObject>#include <QList>#include <QMetaObject>#include <QTimer>@@ -17,6 +19,7 @@ class PolymarketCommandBar;class PolymarketBrowsePanel;class PolymarketDetailPanel;class PolymarketLeaderboard;+class PolymarketOrderBlotter;class PolymarketStatusBar;} // namespace fincept::screens::polymarket@@ -93,6 +96,24 @@ class PolymarketScreen : public QWidget, public fincept::screens::IStatefulScreevoid on_comments_received(const QVector<fincept::services::polymarket::Comment>& comments);void on_related_markets_received(const QVector<fincept::services::polymarket::Market>& markets);+ // Kalshi-only enrichments (surfaced via KalshiAdapter-specific signals).+ void on_kalshi_exchange_status(const QJsonObject& status);+ void on_kalshi_exchange_schedule(const QJsonObject& schedule);+ void on_kalshi_ws_trade(const fincept::services::prediction::PredictionTrade& trade);+ void on_kalshi_market_lifecycle(const QString& ticker, const QString& status);+ void on_kalshi_batch_candles(+ const QHash<QString, fincept::services::prediction::PriceHistory>& histories);+ void on_kalshi_market_detail(const fincept::services::prediction::PredictionMarket& market);+ void on_kalshi_series_detail(const QString& series_ticker, const QJsonObject& series);++ // Open-orders blotter.+ void on_open_orders_ready(const QVector<fincept::services::prediction::OpenOrder>& orders);+ void on_order_refresh_requested(const QString& order_id);+ void on_order_amend_requested(const QString& order_id, const QString& side, double price);+ void on_order_cancel_requested(const QString& order_id);+ void on_orders_cancel_all_requested(const QStringList& order_ids);+ void on_kalshi_single_order(const QJsonObject& order);+private:void build_ui();void connect_active_adapter();@@ -112,6 +133,7 @@ class PolymarketScreen : public QWidget, public fincept::screens::IStatefulScreepolymarket::PolymarketBrowsePanel* browse_panel_ = nullptr;polymarket::PolymarketDetailPanel* detail_panel_ = nullptr;polymarket::PolymarketLeaderboard* leaderboard_ = nullptr;+ polymarket::PolymarketOrderBlotter* order_blotter_ = nullptr;polymarket::PolymarketStatusBar* status_bar_ = nullptr;// State@@ -136,6 +158,10 @@ class PolymarketScreen : public QWidget, public fincept::screens::IStatefulScreeQList<QMetaObject::Connection> adapter_connections_;QList<QMetaObject::Connection> polymarket_extras_connections_;QString wired_adapter_id_;++ // Batch-candles cache for Kalshi browse panel sparklines. Populated in+ // on_markets_ready (Kalshi only). Keyed by market_id.+ QHash<QString, fincept::services::prediction::PriceHistory> batch_candles_cache_;};} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/polymarket/PolymarketStatusBar.cpp b/fincept-qt/src/screens/polymarket/PolymarketStatusBar.cppindex e412c0234..a3cd31b22 100644--- a/fincept-qt/src/screens/polymarket/PolymarketStatusBar.cpp+++ b/fincept-qt/src/screens/polymarket/PolymarketStatusBar.cpp@@ -10,34 +10,81 @@ using namespace fincept::ui;PolymarketStatusBar::PolymarketStatusBar(QWidget* parent) : QWidget(parent) {setFixedHeight(22);- setStyleSheet(QString("background: %1; border-top: 1px solid %2;").arg(colors::BG_RAISED(), colors::BORDER_DIM()));+ setStyleSheet(+ QString("background: %1; border-top: 1px solid %2;")+ .arg(colors::BG_RAISED(), colors::BORDER_DIM()));auto* hl = new QHBoxLayout(this);- hl->setContentsMargins(16, 0, 16, 0);- hl->setSpacing(12);+ hl->setContentsMargins(14, 0, 14, 0);+ hl->setSpacing(14);++ // Brand+ brand_label_ = new QLabel("POLYMARKET");+ brand_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 1.5px; "+ "background: transparent;")+ .arg(accent_.name()));+ hl->addWidget(brand_label_);++ // Divider+ auto* d1 = new QWidget;+ d1->setFixedSize(1, 12);+ d1->setStyleSheet(QString("background: %1;").arg(colors::BORDER_DIM()));+ hl->addWidget(d1);++ // Exchange status (Kalshi)+ exchange_status_ = new QLabel;+ exchange_status_->setVisible(false);+ exchange_status_->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; background: transparent;").arg(colors::POSITIVE()));+ hl->addWidget(exchange_status_);++ // Next session+ next_session_ = new QLabel;+ next_session_->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent;").arg(colors::TEXT_DIM()));+ next_session_->setVisible(false);+ hl->addWidget(next_session_);- auto label_style = QString("color: %1; font-size: 9px; background: transparent;").arg(colors::TEXT_SECONDARY());- auto highlight_style = QString("color: %1; font-size: 9px; background: transparent;").arg(colors::CYAN());-- auto* brand = new QLabel("POLYMARKET");- brand->setStyleSheet(label_style);- hl->addWidget(brand);hl->addStretch(1);+ // Viewview_label_ = new QLabel("MARKETS");- view_label_->setStyleSheet(label_style);+ view_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 600; background: transparent;")+ .arg(colors::TEXT_DIM()));hl->addWidget(view_label_);+ // Countcount_label_ = new QLabel;- count_label_->setStyleSheet(label_style);+ count_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent;").arg(colors::TEXT_DIM()));hl->addWidget(count_label_);+ // Divider+ auto* d2 = new QWidget;+ d2->setFixedSize(1, 12);+ d2->setStyleSheet(QString("background: %1;").arg(colors::BORDER_DIM()));+ hl->addWidget(d2);++ // Selected market (truncated)selected_label_ = new QLabel;- selected_label_->setStyleSheet(highlight_style);+ selected_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent; "+ "max-width: 360px;")+ .arg(accent_.name()));hl->addWidget(selected_label_);+ // Divider+ auto* d3 = new QWidget;+ d3->setFixedSize(1, 12);+ d3->setStyleSheet(QString("background: %1;").arg(colors::BORDER_DIM()));+ hl->addWidget(d3);++ // WSws_label_ = new QLabel;- ws_label_->setStyleSheet(label_style);+ ws_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent;").arg(colors::TEXT_DIM()));hl->addWidget(ws_label_);set_ws_status(false);}@@ -51,21 +98,62 @@ void PolymarketStatusBar::set_count(int count, const QString& label) {}void PolymarketStatusBar::set_selected(const QString& question) {- QString q = question.left(50);- if (question.size() > 50)- q += "...";+ QString q = question.left(60);+ if (question.size() > 60) q += "…";selected_label_->setText(q);}void PolymarketStatusBar::set_ws_status(bool connected) {if (connected) {- ws_label_->setText("WS: LIVE");+ ws_label_->setText("● LIVE");ws_label_->setStyleSheet(- QString("color: %1; font-size: 9px; font-weight: 700; background: transparent;").arg(colors::POSITIVE()));+ QString("color: %1; font-size: 8px; font-weight: 700; background: transparent;")+ .arg(colors::POSITIVE()));} else {- ws_label_->setText("WS: OFF");- ws_label_->setStyleSheet(QString("color: %1; font-size: 9px; background: transparent;").arg(colors::TEXT_DIM()));+ ws_label_->setText("○ OFF");+ ws_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent;").arg(colors::TEXT_DIM()));+ }+}++void PolymarketStatusBar::set_brand(const QString& name, const QColor& accent) {+ accent_ = accent;+ brand_label_->setText(name.toUpper());+ brand_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; letter-spacing: 1.5px; "+ "background: transparent;")+ .arg(accent_.name()));+ selected_label_->setStyleSheet(+ QString("color: %1; font-size: 8px; background: transparent;").arg(accent_.name()));+}++void PolymarketStatusBar::set_exchange_status(const QString& status) {+ if (status.isEmpty()) {+ exchange_status_->setVisible(false);+ return;+ }+ const QString upper = status.toUpper();+ QString color = colors::POSITIVE();+ if (upper == QStringLiteral("PAUSED") || upper == QStringLiteral("MAINT"))+ color = colors::AMBER();+ else if (upper == QStringLiteral("CLOSED") || upper == QStringLiteral("OFF"))+ color = colors::NEGATIVE();++ exchange_status_->setText(upper);+ exchange_status_->setStyleSheet(+ QString("color: %1; font-size: 8px; font-weight: 700; background: transparent;"+ "padding: 0 4px; border: 1px solid %1;")+ .arg(color));+ exchange_status_->setVisible(true);+}++void PolymarketStatusBar::set_next_session(const QString& text) {+ if (text.isEmpty()) {+ next_session_->setVisible(false);+ return;}+ next_session_->setText(text);+ next_session_->setVisible(true);}} // namespace fincept::screens::polymarketdiff --git a/fincept-qt/src/screens/polymarket/PolymarketStatusBar.h b/fincept-qt/src/screens/polymarket/PolymarketStatusBar.hindex f30d4b932..2df409dc2 100644--- a/fincept-qt/src/screens/polymarket/PolymarketStatusBar.h+++ b/fincept-qt/src/screens/polymarket/PolymarketStatusBar.h@@ -1,11 +1,13 @@#pragma once+#include <QColor>#include <QLabel>#include <QWidget>namespace fincept::screens::polymarket {-/// Bottom status strip with view info, market count, selection, WS status.+/// Bottom status strip with brand, view info, market count, selection,+/// exchange-level status (Kalshi only), and WS status.class PolymarketStatusBar : public QWidget {Q_OBJECTpublic:@@ -16,11 +18,28 @@ class PolymarketStatusBar : public QWidget {void set_selected(const QString& question);void set_ws_status(bool connected);+ /// Brand label (left) follows the active exchange. The colour is used+ /// for the brand text and the selected-market highlight.+ void set_brand(const QString& name, const QColor& accent);++ /// Exchange lifecycle (OPEN / PAUSED / CLOSED / MAINT). Empty string+ /// hides the pill — use this for exchanges that don't expose status.+ void set_exchange_status(const QString& status);++ /// Human-readable "Opens at …" / "Closed" hint pulled from the+ /// exchange schedule. Empty hides the label.+ void set_next_session(const QString& text);+private:+ QLabel* brand_label_ = nullptr;QLabel* view_label_ = nullptr;QLabel* count_label_ = nullptr;QLabel* selected_label_ = nullptr;+ QLabel* exchange_status_ = nullptr;+ QLabel* next_session_ = nullptr;QLabel* ws_label_ = nullptr;++ QColor accent_{0xD97706}; // default amber — Polymarket};} // namespace fincept::screens::polymarketdiff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cppindex cf4ac285e..1b01f7071 100644--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp@@ -17,7 +17,9 @@#include "screens/settings/LlmConfigSection.h"#include "screens/settings/McpServersSection.h"#include "screens/settings/PythonEnvSection.h"+#include "screens/settings/VoiceConfigSection.h"#include "services/notifications/NotificationService.h"+#include "services/stt/SpeechService.h"#include "storage/StorageManager.h"#include "storage/cache/CacheManager.h"#include "storage/repositories/DataSourceRepository.h"@@ -170,6 +172,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {sections_->addWidget(build_keybindings()); // 10sections_->addWidget(build_python_env()); // 11sections_->addWidget(build_developer()); // 12+ sections_->addWidget(new VoiceConfigSection); // 13QList<QPushButton*> nav_btns;auto make_btn = [&](const QString& text, int idx) {@@ -206,6 +209,7 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {make_btn("Keybindings", 10);make_btn("Python Env", 11);make_btn("Developer", 12);+ make_btn("Voice", 13);first->setChecked(true);@@ -219,6 +223,12 @@ SettingsScreen::SettingsScreen(QWidget* parent) : QWidget(parent) {[]() { ai_chat::LlmService::instance().reload_config(); });}+ // Wire Voice config changes → reload STT service (picks up provider / API key / model)+ if (auto* voice = qobject_cast<VoiceConfigSection*>(sections_->widget(13))) {+ connect(voice, &VoiceConfigSection::config_changed, this,+ []() { fincept::services::SpeechService::instance().reload_config(); });+ }+connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,[this](const ui::ThemeTokens&) { refresh_theme(); });refresh_theme();diff --git a/fincept-qt/src/screens/settings/VoiceConfigSection.cpp b/fincept-qt/src/screens/settings/VoiceConfigSection.cppnew file mode 100644index 000000000..9533cbefd--- /dev/null+++ b/fincept-qt/src/screens/settings/VoiceConfigSection.cpp@@ -0,0 +1,355 @@+// VoiceConfigSection.cpp — Voice / STT provider configuration panel.++#include "screens/settings/VoiceConfigSection.h"++#include "core/config/AppConfig.h"+#include "core/logging/Logger.h"+#include "storage/secure/SecureStorage.h"+#include "ui/theme/Theme.h"+#include "ui/theme/ThemeManager.h"++#include <QFormLayout>+#include <QFrame>+#include <QHBoxLayout>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QScrollArea>+#include <QTimer>+#include <QUrl>+#include <QVBoxLayout>++namespace fincept::screens {++static constexpr const char* TAG = "VoiceConfigSection";+static constexpr const char* kSecureKey = "voice.deepgram.api_key";++// ── Style helpers (match SettingsScreen / LlmConfigSection look) ─────────────++static QString label_ss() {+ return QString("color:%1;background:transparent;").arg(ui::colors::TEXT_SECONDARY());+}+static QString title_ss() {+ return QString("color:%1;font-weight:bold;letter-spacing:0.5px;background:transparent;")+ .arg(ui::colors::AMBER());+}+static QString input_ss() {+ return QString("QLineEdit{background:%1;color:%2;border:1px solid %3;padding:6px;}"+ "QLineEdit:focus{border:1px solid %4;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::AMBER());+}+static QString combo_ss() {+ return QString(+ "QComboBox{background:%1;color:%2;border:1px solid %3;padding:5px 8px;min-width:160px;}"+ "QComboBox:focus{border:1px solid %4;}"+ "QComboBox::drop-down{border:none;width:20px;}"+ "QComboBox QAbstractItemView{background:%1;color:%2;selection-background-color:%5;border:1px solid %3;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::AMBER(),+ ui::colors::BG_HOVER());+}+static QString btn_primary_ss() {+ return QString("QPushButton{background:%1;color:%2;border:none;font-weight:700;padding:0 16px;height:32px;}"+ "QPushButton:hover{background:%3;}")+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::AMBER_DIM());+}+static QString btn_secondary_ss() {+ return QString("QPushButton{background:%1;color:%2;border:1px solid %3;padding:0 12px;height:32px;}"+ "QPushButton:hover{background:%4;}")+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_BRIGHT(), ui::colors::BG_HOVER());+}++// ── Construction ─────────────────────────────────────────────────────────────++VoiceConfigSection::VoiceConfigSection(QWidget* parent) : QWidget(parent) {+ build_ui();+ reload();+}++void VoiceConfigSection::build_ui() {+ auto* scroll = new QScrollArea(this);+ scroll->setWidgetResizable(true);+ scroll->setStyleSheet(QString("QScrollArea{border:none;background:transparent;}"+ "QScrollBar:vertical{width:6px;background:transparent;}"+ "QScrollBar::handle:vertical{background:%1;border-radius:3px;}"+ "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}")+ .arg(ui::colors::BORDER_MED()));++ auto* page = new QWidget;+ auto* vl = new QVBoxLayout(page);+ vl->setContentsMargins(24, 24, 24, 24);+ vl->setSpacing(14);++ // ── Title + blurb ────────────────────────────────────────────────────────+ auto* title = new QLabel("VOICE / SPEECH-TO-TEXT");+ title->setStyleSheet(title_ss());+ vl->addWidget(title);++ auto* blurb = new QLabel(+ "Configure the speech recognition engine used by the AI chat mic button.\n"+ "Google is free but unauthenticated and often rate-limited. Deepgram offers "+ "significantly better accuracy and supports financial keyword boosting.");+ blurb->setStyleSheet(label_ss());+ blurb->setWordWrap(true);+ vl->addWidget(blurb);++ // ── Provider selector ───────────────────────────────────────────────────+ auto* prov_row = new QWidget;+ auto* prov_hl = new QHBoxLayout(prov_row);+ prov_hl->setContentsMargins(0, 0, 0, 0);+ auto* prov_lbl = new QLabel("Provider");+ prov_lbl->setStyleSheet(label_ss());+ provider_combo_ = new QComboBox;+ provider_combo_->setStyleSheet(combo_ss());+ provider_combo_->addItem("Google (free, default)", "google");+ provider_combo_->addItem("Deepgram (API key required)", "deepgram");+ prov_hl->addWidget(prov_lbl);+ prov_hl->addStretch();+ prov_hl->addWidget(provider_combo_);+ vl->addWidget(prov_row);++ // ── Deepgram group (hidden for Google) ───────────────────────────────────+ deepgram_group_ = new QWidget;+ auto* dg_vl = new QVBoxLayout(deepgram_group_);+ dg_vl->setContentsMargins(0, 8, 0, 0);+ dg_vl->setSpacing(10);++ auto* dg_title = new QLabel("DEEPGRAM SETTINGS");+ dg_title->setStyleSheet(QString("color:%1;font-weight:700;letter-spacing:0.5px;background:transparent;")+ .arg(ui::colors::TEXT_SECONDARY()));+ dg_vl->addWidget(dg_title);++ // API key row with show/hide toggle+ auto* key_row = new QWidget;+ auto* key_hl = new QHBoxLayout(key_row);+ key_hl->setContentsMargins(0, 0, 0, 0);+ auto* key_lbl = new QLabel("API Key");+ key_lbl->setStyleSheet(label_ss());+ api_key_edit_ = new QLineEdit;+ api_key_edit_->setEchoMode(QLineEdit::Password);+ api_key_edit_->setPlaceholderText("Paste your Deepgram API key");+ api_key_edit_->setStyleSheet(input_ss());+ api_key_edit_->setMinimumWidth(320);+ show_key_btn_ = new QPushButton("Show");+ show_key_btn_->setStyleSheet(btn_secondary_ss());+ show_key_btn_->setCheckable(true);+ key_hl->addWidget(key_lbl);+ key_hl->addStretch();+ key_hl->addWidget(api_key_edit_);+ key_hl->addWidget(show_key_btn_);+ dg_vl->addWidget(key_row);++ // Model dropdown+ auto* model_row = new QWidget;+ auto* model_hl = new QHBoxLayout(model_row);+ model_hl->setContentsMargins(0, 0, 0, 0);+ auto* model_lbl = new QLabel("Model");+ model_lbl->setStyleSheet(label_ss());+ model_combo_ = new QComboBox;+ model_combo_->setStyleSheet(combo_ss());+ model_combo_->addItem("nova-3 (recommended)", "nova-3");+ model_combo_->addItem("nova-2", "nova-2");+ model_combo_->addItem("enhanced", "enhanced");+ model_combo_->addItem("base", "base");+ model_hl->addWidget(model_lbl);+ model_hl->addStretch();+ model_hl->addWidget(model_combo_);+ dg_vl->addWidget(model_row);++ // Language dropdown+ auto* lang_row = new QWidget;+ auto* lang_hl = new QHBoxLayout(lang_row);+ lang_hl->setContentsMargins(0, 0, 0, 0);+ auto* lang_lbl = new QLabel("Language");+ lang_lbl->setStyleSheet(label_ss());+ language_combo_ = new QComboBox;+ language_combo_->setStyleSheet(combo_ss());+ language_combo_->addItem("English (auto)", "en");+ language_combo_->addItem("English (US)", "en-US");+ language_combo_->addItem("English (UK)", "en-GB");+ language_combo_->addItem("Multilingual (nova-3 only)", "multi");+ lang_hl->addWidget(lang_lbl);+ lang_hl->addStretch();+ lang_hl->addWidget(language_combo_);+ dg_vl->addWidget(lang_row);++ // Keyterms+ auto* kt_row = new QWidget;+ auto* kt_hl = new QHBoxLayout(kt_row);+ kt_hl->setContentsMargins(0, 0, 0, 0);+ auto* kt_lbl = new QLabel("Key terms");+ kt_lbl->setStyleSheet(label_ss());+ keyterms_edit_ = new QLineEdit;+ keyterms_edit_->setPlaceholderText("AAPL, BTCUSD, Nifty (comma-separated)");+ keyterms_edit_->setStyleSheet(input_ss());+ keyterms_edit_->setMinimumWidth(320);+ kt_hl->addWidget(kt_lbl);+ kt_hl->addStretch();+ kt_hl->addWidget(keyterms_edit_);+ dg_vl->addWidget(kt_row);++ auto* kt_hint = new QLabel("Boosts recognition of financial symbols and proper nouns.");+ kt_hint->setStyleSheet(label_ss());+ kt_hint->setWordWrap(true);+ dg_vl->addWidget(kt_hint);++ vl->addWidget(deepgram_group_);++ // ── Save / Test row ─────────────────────────────────────────────────────+ auto* btn_row = new QWidget;+ auto* btn_hl = new QHBoxLayout(btn_row);+ btn_hl->setContentsMargins(0, 8, 0, 0);+ save_btn_ = new QPushButton("Save");+ save_btn_->setStyleSheet(btn_primary_ss());+ test_btn_ = new QPushButton("Test Deepgram key");+ test_btn_->setStyleSheet(btn_secondary_ss());+ btn_hl->addWidget(save_btn_);+ btn_hl->addWidget(test_btn_);+ btn_hl->addStretch();+ vl->addWidget(btn_row);++ status_lbl_ = new QLabel;+ status_lbl_->setStyleSheet(label_ss());+ status_lbl_->setWordWrap(true);+ vl->addWidget(status_lbl_);++ vl->addStretch();++ auto* outer = new QVBoxLayout(this);+ outer->setContentsMargins(0, 0, 0, 0);+ scroll->setWidget(page);+ outer->addWidget(scroll);++ // ── Wiring ──────────────────────────────────────────────────────────────+ connect(provider_combo_, qOverload<int>(&QComboBox::currentIndexChanged),+ this, &VoiceConfigSection::on_provider_changed);+ connect(show_key_btn_, &QPushButton::clicked, this, &VoiceConfigSection::on_show_hide_key);+ connect(save_btn_, &QPushButton::clicked, this, &VoiceConfigSection::on_save);+ connect(test_btn_, &QPushButton::clicked, this, &VoiceConfigSection::on_test);+}++// ── Load / Save ──────────────────────────────────────────────────────────────++void VoiceConfigSection::reload() {+ auto& cfg = AppConfig::instance();++ const QString provider = cfg.get("voice/provider", "google").toString().toLower();+ const int idx = provider_combo_->findData(provider);+ provider_combo_->setCurrentIndex(idx >= 0 ? idx : 0);++ // API key from SecureStorage+ auto key_res = SecureStorage::instance().retrieve(kSecureKey);+ api_key_edit_->setText(key_res.is_ok() ? key_res.value() : QString());++ const QString model = cfg.get("voice/deepgram/model", "nova-3").toString();+ const int midx = model_combo_->findData(model);+ model_combo_->setCurrentIndex(midx >= 0 ? midx : 0);++ const QString lang = cfg.get("voice/deepgram/language", "en").toString();+ const int lidx = language_combo_->findData(lang);+ language_combo_->setCurrentIndex(lidx >= 0 ? lidx : 0);++ keyterms_edit_->setText(cfg.get("voice/deepgram/keyterms", "").toString());++ apply_provider_visibility(provider);+ set_status({}, false);+}++void VoiceConfigSection::apply_provider_visibility(const QString& provider) {+ const bool is_dg = (provider == "deepgram");+ deepgram_group_->setVisible(is_dg);+ test_btn_->setVisible(is_dg);+}++void VoiceConfigSection::on_provider_changed(int /*index*/) {+ apply_provider_visibility(provider_combo_->currentData().toString());+}++void VoiceConfigSection::on_show_hide_key() {+ if (show_key_btn_->isChecked()) {+ api_key_edit_->setEchoMode(QLineEdit::Normal);+ show_key_btn_->setText("Hide");+ } else {+ api_key_edit_->setEchoMode(QLineEdit::Password);+ show_key_btn_->setText("Show");+ }+}++void VoiceConfigSection::on_save() {+ auto& cfg = AppConfig::instance();+ const QString provider = provider_combo_->currentData().toString();+ cfg.set("voice/provider", provider);+ cfg.set("voice/deepgram/model", model_combo_->currentData().toString());+ cfg.set("voice/deepgram/language", language_combo_->currentData().toString());+ cfg.set("voice/deepgram/keyterms", keyterms_edit_->text().trimmed());++ const QString api_key = api_key_edit_->text().trimmed();+ if (api_key.isEmpty()) {+ auto r = SecureStorage::instance().remove(kSecureKey);+ if (r.is_err())+ LOG_WARN(TAG, QString("Failed to clear Deepgram key: %1").arg(QString::fromStdString(r.error())));+ } else {+ auto r = SecureStorage::instance().store(kSecureKey, api_key);+ if (r.is_err()) {+ set_status(QStringLiteral("Failed to save API key: ") + QString::fromStdString(r.error()), true);+ return;+ }+ }++ LOG_INFO(TAG, QString("Voice config saved (provider=%1)").arg(provider));+ set_status(QStringLiteral("Saved. Changes apply on next voice session."), false);+ emit config_changed();+}++// ── Test connection ──────────────────────────────────────────────────────────++void VoiceConfigSection::on_test() {+ const QString api_key = api_key_edit_->text().trimmed();+ if (api_key.isEmpty()) {+ set_status("Enter an API key first.", true);+ return;+ }++ set_status("Testing Deepgram key…", false);+ test_btn_->setEnabled(false);++ // Lightweight verification: GET /v1/projects — succeeds iff the key is+ // valid. No audio sent, no billing impact. QNetworkAccessManager scoped+ // to this widget so it auto-cleans on destroy.+ auto* nam = new QNetworkAccessManager(this);+ QNetworkRequest req(QUrl("https://api.deepgram.com/v1/projects"));+ req.setRawHeader("Authorization", ("Token " + api_key).toUtf8());+ req.setRawHeader("Accept", "application/json");++ QPointer<VoiceConfigSection> self = this;+ QNetworkReply* reply = nam->get(req);+ connect(reply, &QNetworkReply::finished, this, [self, reply, nam]() {+ reply->deleteLater();+ nam->deleteLater();+ if (!self)+ return;+ self->test_btn_->setEnabled(true);+ const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ if (reply->error() == QNetworkReply::NoError && status == 200) {+ self->set_status("Deepgram key is valid.", false);+ } else if (status == 401) {+ self->set_status("Invalid API key (401).", true);+ } else if (status == 402) {+ self->set_status("Deepgram credits exhausted (402).", true);+ } else {+ self->set_status(QString("Test failed: HTTP %1 — %2").arg(status).arg(reply->errorString()), true);+ }+ });+}++void VoiceConfigSection::set_status(const QString& msg, bool error) {+ if (msg.isEmpty()) {+ status_lbl_->clear();+ return;+ }+ status_lbl_->setText(msg);+ status_lbl_->setStyleSheet(QString("color:%1;background:transparent;")+ .arg(error ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()));+}++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/settings/VoiceConfigSection.h b/fincept-qt/src/screens/settings/VoiceConfigSection.hnew file mode 100644index 000000000..63ff74e36--- /dev/null+++ b/fincept-qt/src/screens/settings/VoiceConfigSection.h@@ -0,0 +1,55 @@+#pragma once+// VoiceConfigSection.h — Voice / speech-to-text provider configuration panel.+//+// Provider switch (Google free vs Deepgram API) + Deepgram credentials &+// tuning. Lives alongside LlmConfigSection in the Settings screen.++#include <QCheckBox>+#include <QComboBox>+#include <QLabel>+#include <QLineEdit>+#include <QPushButton>+#include <QWidget>++namespace fincept::screens {++class VoiceConfigSection : public QWidget {+ Q_OBJECT+ public:+ explicit VoiceConfigSection(QWidget* parent = nullptr);++ /// Called when section becomes visible — reloads values from+ /// AppConfig and SecureStorage.+ void reload();++ signals:+ /// Emitted after user saves — SpeechService picks up new config on+ /// its next start_listening() call (no live restart needed).+ void config_changed();++ private slots:+ void on_provider_changed(int index);+ void on_show_hide_key();+ void on_save();+ void on_test();++ private:+ void build_ui();+ void apply_provider_visibility(const QString& provider);+ void set_status(const QString& msg, bool error = false);++ QComboBox* provider_combo_ = nullptr;+ QLineEdit* api_key_edit_ = nullptr;+ QPushButton* show_key_btn_ = nullptr;+ QComboBox* model_combo_ = nullptr;+ QComboBox* language_combo_ = nullptr;+ QLineEdit* keyterms_edit_ = nullptr;+ QPushButton* save_btn_ = nullptr;+ QPushButton* test_btn_ = nullptr;+ QLabel* status_lbl_ = nullptr;++ // Deepgram-only rows, hidden when provider is Google+ QWidget* deepgram_group_ = nullptr;+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/setup/SetupScreen.cpp b/fincept-qt/src/screens/setup/SetupScreen.cppindex fe42b3264..abe144e72 100644--- a/fincept-qt/src/screens/setup/SetupScreen.cpp+++ b/fincept-qt/src/screens/setup/SetupScreen.cpp@@ -2,8 +2,12 @@#include "screens/setup/SetupScreen.h"#include "core/logging/Logger.h"+#include "core/net/NetSpeedMeter.h"#include "python/PythonSetupManager.h"#include "ui/theme/Theme.h"+#include "ui/widgets/SpeedSparkline.h"++#include <QDateTime>#include <QHBoxLayout>#include <QLabel>@@ -40,6 +44,17 @@ SetupScreen::SetupScreen(QWidget* parent) : QWidget(parent) {timeout_timer_->setSingleShot(true);timeout_timer_->setInterval(15 * 60 * 1000);connect(timeout_timer_, &QTimer::timeout, this, &SetupScreen::on_setup_timeout);++ // Liveness: system-wide network throughput meter (starts when user clicks+ // BEGIN SETUP, stops on completion/skip/timeout).+ net_meter_ = new fincept::net::NetSpeedMeter(this);+ connect(net_meter_, &fincept::net::NetSpeedMeter::speed_changed,+ this, &SetupScreen::on_net_speed);++ // Elapsed-time ticker, drives the "Elapsed: Xm Ys" label once per second.+ elapsed_timer_ = new QTimer(this);+ elapsed_timer_->setInterval(1000);+ connect(elapsed_timer_, &QTimer::timeout, this, &SetupScreen::on_elapsed_tick);}// ─────────────────────────────────────────────────────────────────────────────@@ -125,6 +140,41 @@ void SetupScreen::build_ui() {.arg(colors::TEXT_TERTIARY(), fonts::DATA_FAMILY));cl->addWidget(status_label_);+ // ── Liveness row: elapsed time + ↓/↑ network speed + sparkline ───────────+ // Hidden until BEGIN SETUP is pressed so it doesn't clutter the idle view.+ live_row_ = new QWidget(center);+ live_row_->setVisible(false);+ auto* live_hl = new QHBoxLayout(live_row_);+ live_hl->setContentsMargins(0, 4, 0, 0);+ live_hl->setSpacing(12);++ const QString stat_css = QString("color:%1; font-family:%2; font-size:10px;")+ .arg(colors::TEXT_SECONDARY(), fonts::DATA_FAMILY);+ elapsed_lbl_ = new QLabel("Elapsed: 0s", live_row_);+ elapsed_lbl_->setStyleSheet(stat_css);+ elapsed_lbl_->setFixedWidth(120);+ live_hl->addWidget(elapsed_lbl_);++ down_lbl_ = new QLabel("\u2193 0 B/s", live_row_);+ down_lbl_->setStyleSheet(stat_css);+ down_lbl_->setFixedWidth(110);+ live_hl->addWidget(down_lbl_);++ up_lbl_ = new QLabel("\u2191 0 B/s", live_row_);+ up_lbl_->setStyleSheet(stat_css);+ up_lbl_->setFixedWidth(110);+ live_hl->addWidget(up_lbl_);++ sparkline_ = new fincept::ui::SpeedSparkline(live_row_);+ sparkline_->setMinimumHeight(18);+ sparkline_->set_line_color(QColor(kAccent));+ QColor accent_fill(kAccent);+ accent_fill.setAlpha(48);+ sparkline_->set_fill_color(accent_fill);+ live_hl->addWidget(sparkline_, 1);++ cl->addWidget(live_row_);+summary_lbl_ = new QLabel({}, center);summary_lbl_->setAlignment(Qt::AlignCenter);summary_lbl_->setWordWrap(true);@@ -279,11 +329,47 @@ void SetupScreen::on_begin_setup() {status_label_->setStyleSheet(QString("color:%1; font-family:%2; font-size:10px; margin-top:6px;").arg(kAccent, fonts::DATA_FAMILY));+ // Show liveness row and start throughput + elapsed meters.+ setup_started_ms_ = QDateTime::currentMSecsSinceEpoch();+ if (live_row_)+ live_row_->setVisible(true);+ if (elapsed_lbl_)+ elapsed_lbl_->setText("Elapsed: 0s");+ if (down_lbl_)+ down_lbl_->setText(QStringLiteral("\u2193 0 B/s"));+ if (up_lbl_)+ up_lbl_->setText(QStringLiteral("\u2191 0 B/s"));+ if (net_meter_)+ net_meter_->start(1000);+ if (elapsed_timer_)+ elapsed_timer_->start();+if (timeout_timer_)timeout_timer_->start();python::PythonSetupManager::instance().run_setup();}+void SetupScreen::on_net_speed(qint64 down_bps, qint64 up_bps) {+ if (down_lbl_)+ down_lbl_->setText(QStringLiteral("\u2193 ") + fincept::net::NetSpeedMeter::format_bps(down_bps));+ if (up_lbl_)+ up_lbl_->setText(QStringLiteral("\u2191 ") + fincept::net::NetSpeedMeter::format_bps(up_bps));+ if (sparkline_)+ sparkline_->push(down_bps);+}++void SetupScreen::on_elapsed_tick() {+ if (!elapsed_lbl_ || setup_started_ms_ == 0)+ return;+ const qint64 secs = (QDateTime::currentMSecsSinceEpoch() - setup_started_ms_) / 1000;+ QString text;+ if (secs < 60)+ text = QString("Elapsed: %1s").arg(secs);+ else+ text = QString("Elapsed: %1m %2s").arg(secs / 60).arg(secs % 60);+ elapsed_lbl_->setText(text);+}+void SetupScreen::on_progress(const python::SetupProgress& progress) {const QString& key = progress.step;@@ -324,6 +410,12 @@ void SetupScreen::on_progress(const python::SetupProgress& progress) {}void SetupScreen::on_setup_done(bool success, const QString& error) {+ // Stop liveness meters regardless of outcome.+ if (net_meter_)+ net_meter_->stop();+ if (elapsed_timer_)+ elapsed_timer_->stop();+if (success) {LOG_INFO("SetupScreen", "Python setup completed — all steps done");status_label_->setText("Everything is ready! Launching Fincept Terminal...");@@ -351,6 +443,10 @@ void SetupScreen::on_skip_clicked() {LOG_INFO("SetupScreen", "User skipped setup — launching app");if (timeout_timer_)timeout_timer_->stop();+ if (net_meter_)+ net_meter_->stop();+ if (elapsed_timer_)+ elapsed_timer_->stop();for (auto it = steps_.keyBegin(); it != steps_.keyEnd(); ++it)stop_pulse(*it);emit setup_complete();diff --git a/fincept-qt/src/screens/setup/SetupScreen.h b/fincept-qt/src/screens/setup/SetupScreen.hindex b3687f9cf..6499f39ab 100644--- a/fincept-qt/src/screens/setup/SetupScreen.h+++ b/fincept-qt/src/screens/setup/SetupScreen.h@@ -14,6 +14,14 @@ namespace fincept::python {struct SetupProgress;}+namespace fincept::net {+class NetSpeedMeter;+}++namespace fincept::ui {+class SpeedSparkline;+}+namespace fincept::screens {class SetupScreen : public QWidget {@@ -30,6 +38,8 @@ class SetupScreen : public QWidget {void on_setup_done(bool success, const QString& error);void on_skip_clicked(); // user-initiated skipvoid on_setup_timeout(); // overall 15-min timeout fired+ void on_net_speed(qint64 down_bps, qint64 up_bps);+ void on_elapsed_tick();private:void build_ui();@@ -47,6 +57,17 @@ class SetupScreen : public QWidget {QLabel* summary_lbl_ = nullptr;QTimer* timeout_timer_ = nullptr; // 15-min overall timeout+ // Liveness indicator — shown while setup is running so users can see+ // network activity even during long silent package installs.+ QWidget* live_row_ = nullptr;+ QLabel* down_lbl_ = nullptr;+ QLabel* up_lbl_ = nullptr;+ QLabel* elapsed_lbl_ = nullptr;+ fincept::ui::SpeedSparkline* sparkline_ = nullptr;+ fincept::net::NetSpeedMeter* net_meter_ = nullptr;+ QTimer* elapsed_timer_ = nullptr;+ qint64 setup_started_ms_ = 0;+// Step progress bars (keyed by step name)struct StepUI {QLabel* label = nullptr;diff --git a/fincept-qt/src/services/polymarket/PolymarketService.cpp b/fincept-qt/src/services/polymarket/PolymarketService.cppindex 2d869d00d..0ca2fe3a0 100644--- a/fincept-qt/src/services/polymarket/PolymarketService.cpp+++ b/fincept-qt/src/services/polymarket/PolymarketService.cpp@@ -44,26 +44,31 @@ static double num_or_str(const QJsonValue& v) {Market Market::from_json(const QJsonObject& obj) {Market m;- m.id = obj["id"].toInt();+ // Gamma API returns numeric IDs as JSON strings — accept both forms.+ const QJsonValue id_val = obj["id"];+ m.id = id_val.isString() ? id_val.toString().toInt() : id_val.toInt();m.question = obj["question"].toString();m.slug = obj["slug"].toString();m.description = obj["description"].toString();m.condition_id = obj["conditionId"].toString();m.image = obj["image"].toString();- m.volume = obj["volume"].toDouble();- m.liquidity = obj["liquidity"].toDouble();+ // volume / liquidity come back as JSON strings from Gamma ("1567632.01").+ m.volume = num_or_str(obj["volume"]);+ m.liquidity = num_or_str(obj["liquidity"]);m.active = obj["active"].toBool();m.closed = obj["closed"].toBool();m.end_date = obj["endDate"].toString();m.category = obj["category"].toString();- m.event_id = obj["eventId"].toInt();+ const QJsonValue eid_val = obj["eventId"];+ m.event_id = eid_val.isString() ? eid_val.toString().toInt() : eid_val.toInt();auto outcomes_arr = parse_json_arr(obj["outcomes"]);auto prices_arr = parse_json_arr(obj["outcomePrices"]);for (int i = 0; i < outcomes_arr.size(); ++i) {Outcome o;o.name = outcomes_arr[i].toString();- o.price = (i < prices_arr.size()) ? prices_arr[i].toDouble() : 0.0;+ // outcomePrices are JSON strings ("0.535") — use num_or_str.+ o.price = (i < prices_arr.size()) ? num_or_str(prices_arr[i]) : 0.0;m.outcomes.append(o);}@@ -88,23 +93,27 @@ Market Market::from_json(const QJsonObject& obj) {Event Event::from_json(const QJsonObject& obj) {Event e;- e.id = obj["id"].toInt();+ const QJsonValue id_val = obj["id"];+ e.id = id_val.isString() ? id_val.toString().toInt() : id_val.toInt();e.title = obj["title"].toString();e.slug = obj["slug"].toString();e.description = obj["description"].toString();e.image = obj["image"].toString();- e.volume = obj["volume"].toDouble();- e.liquidity = obj["liquidity"].toDouble();+ e.volume = num_or_str(obj["volume"]);+ e.liquidity = num_or_str(obj["liquidity"]);e.active = obj["active"].toBool();e.closed = obj["closed"].toBool();e.end_date = obj["endDate"].toString();+ // Events carry a direct "category" field ("Sports", "Politics", etc.).+ // Fall back to first tag label if absent.+ e.category = obj["category"].toString();auto tags_arr = obj["tags"].toArray();for (const auto& t : tags_arr) {auto tag_obj = t.toObject();e.tags.append(tag_obj["label"].toString());}- if (!e.tags.isEmpty())+ if (e.category.isEmpty() && !e.tags.isEmpty())e.category = e.tags.first();auto markets_arr = obj["markets"].toArray();@@ -144,7 +153,8 @@ PriceHistory PriceHistory::from_json(const QJsonObject& obj) {auto po = pt.toObject();PricePoint pp;pp.timestamp = static_cast<int64_t>(po["t"].toVariant().toLongLong());- pp.price = po["p"].toDouble();+ // CLOB returns price "p" as a JSON string.+ pp.price = num_or_str(po["p"]);ph.points.append(pp);}return ph;@@ -153,8 +163,9 @@ PriceHistory PriceHistory::from_json(const QJsonObject& obj) {Trade Trade::from_json(const QJsonObject& obj) {Trade t;t.side = obj["side"].toString();- t.price = obj["price"].toDouble();- t.size = obj["size"].toDouble();+ // CLOB and Data APIs return price/size as JSON strings.+ t.price = num_or_str(obj["price"]);+ t.size = num_or_str(obj["size"]);t.timestamp = static_cast<int64_t>(obj["timestamp"].toVariant().toLongLong());t.condition_id = obj["conditionId"].toString();return t;@@ -174,11 +185,12 @@ TopHolder TopHolder::from_json(const QJsonObject& obj) {if (h.display_name.isEmpty() && !h.address.isEmpty())h.display_name = h.address.left(6) + "..." + h.address.right(4);// /holders returns `amount` (token balance). `size` is a legacy fallback.- h.position_size = obj["amount"].toDouble();+ h.position_size = num_or_str(obj["amount"]);if (h.position_size == 0.0)- h.position_size = obj["size"].toDouble();- h.entry_price = obj["avgPrice"].toDouble();- h.rank = obj["rank"].toInt();+ h.position_size = num_or_str(obj["size"]);+ h.entry_price = num_or_str(obj["avgPrice"]);+ const QJsonValue rv = obj["rank"];+ h.rank = rv.isString() ? rv.toString().toInt() : rv.toInt();return h;}@@ -196,15 +208,17 @@ LeaderboardEntry LeaderboardEntry::from_json(const QJsonObject& obj) {if (e.display_name.isEmpty() && !e.address.isEmpty())e.display_name = e.address.left(6) + "..." + e.address.right(4);e.profile_image = obj["profileImage"].toString();- e.pnl = obj["pnl"].toDouble();+ e.pnl = num_or_str(obj["pnl"]);if (e.pnl == 0)- e.pnl = obj["cashPnl"].toDouble();+ e.pnl = num_or_str(obj["cashPnl"]);// /v1/leaderboard uses `vol`; legacy `volume` retained for safety.- e.volume = obj["vol"].toDouble();+ e.volume = num_or_str(obj["vol"]);if (e.volume == 0)- e.volume = obj["volume"].toDouble();+ e.volume = num_or_str(obj["volume"]);e.num_trades = obj["numTrades"].toInt();- e.rank = obj["rank"].toInt();+ // API returns rank as string ("1", "2") — accept both.+ const QJsonValue rv = obj["rank"];+ e.rank = rv.isString() ? rv.toString().toInt() : rv.toInt();return e;}@@ -214,9 +228,9 @@ Activity Activity::from_json(const QJsonObject& obj) {a.address = obj["proxyWallet"].toString();if (a.address.isEmpty())a.address = obj["address"].toString();- a.amount = obj["size"].toDouble();- a.usdc_size = obj["usdcSize"].toDouble();- a.price = obj["price"].toDouble();+ a.amount = num_or_str(obj["size"]);+ a.usdc_size = num_or_str(obj["usdcSize"]);+ a.price = num_or_str(obj["price"]);a.timestamp = static_cast<int64_t>(obj["timestamp"].toVariant().toLongLong());a.condition_id = obj["conditionId"].toString();a.title = obj["title"].toString();@@ -283,15 +297,16 @@ LiveVolume LiveVolume::from_json(const QJsonObject& obj) {WsMarketUpdate WsMarketUpdate::from_json(const QJsonObject& obj) {WsMarketUpdate u;u.asset_id = obj["asset_id"].toString();- u.price = obj["price"].toDouble();+ // WS messages return price as a string.+ u.price = num_or_str(obj["price"]);u.timestamp = static_cast<int64_t>(obj["timestamp"].toVariant().toLongLong());for (const auto& b : obj["bids"].toArray()) {auto bo = b.toObject();- u.bids.append({bo["price"].toDouble(), bo["size"].toDouble()});+ u.bids.append({num_or_str(bo["price"]), num_or_str(bo["size"])});}for (const auto& a : obj["asks"].toArray()) {auto ao = a.toObject();- u.asks.append({ao["price"].toDouble(), ao["size"].toDouble()});+ u.asks.append({num_or_str(ao["price"]), num_or_str(ao["size"])});}return u;}@@ -443,7 +458,7 @@ void PolymarketService::search_markets(const QString& query, int limit) {for (const auto& v : arr)result.append(Market::from_json(v.toObject()));LOG_INFO("Polymarket", "Search returned " + QString::number(result.size()) + " markets");- emit markets_ready(result);+ emit search_results_ready(result, {});},"SearchMarkets");}@@ -578,8 +593,9 @@ void PolymarketService::fetch_tags() {"FetchTags");}-void PolymarketService::fetch_comments(const QString& market_slug, int limit) {- QString path = "/comments?asset=" + QUrl::toPercentEncoding(market_slug) + "&limit=" + QString::number(limit);+void PolymarketService::fetch_comments(const QString& condition_id, int limit) {+ // Gamma /comments requires conditionId (0x hex), not the slug.+ QString path = "/comments?conditionId=" + QUrl::toPercentEncoding(condition_id) + "&limit=" + QString::number(limit);get_gamma(path,diff --git a/fincept-qt/src/services/polymarket/PolymarketService.h b/fincept-qt/src/services/polymarket/PolymarketService.hindex b0c32c2cd..5c39ef04c 100644--- a/fincept-qt/src/services/polymarket/PolymarketService.h+++ b/fincept-qt/src/services/polymarket/PolymarketService.h@@ -30,7 +30,7 @@ class PolymarketService : public QObject {void fetch_event_by_id(int id);void fetch_related_markets(int event_id);void fetch_tags();- void fetch_comments(const QString& market_slug, int limit = 50);+ void fetch_comments(const QString& condition_id, int limit = 50);void fetch_teams(const QString& league = "");// ── CLOB API ─────────────────────────────────────────────────────────diff --git a/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.cpp b/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.cppindex f983a577d..0172a8fab 100644--- a/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.cpp+++ b/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.cpp@@ -86,6 +86,7 @@ void KalshiAdapter::search(const QString& query, int limit) {// treat the query as a series_ticker filter. If the user enters a// full ticker like "KXPRES" it'll pull matching markets. For richer// search we'd need to list + client-side filter, which is Phase 8.+ search_pending_ = true;rest_->fetch_markets(QStringLiteral("open"), QString(), query.toUpper(), QString(), limit, QString());}@@ -147,11 +148,16 @@ void KalshiAdapter::fetch_price_history(const QString& asset_id, const QString&else if (interval == QStringLiteral("6h")) start = end - (6 * 3600);else if (interval == QStringLiteral("1h")) start = end - 3600;- // Kalshi candlestick endpoint requires the series ticker. For tickers- // of the form "KXFOO-23DEC-T3.00", the series is the prefix before- // the first dash (e.g. "KXFOO"). Fallback to the whole ticker.- const int dash = ticker.indexOf('-');- const QString series = (dash > 0) ? ticker.left(dash) : ticker;+ // Kalshi candlestick endpoint requires the series ticker. Prefer the+ // cached mapping populated from markets_ready/events_ready responses;+ // fall back to the prefix-before-first-dash heuristic for tickers we+ // haven't seen. Many Kalshi tickers have multi-segment structure (e.g.+ // KXPRES-24-DJT) so the heuristic is best-effort, not authoritative.+ QString series = series_by_market_.value(ticker);+ if (series.isEmpty()) {+ const int dash = ticker.indexOf('-');+ series = (dash > 0) ? ticker.left(dash) : ticker;+ }rest_->fetch_candlesticks(series, ticker, period, start, end);}@@ -204,6 +210,12 @@ void KalshiAdapter::stub_unsupported(const QString& ctx) {emit error_occurred(ctx, QStringLiteral("Kalshi adapter: not supported in this call"));}+// prediction_kalshi.py also exposes `settlements` and `decrease_order`+// commands. They're reachable directly via PythonRunner for scripted+// testing but intentionally not surfaced on the adapter because no UI+// currently consumes a settlements view or a decrease-order control.+// Wire an adapter method here when that UI lands.+QJsonObject KalshiAdapter::creds_to_json() const {QJsonObject o;o.insert("api_key_id", creds_.api_key_id);@@ -385,8 +397,9 @@ void KalshiAdapter::cancel_order(const QString& order_id) {}void KalshiAdapter::cancel_all_for_market(const pr::MarketKey& key, const QString& /*asset_id*/) {- // Kalshi has no single bulk-cancel-by-market endpoint; iterate open- // orders filtered by ticker and cancel each.+ // Fetch the ticker-filtered open orders and cancel them in one batched+ // DELETE /portfolio/orders/batched round-trip (instead of N individual+ // cancels). Empty result set is a silent success.if (key.market_id.isEmpty()) {emit error_occurred(QStringLiteral("cancel_all_for_market"),QStringLiteral("Kalshi cancel-all requires a ticker"));@@ -399,15 +412,111 @@ void KalshiAdapter::cancel_all_for_market(const pr::MarketKey& key, const QStrinrun_py(QStringLiteral("open_orders"), extra,[self](const QJsonObject& resp) {if (!self) return;+ QStringList ids;const auto arr = resp.value("orders").toArray();+ ids.reserve(arr.size());for (const auto& v : arr) {const QString oid = v.toObject().value("order_id").toString();- if (!oid.isEmpty()) self->cancel_order(oid);+ if (!oid.isEmpty()) ids.push_back(oid);}+ if (!ids.isEmpty()) self->cancel_orders_batch(ids);},QStringLiteral("cancel_all_for_market"));}+// ── Kalshi-specific public reads ────────────────────────────────────────────++void KalshiAdapter::fetch_exchange_status() { rest_->fetch_exchange_status(); }+void KalshiAdapter::fetch_exchange_schedule() { rest_->fetch_exchange_schedule(); }++void KalshiAdapter::fetch_batch_candles(const QStringList& tickers, int period_interval_min,+ qint64 start_ts, qint64 end_ts) {+ rest_->fetch_batch_candlesticks(tickers, period_interval_min, start_ts, end_ts);+}++void KalshiAdapter::fetch_series_detail(const QString& series_ticker) {+ if (series_ticker.isEmpty()) return;+ // If cached, re-emit synchronously so consumers don't have to track+ // "did I already fetch this?" — they can just call the method.+ const auto it = series_cache_.constFind(series_ticker);+ if (it != series_cache_.constEnd()) {+ QMetaObject::invokeMethod(this, [this, series_ticker]() {+ emit series_detail_ready(series_ticker, series_cache_.value(series_ticker));+ }, Qt::QueuedConnection);+ return;+ }+ rest_->fetch_series_detail(series_ticker);+}++QJsonObject KalshiAdapter::cached_series(const QString& series_ticker) const {+ return series_cache_.value(series_ticker);+}++void KalshiAdapter::fetch_historical_markets(const QString& series_ticker, int limit,+ const QString& cursor) {+ rest_->fetch_historical_markets(series_ticker, limit, cursor);+}++void KalshiAdapter::fetch_historical_candles(const QString& ticker, int period_interval_min,+ qint64 start_ts, qint64 end_ts) {+ rest_->fetch_historical_candlesticks(ticker, period_interval_min, start_ts, end_ts);+}++void KalshiAdapter::fetch_historical_trades(const QString& ticker, int limit,+ const QString& cursor) {+ rest_->fetch_historical_trades(ticker, limit, cursor);+}++// ── Kalshi-specific trading ─────────────────────────────────────────────────++void KalshiAdapter::amend_order(const QString& order_id, const QString& side,+ int price_cents, const QString& client_order_id) {+ const int p = qBound(1, price_cents, 99);+ QJsonObject extra;+ extra.insert("order_id", order_id);+ if (side.toLower() == QStringLiteral("yes"))+ extra.insert("yes_price_cents", p);+ else+ extra.insert("no_price_cents", p);+ if (!client_order_id.isEmpty()) extra.insert("client_order_id", client_order_id);+ const QString oid = order_id;+ QPointer<KalshiAdapter> self = this;+ run_py(QStringLiteral("amend_order"), extra,+ [self, oid](const QJsonObject& /*resp*/) {+ if (!self) return;+ emit self->order_amended(oid, true, QString());+ },+ QStringLiteral("amend_order"));+}++void KalshiAdapter::fetch_order(const QString& order_id) {+ QJsonObject extra;+ extra.insert("order_id", order_id);+ QPointer<KalshiAdapter> self = this;+ run_py(QStringLiteral("get_order"), extra,+ [self](const QJsonObject& resp) {+ if (!self) return;+ emit self->single_order_ready(resp.value("order").toObject());+ },+ QStringLiteral("fetch_order"));+}++void KalshiAdapter::cancel_orders_batch(const QStringList& order_ids) {+ if (order_ids.isEmpty()) return;+ QJsonObject extra;+ QJsonArray ids;+ for (const auto& id : order_ids) ids.append(id);+ extra.insert("order_ids", ids);+ const QStringList ids_copy = order_ids;+ QPointer<KalshiAdapter> self = this;+ run_py(QStringLiteral("cancel_orders_batch"), extra,+ [self, ids_copy](const QJsonObject& /*resp*/) {+ if (!self) return;+ emit self->orders_batch_cancelled(ids_copy, true, QString());+ },+ QStringLiteral("cancel_orders_batch"));+}+// ── Credentials plumbing ────────────────────────────────────────────────────void KalshiAdapter::set_credentials(const KalshiCredentials& creds) {@@ -428,19 +537,45 @@ void KalshiAdapter::ensure_registered_with_hub() {// ── Signal wiring ───────────────────────────────────────────────────────────void KalshiAdapter::wire() {- // REST → adapter signal forwarding.+ // REST → adapter signal forwarding. Also harvests market→series+ // mappings so fetch_price_history can hit the correct endpoint.connect(rest_.get(), &KalshiRestClient::markets_ready, this,[this](const QVector<pr::PredictionMarket>& markets, const QString& /*cursor*/) {- emit markets_ready(markets);+ for (const auto& m : markets) {+ const QString s = m.extras.value(QStringLiteral("series_ticker")).toString();+ if (!s.isEmpty()) series_by_market_.insert(m.key.market_id, s);+ }+ if (search_pending_) {+ search_pending_ = false;+ emit search_results_ready(markets, {});+ } else {+ emit markets_ready(markets);+ }});connect(rest_.get(), &KalshiRestClient::events_ready, this,[this](const QVector<pr::PredictionEvent>& events, const QString& /*cursor*/) {+ for (const auto& e : events) {+ for (const auto& m : e.markets) {+ const QString s = m.extras.value(QStringLiteral("series_ticker")).toString();+ if (!s.isEmpty()) series_by_market_.insert(m.key.market_id, s);+ }+ }emit events_ready(events);});- connect(rest_.get(), &KalshiRestClient::market_detail_ready,- this, &KalshiAdapter::market_detail_ready);- connect(rest_.get(), &KalshiRestClient::event_detail_ready,- this, &KalshiAdapter::event_detail_ready);+ connect(rest_.get(), &KalshiRestClient::market_detail_ready, this,+ [this](const pr::PredictionMarket& m) {+ const QString s = m.extras.value(QStringLiteral("series_ticker")).toString();+ if (!s.isEmpty()) series_by_market_.insert(m.key.market_id, s);+ emit market_detail_ready(m);+ });+ connect(rest_.get(), &KalshiRestClient::event_detail_ready, this,+ [this](const pr::PredictionEvent& e) {+ for (const auto& m : e.markets) {+ const QString s = m.extras.value(QStringLiteral("series_ticker")).toString();+ if (!s.isEmpty()) series_by_market_.insert(m.key.market_id, s);+ }+ emit event_detail_ready(e);+ });connect(rest_.get(), &KalshiRestClient::tags_ready,this, &KalshiAdapter::tags_ready);connect(rest_.get(), &KalshiRestClient::trades_ready,@@ -466,11 +601,37 @@ void KalshiAdapter::wire() {emit price_history_ready(out);});+ // Kalshi-specific REST signal forwards.+ connect(rest_.get(), &KalshiRestClient::exchange_status_ready,+ this, &KalshiAdapter::exchange_status_ready);+ connect(rest_.get(), &KalshiRestClient::exchange_schedule_ready,+ this, &KalshiAdapter::exchange_schedule_ready);+ connect(rest_.get(), &KalshiRestClient::batch_candlesticks_ready,+ this, &KalshiAdapter::batch_candles_ready);+ connect(rest_.get(), &KalshiRestClient::historical_markets_ready,+ this, &KalshiAdapter::historical_markets_ready);+ connect(rest_.get(), &KalshiRestClient::historical_trades_ready,+ this, &KalshiAdapter::historical_trades_ready);+ connect(rest_.get(), &KalshiRestClient::historical_candlesticks_ready,+ this, &KalshiAdapter::historical_candles_ready);++ // Series detail — cache before emitting so sync consumers can read.+ connect(rest_.get(), &KalshiRestClient::series_detail_ready, this,+ [this](const QJsonObject& series) {+ const QString t = series.value(QStringLiteral("ticker")).toString();+ if (!t.isEmpty()) series_cache_.insert(t, series);+ emit series_detail_ready(t, series);+ });+// WebSocket → adapter.connect(ws_.get(), &KalshiWsClient::price_updated,this, &KalshiAdapter::ws_price_updated);connect(ws_.get(), &KalshiWsClient::orderbook_updated,this, &KalshiAdapter::ws_orderbook_updated);+ connect(ws_.get(), &KalshiWsClient::trade_received,+ this, &KalshiAdapter::ws_trade_received);+ connect(ws_.get(), &KalshiWsClient::market_lifecycle_changed,+ this, &KalshiAdapter::ws_market_lifecycle_changed);connect(ws_.get(), &KalshiWsClient::connection_status_changed,this, &KalshiAdapter::ws_connection_changed);}diff --git a/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.h b/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.hindex 3423f4621..26e7b7427 100644--- a/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.h+++ b/fincept-qt/src/services/prediction/kalshi/KalshiAdapter.h@@ -3,6 +3,7 @@#include "services/prediction/PredictionExchangeAdapter.h"#include "services/prediction/kalshi/KalshiCredentials.h"+#include <QHash>#include <QJsonObject>#include <QString>#include <QStringList>@@ -67,6 +68,70 @@ class KalshiAdapter : public fincept::services::prediction::PredictionExchangeAd// Credential injection (Phase 5 will wire this via the account dialog).void set_credentials(const KalshiCredentials& creds);+ // ── Kalshi-specific public reads (pass through to REST client) ──────++ /// GET /exchange/status + /exchange/schedule. Results arrive on the+ /// exchange_* signals below.+ void fetch_exchange_status();+ void fetch_exchange_schedule();+ /// GET /markets/candlesticks (batch). Results arrive on batch_candles_ready.+ void fetch_batch_candles(const QStringList& tickers, int period_interval_min,+ qint64 start_ts, qint64 end_ts);+ /// GET /series/{series_ticker}. Result arrives on series_detail_ready.+ /// Cached per ticker — repeat calls are free.+ void fetch_series_detail(const QString& series_ticker);+ /// Lookup a cached series fee config without refetching. Returns an+ /// empty object if we haven't fetched this series yet.+ QJsonObject cached_series(const QString& series_ticker) const;+ /// GET /historical/markets / candlesticks / trades.+ void fetch_historical_markets(const QString& series_ticker = QString(),+ int limit = 100,+ const QString& cursor = QString());+ void fetch_historical_candles(const QString& ticker, int period_interval_min,+ qint64 start_ts, qint64 end_ts);+ void fetch_historical_trades(const QString& ticker = QString(),+ int limit = 100,+ const QString& cursor = QString());++ // ── Kalshi-specific trading (pass through to Python bridge) ─────────++ /// POST /portfolio/orders/{order_id}/amend.+ /// price_cents 1-99. `side` is the resting side ("yes" or "no") — the+ /// caller passes the order's current side so we target the right price+ /// field.+ void amend_order(const QString& order_id, const QString& side, int price_cents,+ const QString& client_order_id = QString());+ /// GET /portfolio/orders/{order_id}. Result arrives on single_order_ready.+ void fetch_order(const QString& order_id);+ /// DELETE /portfolio/orders/batched. Result arrives on orders_batch_cancelled.+ void cancel_orders_batch(const QStringList& order_ids);++ signals:+ // Kalshi-specific extensions (not on the base adapter interface).+ // Consumers cast to KalshiAdapter* to connect.+ void ws_trade_received(const fincept::services::prediction::PredictionTrade& trade);+ void ws_market_lifecycle_changed(const QString& ticker, const QString& status);++ void exchange_status_ready(const QJsonObject& status);+ void exchange_schedule_ready(const QJsonObject& schedule);+ void batch_candles_ready(+ const QHash<QString, fincept::services::prediction::PriceHistory>& histories);+ void series_detail_ready(const QString& series_ticker, const QJsonObject& series);++ void historical_markets_ready(+ const QVector<fincept::services::prediction::PredictionMarket>& markets,+ const QString& next_cursor);+ void historical_candles_ready(+ const fincept::services::prediction::PriceHistory& history, const QString& ticker);+ void historical_trades_ready(+ const QVector<fincept::services::prediction::PredictionTrade>& trades,+ const QString& next_cursor);++ void order_amended(const QString& order_id, bool ok, const QString& error);+ void single_order_ready(const QJsonObject& order);+ void orders_batch_cancelled(const QStringList& order_ids, bool ok,+ const QString& error);+private:void wire();void stub_unsupported(const QString& ctx);@@ -91,6 +156,19 @@ class KalshiAdapter : public fincept::services::prediction::PredictionExchangeAd// can attach it to the emitted PriceHistory (Kalshi REST only returns// YES-side candles).QString last_history_asset_id_;++ // Set to true while a search() call is in-flight so the markets_ready+ // handler can emit search_results_ready instead of markets_ready.+ bool search_pending_ = false;++ // Market ticker → series_ticker cache populated from markets_ready /+ // events_ready. Used by fetch_price_history to build the+ // /series/{s}/markets/{t}/candlesticks path without string heuristics.+ QHash<QString, QString> series_by_market_;++ // Cached /series/{ticker} responses. Keyed by series ticker. Populated+ // via fetch_series_detail; repeat fetches hit the cache.+ QHash<QString, QJsonObject> series_cache_;};} // namespace fincept::services::prediction::kalshi_nsdiff --git a/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.cpp b/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.cppindex 6d2e82fdc..b06bc2aef 100644--- a/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.cpp+++ b/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.cpp@@ -34,7 +34,12 @@ static double fp_to_double(const QJsonValue& v) {}static double str_or_num(const QJsonValue& v) {- if (v.isString()) return v.toString().toDouble();+ if (v.isString()) {+ QString s = v.toString();+ // Historical endpoints prefix prices with "$" (e.g. "$0.05") — strip it.+ if (s.startsWith('$')) s = s.mid(1);+ return s.toDouble();+ }return v.toDouble();}@@ -61,10 +66,12 @@ static pr::PredictionMarket parse_market(const QJsonObject& obj) {m.open_interest = fp_to_double(obj.value("open_interest_fp"));m.liquidity = str_or_num(obj.value("liquidity_dollars"));- const QString status = obj.value("status").toString();- m.active = (status == QStringLiteral("active"));- m.closed = (status == QStringLiteral("closed") || status == QStringLiteral("determined") ||- status == QStringLiteral("finalized"));+ // Kalshi v2 market statuses: unopened, open, active, paused, closed, settled.+ // Real API returns "active" (not "open") for live markets — compare+ // case-insensitively since casing has varied across API versions.+ const QString status = obj.value("status").toString().toLower();+ m.active = (status == QStringLiteral("open") || status == QStringLiteral("active"));+ m.closed = (status == QStringLiteral("closed") || status == QStringLiteral("settled"));pr::Outcome yes;yes.name = QStringLiteral("Yes");@@ -76,6 +83,11 @@ static pr::PredictionMarket parse_market(const QJsonObject& obj) {no.price = str_or_num(obj.value("no_bid_dollars"));m.outcomes = {yes, no};+ m.extras.insert(QStringLiteral("status"), obj.value("status").toString());+ // Kalshi markets don't carry series_ticker directly; the event does. When+ // parse_market is called from parse_event the caller patches this in.+ // We still insert an empty placeholder so callers can unconditionally read.+ m.extras.insert(QStringLiteral("series_ticker"), QString());m.extras.insert(QStringLiteral("yes_ask_dollars"), str_or_num(obj.value("yes_ask_dollars")));m.extras.insert(QStringLiteral("no_ask_dollars"), str_or_num(obj.value("no_ask_dollars")));m.extras.insert(QStringLiteral("last_price_dollars"), str_or_num(obj.value("last_price_dollars")));@@ -84,7 +96,10 @@ static pr::PredictionMarket parse_market(const QJsonObject& obj) {m.extras.insert(QStringLiteral("market_type"), obj.value("market_type").toString());m.extras.insert(QStringLiteral("yes_sub_title"), obj.value("yes_sub_title").toString());m.extras.insert(QStringLiteral("no_sub_title"), obj.value("no_sub_title").toString());- m.extras.insert(QStringLiteral("settlement_ts"), qint64(obj.value("settlement_ts").toDouble()));+ m.extras.insert(QStringLiteral("settlement_value_dollars"),+ str_or_num(obj.value("settlement_value_dollars")));+ m.extras.insert(QStringLiteral("settlement_timer_seconds"),+ qint64(obj.value("settlement_timer_seconds").toDouble()));return m;}@@ -99,14 +114,21 @@ static pr::PredictionEvent parse_event(const QJsonObject& obj) {// Kalshi doesn't give event-level volume; aggregate from markets below.e.volume = 0.0;- const QString status = obj.value("status").toString();- e.active = status == QStringLiteral("active") || status == QStringLiteral("open");- e.closed = status == QStringLiteral("closed") || status == QStringLiteral("settled");+ // API returns "Active" (capitalised) — compare case-insensitively.+ const QString status = obj.value("status").toString().toLower();+ e.active = (status == QStringLiteral("active") || status == QStringLiteral("open"));+ e.closed = (status == QStringLiteral("closed") || status == QStringLiteral("settled"));+ const QString series = obj.value("series_ticker").toString();const auto mk_arr = obj.value("markets").toArray();e.markets.reserve(mk_arr.size());for (const auto& v : mk_arr) {auto m = parse_market(v.toObject());+ // Event carries the series; propagate into each nested market so the+ // candlestick endpoint can look it up without heuristics.+ if (!series.isEmpty()) {+ m.extras.insert(QStringLiteral("series_ticker"), series);+ }e.volume += m.volume;e.markets.push_back(m);}@@ -170,16 +192,26 @@ void KalshiRestClient::fetch_markets(const QString& status, const QString& eventQUrl u(base_url() + QStringLiteral("/markets"));u.setQuery(q);+ const QString series_filter = series_ticker;QPointer<KalshiRestClient> self = this;get_json(u.toString(base_url().startsWith(QStringLiteral("https")) ?QUrl::FullyEncoded : QUrl::PrettyDecoded),- [self](const QJsonDocument& doc) {+ [self, series_filter](const QJsonDocument& doc) {if (!self) return;const auto obj = doc.object();QVector<pr::PredictionMarket> markets;const auto arr = obj.value("markets").toArray();markets.reserve(arr.size());- for (const auto& v : arr) markets.push_back(parse_market(v.toObject()));+ for (const auto& v : arr) {+ auto m = parse_market(v.toObject());+ // When the caller filtered by series_ticker the series is+ // unambiguous, so stamp it so candlestick lookups don't+ // need heuristic ticker parsing.+ if (!series_filter.isEmpty()) {+ m.extras.insert(QStringLiteral("series_ticker"), series_filter);+ }+ markets.push_back(m);+ }emit self->markets_ready(markets, obj.value("cursor").toString());},QStringLiteral("Kalshi.fetch_markets"));@@ -375,16 +407,17 @@ void KalshiRestClient::fetch_market_trades(const QString& ticker, int limit, conconst auto o = v.toObject();pr::PredictionTrade t;t.asset_id = o.value("ticker").toString() + QStringLiteral(":yes");- t.side = o.value("taker_side").toString().toUpper();- if (t.side.isEmpty()) t.side = QStringLiteral("BUY");+ // taker_side is "yes"/"no"; map to BUY/SELL for the+ // unified shape. YES-taker = BUY of YES; NO-taker = SELL.+ const QString ts_side = o.value("taker_side").toString().toLower();+ t.side = (ts_side == QStringLiteral("no")) ? QStringLiteral("SELL")+ : QStringLiteral("BUY");t.price = str_or_num(o.value("yes_price_dollars"));- if (t.price <= 0) t.price = str_or_num(o.value("price_dollars"));t.size = fp_to_double(o.value("count_fp"));- t.ts_ms = qint64(o.value("created_time_ts").toDouble()) * 1000;- if (t.ts_ms <= 0) {- const QString iso = o.value("created_time").toString();- t.ts_ms = QDateTime::fromString(iso, Qt::ISODate).toMSecsSinceEpoch();- }+ // Kalshi returns ISO 8601 `created_time`; there is no+ // epoch variant on trades.+ const QString iso = o.value("created_time").toString();+ t.ts_ms = QDateTime::fromString(iso, Qt::ISODate).toMSecsSinceEpoch();trades.push_back(t);}emit self->trades_ready(trades);@@ -392,4 +425,225 @@ void KalshiRestClient::fetch_market_trades(const QString& ticker, int limit, conQStringLiteral("Kalshi.fetch_market_trades"));}+// ── Shared trade parser (used by market + historical trades) ───────────────++static pr::PredictionTrade parse_trade(const QJsonObject& o) {+ pr::PredictionTrade t;+ t.asset_id = o.value("ticker").toString() + QStringLiteral(":yes");+ const QString ts_side = o.value("taker_side").toString().toLower();+ t.side = (ts_side == QStringLiteral("no")) ? QStringLiteral("SELL")+ : QStringLiteral("BUY");+ t.price = str_or_num(o.value("yes_price_dollars"));+ t.size = fp_to_double(o.value("count_fp"));+ const QString iso = o.value("created_time").toString();+ t.ts_ms = QDateTime::fromString(iso, Qt::ISODate).toMSecsSinceEpoch();+ return t;+}++// ── Candlestick parser (shared by per-market + historical + batch) ─────────++static pr::PriceHistory parse_candlestick_history(const QJsonArray& arr,+ const QString& asset_id) {+ pr::PriceHistory h;+ h.asset_id = asset_id;+ h.points.reserve(arr.size());+ for (const auto& v : arr) {+ const auto o = v.toObject();+ const qint64 ts = qint64(o.value("end_period_ts").toDouble()) * 1000;+ const auto price = o.value("price").toObject();+ QJsonValue close = price.value("close_dollars");+ if (close.isNull() || close.isUndefined()) {+ close = o.value("yes_bid").toObject().value("close_dollars");+ }+ const double p = str_or_num(close);+ if (ts > 0 && p > 0) h.points.push_back({ts, p});+ }+ return h;+}++// ── Exchange metadata ──────────────────────────────────────────────────────++void KalshiRestClient::fetch_exchange_status() {+ QPointer<KalshiRestClient> self = this;+ get_json(QStringLiteral("/exchange/status"),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ emit self->exchange_status_ready(doc.object());+ },+ QStringLiteral("Kalshi.fetch_exchange_status"));+}++void KalshiRestClient::fetch_exchange_schedule() {+ QPointer<KalshiRestClient> self = this;+ get_json(QStringLiteral("/exchange/schedule"),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ emit self->exchange_schedule_ready(doc.object());+ },+ QStringLiteral("Kalshi.fetch_exchange_schedule"));+}++// ── Series metadata ────────────────────────────────────────────────────────++void KalshiRestClient::fetch_series_detail(const QString& series_ticker) {+ QPointer<KalshiRestClient> self = this;+ get_json(QStringLiteral("/series/") + series_ticker,+ [self](const QJsonDocument& doc) {+ if (!self) return;+ // Response is wrapped as { "series": {...} }; unwrap if present.+ const auto obj = doc.object();+ const auto inner = obj.value("series").toObject();+ emit self->series_detail_ready(inner.isEmpty() ? obj : inner);+ },+ QStringLiteral("Kalshi.fetch_series_detail"));+}++void KalshiRestClient::fetch_series_fee_changes() {+ QPointer<KalshiRestClient> self = this;+ get_json(QStringLiteral("/series/fee_changes"),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ // Response is { "fee_changes": [...] } — emit the array.+ emit self->series_fee_changes_ready(+ doc.object().value("fee_changes").toArray());+ },+ QStringLiteral("Kalshi.fetch_series_fee_changes"));+}++// ── Batch market candlesticks ──────────────────────────────────────────────++void KalshiRestClient::fetch_batch_candlesticks(const QStringList& tickers,+ int period_interval_min,+ qint64 start_ts, qint64 end_ts) {+ if (tickers.isEmpty()) {+ emit batch_candlesticks_ready({});+ return;+ }+ QUrlQuery q;+ q.addQueryItem("tickers", tickers.join(","));+ q.addQueryItem("period_interval", QString::number(period_interval_min));+ if (start_ts > 0) q.addQueryItem("start_ts", QString::number(start_ts));+ if (end_ts > 0) q.addQueryItem("end_ts", QString::number(end_ts));+ QUrl u(base_url() + QStringLiteral("/markets/candlesticks"));+ u.setQuery(q);++ QPointer<KalshiRestClient> self = this;+ get_json(u.toString(),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ QHash<QString, pr::PriceHistory> out;+ // Response: { "candlesticks_by_ticker": [ { ticker, candlesticks: [...] } ] }+ const auto arr = doc.object().value("candlesticks_by_ticker").toArray();+ for (const auto& v : arr) {+ const auto o = v.toObject();+ const QString t = o.value("ticker").toString();+ if (t.isEmpty()) continue;+ out.insert(t, parse_candlestick_history(+ o.value("candlesticks").toArray(),+ t + QStringLiteral(":yes")));+ }+ emit self->batch_candlesticks_ready(out);+ },+ QStringLiteral("Kalshi.fetch_batch_candlesticks"));+}++// ── Historical (public slice) ──────────────────────────────────────────────++void KalshiRestClient::fetch_historical_markets(const QString& series_ticker,+ int limit, const QString& cursor) {+ QUrlQuery q;+ if (!series_ticker.isEmpty()) q.addQueryItem("series_ticker", series_ticker);+ q.addQueryItem("limit", QString::number(qBound(1, limit, 1000)));+ if (!cursor.isEmpty()) q.addQueryItem("cursor", cursor);+ QUrl u(base_url() + QStringLiteral("/historical/markets"));+ u.setQuery(q);++ QPointer<KalshiRestClient> self = this;+ get_json(u.toString(),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ const auto obj = doc.object();+ QVector<pr::PredictionMarket> markets;+ const auto arr = obj.value("markets").toArray();+ markets.reserve(arr.size());+ for (const auto& v : arr) markets.push_back(parse_market(v.toObject()));+ emit self->historical_markets_ready(markets, obj.value("cursor").toString());+ },+ QStringLiteral("Kalshi.fetch_historical_markets"));+}++void KalshiRestClient::fetch_historical_candlesticks(const QString& ticker,+ int period_interval_min,+ qint64 start_ts, qint64 end_ts) {+ QUrlQuery q;+ q.addQueryItem("period_interval", QString::number(period_interval_min));+ if (start_ts > 0) q.addQueryItem("start_ts", QString::number(start_ts));+ if (end_ts > 0) q.addQueryItem("end_ts", QString::number(end_ts));+ QUrl u(base_url() + QStringLiteral("/historical/markets/") + ticker ++ QStringLiteral("/candlesticks"));+ u.setQuery(q);++ const QString ticker_copy = ticker;+ QPointer<KalshiRestClient> self = this;+ get_json(u.toString(),+ [self, ticker_copy](const QJsonDocument& doc) {+ if (!self) return;+ auto h = parse_candlestick_history(+ doc.object().value("candlesticks").toArray(),+ ticker_copy + QStringLiteral(":yes"));+ emit self->historical_candlesticks_ready(h, ticker_copy);+ },+ QStringLiteral("Kalshi.fetch_historical_candlesticks"));+}++void KalshiRestClient::fetch_historical_trades(const QString& ticker, int limit,+ const QString& cursor) {+ QUrlQuery q;+ if (!ticker.isEmpty()) q.addQueryItem("ticker", ticker);+ q.addQueryItem("limit", QString::number(qBound(1, limit, 1000)));+ if (!cursor.isEmpty()) q.addQueryItem("cursor", cursor);+ QUrl u(base_url() + QStringLiteral("/historical/trades"));+ u.setQuery(q);++ QPointer<KalshiRestClient> self = this;+ get_json(u.toString(),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ const auto obj = doc.object();+ QVector<pr::PredictionTrade> trades;+ const auto arr = obj.value("trades").toArray();+ trades.reserve(arr.size());+ for (const auto& v : arr) trades.push_back(parse_trade(v.toObject()));+ emit self->historical_trades_ready(trades, obj.value("cursor").toString());+ },+ QStringLiteral("Kalshi.fetch_historical_trades"));+}++// ── Search / filter metadata ───────────────────────────────────────────────++void KalshiRestClient::fetch_search_tags_by_categories() {+ QPointer<KalshiRestClient> self = this;+ get_json(QStringLiteral("/search/tags_by_categories"),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ emit self->search_tags_ready(doc.object());+ },+ QStringLiteral("Kalshi.fetch_search_tags_by_categories"));+}++void KalshiRestClient::fetch_search_filters_by_sport(const QString& sport) {+ QUrlQuery q;+ if (!sport.isEmpty()) q.addQueryItem("sport", sport);+ QUrl u(base_url() + QStringLiteral("/search/filters_by_sport"));+ u.setQuery(q);++ QPointer<KalshiRestClient> self = this;+ get_json(u.toString(),+ [self](const QJsonDocument& doc) {+ if (!self) return;+ emit self->search_filters_ready(doc.object());+ },+ QStringLiteral("Kalshi.fetch_search_filters_by_sport"));+}+} // namespace fincept::services::prediction::kalshi_nsdiff --git a/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.h b/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.hindex 092c1c87e..c9e333d54 100644--- a/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.h+++ b/fincept-qt/src/services/prediction/kalshi/KalshiRestClient.h@@ -2,6 +2,9 @@#include "services/prediction/PredictionTypes.h"+#include <QHash>+#include <QJsonArray>+#include <QJsonObject>#include <QObject>#include <QString>#include <QStringList>@@ -65,6 +68,48 @@ class KalshiRestClient : public QObject {void fetch_market_trades(const QString& ticker, int limit = 100,const QString& cursor = QString());+ // ── Exchange metadata ────────────────────────────────────────────────++ /// GET /exchange/status — is the exchange accepting trades right now.+ void fetch_exchange_status();+ /// GET /exchange/schedule — trading calendar.+ void fetch_exchange_schedule();++ // ── Series metadata ──────────────────────────────────────────────────++ /// GET /series/{series_ticker} — single series detail (fees, frequency).+ void fetch_series_detail(const QString& series_ticker);+ /// GET /series/fee_changes — upcoming fee adjustments.+ void fetch_series_fee_changes();++ // ── Batch market data ────────────────────────────────────────────────++ /// GET /markets/candlesticks — batched across tickers. Returns a map+ /// of ticker → PriceHistory.+ void fetch_batch_candlesticks(const QStringList& tickers, int period_interval_min,+ qint64 start_ts, qint64 end_ts);++ // ── Historical data (public slice) ───────────────────────────────────++ /// GET /historical/markets — archived markets, paginated.+ void fetch_historical_markets(const QString& series_ticker = QString(),+ int limit = 100,+ const QString& cursor = QString());+ /// GET /historical/markets/{ticker}/candlesticks — archived candles.+ void fetch_historical_candlesticks(const QString& ticker, int period_interval_min,+ qint64 start_ts, qint64 end_ts);+ /// GET /historical/trades — archived trade tape.+ void fetch_historical_trades(const QString& ticker = QString(),+ int limit = 100,+ const QString& cursor = QString());++ // ── Search / filter metadata ─────────────────────────────────────────++ /// GET /search/tags_by_categories — tag taxonomy for browse filters.+ void fetch_search_tags_by_categories();+ /// GET /search/filters_by_sport — sport-specific filter options.+ void fetch_search_filters_by_sport(const QString& sport);+signals:// Each signal carries (markets, cursor) so callers can paginate.void markets_ready(const QVector<fincept::services::prediction::PredictionMarket>& markets,@@ -81,6 +126,29 @@ class KalshiRestClient : public QObject {const QString& ticker);void trades_ready(const QVector<fincept::services::prediction::PredictionTrade>& trades);+ // Exchange / series / search metadata — raw JSON pass-through since+ // these are low-use endpoints without a frontend struct yet.+ void exchange_status_ready(const QJsonObject& status);+ void exchange_schedule_ready(const QJsonObject& schedule);+ void series_detail_ready(const QJsonObject& series);+ void series_fee_changes_ready(const QJsonArray& fee_changes);+ void search_tags_ready(const QJsonObject& tags_by_categories);+ void search_filters_ready(const QJsonObject& filters);++ // Batch candlesticks: map of ticker → history.+ void batch_candlesticks_ready(+ const QHash<QString, fincept::services::prediction::PriceHistory>& histories);++ // Historical (matches the live counterparts).+ void historical_markets_ready(+ const QVector<fincept::services::prediction::PredictionMarket>& markets,+ const QString& next_cursor);+ void historical_candlesticks_ready(+ const fincept::services::prediction::PriceHistory& history, const QString& ticker);+ void historical_trades_ready(+ const QVector<fincept::services::prediction::PredictionTrade>& trades,+ const QString& next_cursor);+void request_error(const QString& context, const QString& message);private:diff --git a/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.cpp b/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.cppindex 777264854..3165ebd9a 100644--- a/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.cpp+++ b/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.cpp@@ -6,6 +6,7 @@#include "datahub/TopicPolicy.h"#include "network/websocket/WebSocketClient.h"+#include <QDateTime>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>@@ -96,8 +97,16 @@ void KalshiWsClient::ensure_connected() {void KalshiWsClient::send_subscribe(const QStringList& tickers) {QJsonObject params;QJsonArray channels;+ // Kalshi v2 (Apr 2026):+ // - `ticker` is the current L1 channel (yes_bid_dollars, *_size_fp).+ // - `orderbook_delta` + `orderbook_snapshot` for L2 book state.+ // - `trade` streams the public trade tape.+ // - `market_lifecycle_v2` notifies when markets open/close/settle+ // (the v1 `market_lifecycle` channel has been superseded).channels.append("orderbook_delta");channels.append("ticker");+ channels.append("trade");+ channels.append("market_lifecycle_v2");params.insert("channels", channels);QJsonArray tarr;for (const auto& t : tickers) tarr.append(t);@@ -150,17 +159,11 @@ void KalshiWsClient::on_message(const QString& msg) {if (doc.isNull()) return;const auto obj = doc.object();const QString type = obj.value("type").toString();- if (type != QStringLiteral("orderbook_snapshot") &&- type != QStringLiteral("orderbook_delta") &&- type != QStringLiteral("ticker")) {- return;- }-const auto payload = obj.value("msg").toObject();const QString ticker = payload.value("market_ticker").toString();- if (ticker.isEmpty()) return;if (type == QStringLiteral("ticker")) {+ if (ticker.isEmpty()) return;const double yes_price = kalshi_fp_to_double(payload.value("yes_bid_dollars"));if (yes_price > 0) publish_price(ticker + QStringLiteral(":yes"), yes_price);const double no_price = kalshi_fp_to_double(payload.value("no_bid_dollars"));@@ -168,6 +171,40 @@ void KalshiWsClient::on_message(const QString& msg) {return;}+ if (type == QStringLiteral("trade")) {+ if (ticker.isEmpty()) return;+ pr::PredictionTrade t;+ t.asset_id = ticker + QStringLiteral(":yes");+ const QString ts_side = payload.value("taker_side").toString().toLower();+ t.side = (ts_side == QStringLiteral("no")) ? QStringLiteral("SELL")+ : QStringLiteral("BUY");+ t.price = kalshi_fp_to_double(payload.value("yes_price_dollars"));+ t.size = kalshi_fp_to_double(payload.value("count_fp"));+ const QString iso = payload.value("created_time").toString();+ t.ts_ms = iso.isEmpty()+ ? qint64(payload.value("ts").toVariant().toLongLong()) * 1000+ : QDateTime::fromString(iso, Qt::ISODate).toMSecsSinceEpoch();+ emit trade_received(t);+ fincept::datahub::DataHub::instance().publish(+ QStringLiteral("prediction:kalshi:trade:") + ticker,+ QVariant::fromValue(t));+ return;+ }++ if (type == QStringLiteral("market_lifecycle_v2") ||+ type == QStringLiteral("market_lifecycle")) {+ if (ticker.isEmpty()) return;+ const QString status = payload.value("status").toString();+ emit market_lifecycle_changed(ticker, status);+ return;+ }++ if (type != QStringLiteral("orderbook_snapshot") &&+ type != QStringLiteral("orderbook_delta")) {+ return;+ }+ if (ticker.isEmpty()) return;+// Snapshot / delta path — callers should rebuild their local book from// the snapshot then apply deltas. Phase 4 ships only the transport;// full reconciliation (seq gap detection, REST resnapshot) lands withdiff --git a/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.h b/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.hindex 85845c8ad..109c0b978 100644--- a/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.h+++ b/fincept-qt/src/services/prediction/kalshi/KalshiWsClient.h@@ -67,6 +67,8 @@ class KalshiWsClient : public QObject, public fincept::datahub::Producer {void price_updated(const QString& asset_id, double price);void orderbook_updated(const QString& asset_id,const fincept::services::prediction::PredictionOrderBook& book);+ void trade_received(const fincept::services::prediction::PredictionTrade& trade);+ void market_lifecycle_changed(const QString& ticker, const QString& status);void connection_status_changed(bool connected);private slots:diff --git a/fincept-qt/src/services/stt/SpeechService.cpp b/fincept-qt/src/services/stt/SpeechService.cppindex e0d3c75fb..b62588124 100644--- a/fincept-qt/src/services/stt/SpeechService.cpp+++ b/fincept-qt/src/services/stt/SpeechService.cpp@@ -1,18 +1,25 @@-// SpeechService.cpp — Python-based speech-to-text via Google Speech Recognition.+// SpeechService.cpp — Pluggable speech-to-text (Google or Deepgram).//-// Process lifecycle:-// start_listening() → spawn QProcess running speech_to_text.py-// stdout JSON lines → parse_line() → emit transcription_ready / error_occurred-// stop_listening() → kill QProcess+// Architecture:+// SpeechService (public facade)+// └── SttProvider (abstract)+// ├── PythonSttProvider (shared QProcess + JSON-lines plumbing)+// │ ├── GoogleSttProvider → scripts/voice/speech_to_text.py+// │ └── DeepgramSttProvider → scripts/voice/deepgram_stt.py//-// The Python script handles mic capture, ambient noise calibration, and-// Google API calls. This service just manages the process and parses output.+// Both providers share the same JSON-lines stdout protocol:+// {"status": "calibrating"|"listening"|"stopped"}+// {"text": "..."} → transcription+// {"error": "..."} → recoverable error+// {"fatal": "..."} → unrecoverable error (process exits)#include "services/stt/SpeechService.h"+#include "core/config/AppConfig.h"#include "core/logging/Logger.h"#include "python/PythonRunner.h"#include "python/PythonSetupManager.h"+#include "storage/secure/SecureStorage.h"#include <QFileInfo>#include <QJsonDocument>@@ -24,210 +31,339 @@ namespace fincept::services {static constexpr auto TAG = "SpeechService";static constexpr int kShutdownTimeoutMs = 2000;-// ── Singleton ────────────────────────────────────────────────────────────────+// ── PythonSttProvider (base) ─────────────────────────────────────────────────+//+// Shared plumbing for any STT provider implemented as a Python QProcess that+// emits JSON lines on stdout. Subclasses contribute script_path() and any+// extra environment variables via extend_environment().-SpeechService& SpeechService::instance() {- static SpeechService s_instance;- return s_instance;-}+namespace {-SpeechService::SpeechService(QObject* parent) : QObject(parent) {- LOG_INFO(TAG, "SpeechService initialised");-}+class PythonSttProvider : public SttProvider {+ public:+ using SttProvider::SttProvider;-SpeechService::~SpeechService() {- kill_process();-}+ void start() override {+ if (process_)+ return;-// ── Public API ───────────────────────────────────────────────────────────────+ QString python_exe = python::PythonSetupManager::instance().python_path("venv-numpy2");+ if (python_exe.isEmpty() || !QFileInfo::exists(python_exe))+ python_exe = python::PythonRunner::instance().python_path();-void SpeechService::start_listening() {- if (listening_.load(std::memory_order_relaxed))- return;- spawn_process();-}+ if (python_exe.isEmpty()) {+ emit fatal_error(QStringLiteral("Python not available — cannot start voice input"));+ return;+ }-void SpeechService::stop_listening() {- if (!listening_.load(std::memory_order_relaxed))- return;- kill_process();-}+ const QString script = script_path();+ if (!QFileInfo::exists(script)) {+ emit fatal_error(QStringLiteral("Voice script not found: ") + script);+ return;+ }-bool SpeechService::is_listening() const noexcept {- return listening_.load(std::memory_order_relaxed);-}+ process_ = new QProcess(this);-// ── Process management ───────────────────────────────────────────────────────+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();+ env.insert("PYTHONIOENCODING", "utf-8");+ env.insert("PYTHONDONTWRITEBYTECODE", "1");+ env.insert("PYTHONUNBUFFERED", "1");+ env.insert("FINCEPT_DATA_DIR", python::PythonSetupManager::instance().install_dir());-void SpeechService::spawn_process() {- if (process_) {- LOG_WARN(TAG, "Process already running — ignoring spawn request");- return;- }+ const QString scripts_dir = python::PythonRunner::instance().scripts_dir();+ const QString existing_pypath = env.value("PYTHONPATH");+#ifdef _WIN32+ const QChar kPathSep = ';';+#else+ const QChar kPathSep = ':';+#endif+ const QString new_pypath =+ existing_pypath.isEmpty() ? scripts_dir : (scripts_dir + kPathSep + existing_pypath);+ env.insert("PYTHONPATH", new_pypath);++ // Give subclass a chance to inject API keys / model / language+ extend_environment(env);- // Resolve the Python executable from the numpy2 venv- QString python_exe = python::PythonSetupManager::instance().python_path("venv-numpy2");- if (python_exe.isEmpty() || !QFileInfo::exists(python_exe)) {- // Fallback to PythonRunner's resolved path- python_exe = python::PythonRunner::instance().python_path();+ process_->setProcessEnvironment(env);+ process_->setWorkingDirectory(scripts_dir);++#ifdef _WIN32+ process_->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {+ cpa->flags |= 0x08000000; // CREATE_NO_WINDOW+ });+#endif++ connect(process_, &QProcess::readyReadStandardOutput, this, &PythonSttProvider::on_stdout_ready);+ connect(process_, &QProcess::finished, this, &PythonSttProvider::on_process_finished);+ connect(process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {+ if (err == QProcess::FailedToStart) {+ emit fatal_error(QStringLiteral("Failed to start voice recognition process"));+ stop();+ }+ });++ stdout_buffer_.clear();+ process_->start(python_exe, {script});++ active_.store(true, std::memory_order_release);+ LOG_INFO(TAG, QString("Voice provider '%1' started").arg(name()));+ emit active_changed(true);}- if (python_exe.isEmpty()) {- const QString msg = QStringLiteral("Python not available — cannot start voice input");- LOG_ERROR(TAG, msg);- emit error_occurred(msg);- return;++ void stop() override {+ if (!process_)+ return;++ disconnect(process_, nullptr, this, nullptr);++ if (process_->state() != QProcess::NotRunning) {+ process_->kill();+ process_->waitForFinished(kShutdownTimeoutMs);+ }+ process_->deleteLater();+ process_ = nullptr;+ stdout_buffer_.clear();++ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active) {+ LOG_INFO(TAG, QString("Voice provider '%1' stopped").arg(name()));+ emit active_changed(false);+ }}- // Resolve script path- const QString scripts_dir = python::PythonRunner::instance().scripts_dir();- const QString script_path = scripts_dir + QStringLiteral("/voice/speech_to_text.py");- if (!QFileInfo::exists(script_path)) {- const QString msg = QStringLiteral("Voice script not found: ") + script_path;- LOG_ERROR(TAG, msg);- emit error_occurred(msg);- return;+ [[nodiscard]] bool is_active() const noexcept override {+ return active_.load(std::memory_order_relaxed);}- process_ = new QProcess(this);+ protected:+ /// Absolute path to the Python script that implements the JSON-lines protocol.+ virtual QString script_path() const = 0;- // Environment setup — match PythonRunner's env for consistency- QProcessEnvironment env = QProcessEnvironment::systemEnvironment();- env.insert("PYTHONIOENCODING", "utf-8");- env.insert("PYTHONDONTWRITEBYTECODE", "1");- env.insert("PYTHONUNBUFFERED", "1");- env.insert("FINCEPT_DATA_DIR", python::PythonSetupManager::instance().install_dir());+ /// Hook for subclasses to add API keys / model / language etc. to the+ /// child process environment. Default: no extra vars.+ virtual void extend_environment(QProcessEnvironment& /*env*/) const {}- const QString existing_pypath = env.value("PYTHONPATH");-#ifdef _WIN32- const QChar kPathSep = ';';-#else- const QChar kPathSep = ':';-#endif- const QString new_pypath =- existing_pypath.isEmpty() ? scripts_dir : (scripts_dir + kPathSep + existing_pypath);- env.insert("PYTHONPATH", new_pypath);+ private:+ void on_stdout_ready() {+ if (!process_)+ return;- process_->setProcessEnvironment(env);- process_->setWorkingDirectory(scripts_dir);+ stdout_buffer_.append(process_->readAllStandardOutput());-#ifdef _WIN32- process_->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {- cpa->flags |= 0x08000000; // CREATE_NO_WINDOW- });-#endif+ while (true) {+ const int newline_pos = stdout_buffer_.indexOf('\n');+ if (newline_pos < 0)+ break;++ const QByteArray line = stdout_buffer_.left(newline_pos).trimmed();+ stdout_buffer_.remove(0, newline_pos + 1);- connect(process_, &QProcess::readyReadStandardOutput, this, &SpeechService::on_stdout_ready);- connect(process_, &QProcess::finished, this, &SpeechService::on_process_finished);- connect(process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {- if (err == QProcess::FailedToStart) {- const QString msg = QStringLiteral("Failed to start voice recognition process");- LOG_ERROR(TAG, msg);- emit error_occurred(msg);- kill_process();+ if (!line.isEmpty())+ parse_line(line);}- });+ }- stdout_buffer_.clear();- process_->start(python_exe, {script_path});+ void parse_line(const QByteArray& line) {+ QJsonParseError parse_err;+ const QJsonDocument doc = QJsonDocument::fromJson(line, &parse_err);+ if (parse_err.error != QJsonParseError::NoError) {+ LOG_WARN(TAG, QString("Non-JSON stdout line: %1").arg(QString::fromUtf8(line)));+ return;+ }- listening_.store(true, std::memory_order_release);- LOG_INFO(TAG, "Voice recognition process started");- emit listening_changed(true);-}+ const QJsonObject obj = doc.object();++ if (obj.contains("text")) {+ const QString text = obj["text"].toString().trimmed();+ if (!text.isEmpty()) {+ LOG_DEBUG(TAG, QString("Transcript: \"%1\"").arg(text));+ emit transcription(text);+ }+ } else if (obj.contains("error")) {+ const QString msg = obj["error"].toString();+ LOG_WARN(TAG, QString("STT error: %1").arg(msg));+ emit error(msg);+ } else if (obj.contains("fatal")) {+ const QString msg = obj["fatal"].toString();+ LOG_ERROR(TAG, QString("STT fatal: %1").arg(msg));+ emit fatal_error(msg);+ stop();+ } else if (obj.contains("status")) {+ const QString status = obj["status"].toString();+ LOG_DEBUG(TAG, QString("STT status: %1").arg(status));+ }+ }-void SpeechService::kill_process() {- if (!process_)- return;+ void on_process_finished(int exit_code, QProcess::ExitStatus status) {+ LOG_INFO(TAG, QString("Voice provider '%1' process exited (code=%2, status=%3)")+ .arg(name())+ .arg(exit_code)+ .arg(status == QProcess::CrashExit ? "crash" : "normal"));++ if (process_) {+ process_->deleteLater();+ process_ = nullptr;+ }+ stdout_buffer_.clear();- // Disconnect signals before killing to avoid spurious callbacks- disconnect(process_, nullptr, this, nullptr);+ const bool was_active = active_.exchange(false, std::memory_order_acq_rel);+ if (was_active) {+ emit active_changed(false);+ if (status == QProcess::CrashExit || exit_code != 0)+ emit error(QStringLiteral("Voice recognition stopped unexpectedly"));+ }+ }++ QProcess* process_ = nullptr;+ QByteArray stdout_buffer_;+ std::atomic<bool> active_{false};+};++// ── GoogleSttProvider ────────────────────────────────────────────────────────+//+// Unauth'd Google Web Speech via Python `speech_recognition`. No API key.++class GoogleSttProvider final : public PythonSttProvider {+ public:+ using PythonSttProvider::PythonSttProvider;++ QString name() const override { return QStringLiteral("google"); }++ protected:+ QString script_path() const override {+ return python::PythonRunner::instance().scripts_dir() ++ QStringLiteral("/voice/speech_to_text.py");+ }+};++// ── DeepgramSttProvider ──────────────────────────────────────────────────────+//+// Deepgram live WebSocket STT via Python `deepgram-sdk`. Reads API key from+// SecureStorage (key "voice.deepgram.api_key"). Model/language/keyterms come+// from AppConfig.++class DeepgramSttProvider final : public PythonSttProvider {+ public:+ using PythonSttProvider::PythonSttProvider;- if (process_->state() != QProcess::NotRunning) {- process_->kill();- process_->waitForFinished(kShutdownTimeoutMs);+ QString name() const override { return QStringLiteral("deepgram"); }++ protected:+ QString script_path() const override {+ return python::PythonRunner::instance().scripts_dir() ++ QStringLiteral("/voice/deepgram_stt.py");}- process_->deleteLater();- process_ = nullptr;- stdout_buffer_.clear();-- const bool was_listening = listening_.exchange(false, std::memory_order_acq_rel);- if (was_listening) {- LOG_INFO(TAG, "Voice recognition process stopped");- emit listening_changed(false);++ void extend_environment(QProcessEnvironment& env) const override {+ auto key_res = SecureStorage::instance().retrieve(QStringLiteral("voice.deepgram.api_key"));+ const QString api_key = key_res.is_ok() ? key_res.value() : QString();+ env.insert("DEEPGRAM_API_KEY", api_key);++ auto& cfg = AppConfig::instance();+ env.insert("FINCEPT_STT_MODEL", cfg.get("voice/deepgram/model", "nova-3").toString());+ env.insert("FINCEPT_STT_LANGUAGE", cfg.get("voice/deepgram/language", "en").toString());+ env.insert("FINCEPT_STT_KEYTERMS", cfg.get("voice/deepgram/keyterms", "").toString());}+};++} // namespace++// ── Singleton ────────────────────────────────────────────────────────────────++SpeechService& SpeechService::instance() {+ static SpeechService s_instance;+ return s_instance;}-// ── stdout parsing ───────────────────────────────────────────────────────────+SpeechService::SpeechService(QObject* parent) : QObject(parent) {+ LOG_INFO(TAG, "SpeechService initialised");+}-void SpeechService::on_stdout_ready() {- if (!process_)- return;+SpeechService::~SpeechService() {+ teardown_provider();+}- stdout_buffer_.append(process_->readAllStandardOutput());+// ── Public API ───────────────────────────────────────────────────────────────- // Process complete lines (JSON-lines protocol)- while (true) {- const int newline_pos = stdout_buffer_.indexOf('\n');- if (newline_pos < 0)- break;+QString SpeechService::configured_provider() {+ const QString v = AppConfig::instance().get("voice/provider", "google").toString().toLower();+ return (v == "deepgram") ? QStringLiteral("deepgram") : QStringLiteral("google");+}- const QByteArray line = stdout_buffer_.left(newline_pos).trimmed();- stdout_buffer_.remove(0, newline_pos + 1);+void SpeechService::start_listening() {+ if (listening_.load(std::memory_order_relaxed))+ return;- if (!line.isEmpty())- parse_line(line);- }+ install_provider();+ if (!provider_)+ return;++ provider_->start();}-void SpeechService::parse_line(const QByteArray& line) {- QJsonParseError parse_err;- const QJsonDocument doc = QJsonDocument::fromJson(line, &parse_err);- if (parse_err.error != QJsonParseError::NoError) {- LOG_WARN(TAG, QString("Non-JSON stdout line: %1").arg(QString::fromUtf8(line)));+void SpeechService::stop_listening() {+ if (!listening_.load(std::memory_order_relaxed))return;- }+ if (provider_)+ provider_->stop();+}- const QJsonObject obj = doc.object();+void SpeechService::reload_config() {+ const bool was_listening = listening_.load(std::memory_order_relaxed);- if (obj.contains("text")) {- const QString text = obj["text"].toString().trimmed();- if (!text.isEmpty()) {- LOG_DEBUG(TAG, QString("Transcript: \"%1\"").arg(text));- emit transcription_ready(text);- }- } else if (obj.contains("error")) {- const QString msg = obj["error"].toString();- LOG_WARN(TAG, QString("STT error: %1").arg(msg));- emit error_occurred(msg);- } else if (obj.contains("fatal")) {- const QString msg = obj["fatal"].toString();- LOG_ERROR(TAG, QString("STT fatal: %1").arg(msg));- emit error_occurred(msg);- kill_process();- } else if (obj.contains("status")) {- const QString status = obj["status"].toString();- LOG_DEBUG(TAG, QString("STT status: %1").arg(status));+ if (was_listening && provider_)+ provider_->stop();++ // install_provider() compares names — if the provider id didn't change,+ // the same instance is kept (and will re-read env on next start(), which+ // picks up any Deepgram API-key / model / language / keyterms changes).+ install_provider();++ if (was_listening && provider_) {+ LOG_INFO(TAG, "Voice config reloaded — restarting active session");+ provider_->start();+ } else {+ LOG_INFO(TAG, "Voice config reloaded (idle)");}}-void SpeechService::on_process_finished(int exit_code, QProcess::ExitStatus status) {- LOG_INFO(TAG, QString("Voice process exited (code=%1, status=%2)")- .arg(exit_code)- .arg(status == QProcess::CrashExit ? "crash" : "normal"));+bool SpeechService::is_listening() const noexcept {+ return listening_.load(std::memory_order_relaxed);+}++// ── Provider lifecycle ───────────────────────────────────────────────────────- if (process_) {- process_->deleteLater();- process_ = nullptr;- }- stdout_buffer_.clear();+void SpeechService::install_provider() {+ const QString id = configured_provider();- const bool was_listening = listening_.exchange(false, std::memory_order_acq_rel);- if (was_listening) {- emit listening_changed(false);- if (status == QProcess::CrashExit || exit_code != 0) {- emit error_occurred(QStringLiteral("Voice recognition stopped unexpectedly"));- }- }+ // If an existing provider matches the selection, reuse it.+ if (provider_ && provider_->name() == id)+ return;++ teardown_provider();++ if (id == QStringLiteral("deepgram"))+ provider_ = std::make_unique<DeepgramSttProvider>(this);+ else+ provider_ = std::make_unique<GoogleSttProvider>(this);++ connect(provider_.get(), &SttProvider::transcription, this, &SpeechService::transcription_ready);+ connect(provider_.get(), &SttProvider::error, this, &SpeechService::error_occurred);+ connect(provider_.get(), &SttProvider::fatal_error, this, &SpeechService::error_occurred);+ connect(provider_.get(), &SttProvider::active_changed, this, [this](bool active) {+ listening_.store(active, std::memory_order_release);+ emit listening_changed(active);+ });++ LOG_INFO(TAG, QString("Voice provider selected: %1").arg(id));+}++void SpeechService::teardown_provider() {+ if (!provider_)+ return;+ provider_->stop();+ disconnect(provider_.get(), nullptr, this, nullptr);+ provider_.reset();}} // namespace fincept::servicesdiff --git a/fincept-qt/src/services/stt/SpeechService.h b/fincept-qt/src/services/stt/SpeechService.hindex 62d66d7a7..72af131ec 100644--- a/fincept-qt/src/services/stt/SpeechService.h+++ b/fincept-qt/src/services/stt/SpeechService.h@@ -1,11 +1,13 @@#pragma once-// SpeechService.h — Speech-to-text via Python speech_recognition + Google API.+// SpeechService.h — Speech-to-text with pluggable provider backend.//// Architecture:-// • start_listening() spawns scripts/voice/speech_to_text.py as a QProcess-// • Python script captures mic audio, sends to Google STT-// • Results stream back as JSON lines on stdout-// • stop_listening() kills the process+// • Public API unchanged: start_listening() / stop_listening() / signals.+// • Internally selects a provider (Google or Deepgram) based on AppConfig+// key "voice/provider" (default: "google"). Each provider spawns its own+// Python script as a long-running QProcess using the same JSON-lines+// stdout protocol ({status|text|error|fatal}).+// • AiChatBubble never sees the provider — it only sees the three signals.//// Complies with P1 (never block UI), P6 (service layer), P15 (thread safety).// Uses its own QProcess (not PythonRunner) because PythonRunner is designed@@ -14,12 +16,35 @@#include <QObject>#include <QProcess>+#include <QProcessEnvironment>#include <QString>#include <atomic>+#include <memory>namespace fincept::services {+/// Abstract base for STT providers. Both providers share the Python-QProcess+/// + JSON-lines parsing plumbing; subclasses only contribute the script path+/// and any extra environment variables (e.g. API keys, model).+class SttProvider : public QObject {+ Q_OBJECT+ public:+ explicit SttProvider(QObject* parent = nullptr) : QObject(parent) {}+ ~SttProvider() override = default;++ virtual void start() = 0;+ virtual void stop() = 0;+ [[nodiscard]] virtual bool is_active() const noexcept = 0;+ [[nodiscard]] virtual QString name() const = 0;++ signals:+ void transcription(const QString& text);+ void error(const QString& message);+ void fatal_error(const QString& message);+ void active_changed(bool active);+};+class SpeechService : public QObject {Q_OBJECT@@ -32,8 +57,18 @@ class SpeechService : public QObject {void start_listening();void stop_listening();+ /// Picks up a new provider selection or Deepgram settings immediately.+ /// If currently listening, stops the active session and restarts with+ /// the new provider. If idle, just swaps the provider so the next+ /// start_listening() uses it. Safe to call at any time.+ void reload_config();+[[nodiscard]] bool is_listening() const noexcept;+ /// Returns the currently active provider id ("google" or "deepgram").+ /// Reads AppConfig; does not reflect in-flight state.+ [[nodiscard]] static QString configured_provider();+signals:/// Fired on the UI thread with the transcribed text.void transcription_ready(const QString& text);@@ -48,14 +83,10 @@ class SpeechService : public QObject {explicit SpeechService(QObject* parent = nullptr);~SpeechService() override;- void spawn_process();- void kill_process();- void on_stdout_ready();- void on_process_finished(int exit_code, QProcess::ExitStatus status);- void parse_line(const QByteArray& line);+ void install_provider();+ void teardown_provider();- QProcess* process_ = nullptr;- QByteArray stdout_buffer_;+ std::unique_ptr<SttProvider> provider_;std::atomic<bool> listening_{false};};diff --git a/fincept-qt/src/services/updater/UpdateService.h b/fincept-qt/src/services/updater/UpdateService.hindex bea79acf5..675f19ebb 100644--- a/fincept-qt/src/services/updater/UpdateService.h+++ b/fincept-qt/src/services/updater/UpdateService.h@@ -19,7 +19,7 @@ namespace fincept::services {/// Manifest schema (see updates.json):/// {/// "updates": {-/// "windows-x64": { "latest-version": "4.0.2", "download-url": "...", "sha256": "...", "open-url": "...", "changelog": "..." },+/// "windows-x64": { "latest-version": "4.0.1", "download-url": "...", "sha256": "...", "open-url": "...", "changelog": "..." },/// "windows-arm64":{ ... },/// "linux-x64": { ... },/// "macos-arm64": { ... },diff --git a/fincept-qt/src/trading/ExchangeDaemonPool.cpp b/fincept-qt/src/trading/ExchangeDaemonPool.cppnew file mode 100644index 000000000..f93b670d5--- /dev/null+++ b/fincept-qt/src/trading/ExchangeDaemonPool.cpp@@ -0,0 +1,254 @@+#include "trading/ExchangeDaemonPool.h"++#include "core/logging/Logger.h"+#include "python/PythonRunner.h"++#include <QCoreApplication>+#include <QCryptographicHash>+#include <QJsonDocument>+#include <QMutexLocker>+#include <QThread>+#include <QTimer>++namespace fincept::trading {++namespace {+const QString kPoolTag = "ExchangeDaemonPool";++QString pool_resolve_script_path(const QString& relative) {+ const QString dir = fincept::python::PythonRunner::instance().scripts_dir();+ if (dir.isEmpty())+ return {};+ return dir + "/" + relative;+}+} // namespace++ExchangeDaemonPool& ExchangeDaemonPool::instance() {+ static ExchangeDaemonPool s;+ return s;+}++ExchangeDaemonPool::ExchangeDaemonPool() {+ // Pre-warm on a deferred tick so PythonRunner has finished first-run init+ // before we try to resolve its python/scripts paths.+ QTimer::singleShot(0, this, [this]() { start(); });+}++ExchangeDaemonPool::~ExchangeDaemonPool() {+ stop();+}++void ExchangeDaemonPool::start() {+ if (process_ && process_->state() == QProcess::Running)+ return;++ const QString python_path = python::PythonRunner::instance().python_path();+ const QString script_path = pool_resolve_script_path("exchange/exchange_daemon.py");+ if (python_path.isEmpty() || script_path.isEmpty()) {+ LOG_WARN(kPoolTag,"Cannot start daemon: python or exchange_daemon.py not found");+ return;+ }++ process_ = new QProcess(this);+ process_->setProcessChannelMode(QProcess::SeparateChannels);++ connect(process_, &QProcess::readyReadStandardOutput, this, &ExchangeDaemonPool::drain_buffer);+ connect(process_, &QProcess::readyReadStandardError, this, [this]() {+ if (!process_)+ return;+ const QString err = QString::fromUtf8(process_->readAllStandardError()).trimmed();+ if (!err.isEmpty())+ LOG_DEBUG(kPoolTag, "Daemon stderr: " + err);+ });+ connect(process_, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,+ [this](int code, QProcess::ExitStatus status) {+ LOG_WARN(kPoolTag,QString("Daemon exited (code=%1, status=%2)").arg(code).arg(status));+ ready_ = false;+ if (process_) {+ process_->deleteLater();+ process_ = nullptr;+ }+ // Creds must be re-sent after restart because the daemon+ // has forgotten them with the interpreter.+ QMutexLocker lock(&mutex_);+ creds_sent_.clear();+ });++ QStringList args;+ args << "-u" << "-B" << script_path;+ process_->start(python_path, args);+ LOG_INFO(kPoolTag,"Exchange daemon starting...");+}++void ExchangeDaemonPool::stop() {+ if (!process_)+ return;+ ready_ = false;+ process_->closeWriteChannel();+ auto* proc = process_;+ process_ = nullptr;+ connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), proc, &QObject::deleteLater);+ QTimer::singleShot(2000, proc, [proc]() {+ if (proc->state() != QProcess::NotRunning)+ proc->kill();+ });+}++bool ExchangeDaemonPool::wait_for_ready(int timeout_ms) {+ if (ready_.load())+ return true;++ // Kick start from the owner thread if nothing is running yet.+ if (!process_) {+ if (QThread::currentThread() == thread()) {+ start();+ } else {+ QMetaObject::invokeMethod(this, [this]() { start(); }, Qt::QueuedConnection);+ }+ }++ QMutexLocker lock(&mutex_);+ QElapsedTimer elapsed;+ elapsed.start();+ while (!ready_.load() && elapsed.elapsed() < timeout_ms) {+ const int remaining = timeout_ms - static_cast<int>(elapsed.elapsed());+ response_ready_.wait(&mutex_, std::max(remaining, 50));+ }+ return ready_.load();+}++QString ExchangeDaemonPool::credential_fingerprint(const ExchangeCredentials& creds) {+ if (creds.api_key.isEmpty() && creds.secret.isEmpty() && creds.password.isEmpty())+ return {};+ QCryptographicHash hash(QCryptographicHash::Sha256);+ hash.addData(creds.api_key.toUtf8());+ hash.addData("|");+ hash.addData(creds.secret.toUtf8());+ hash.addData("|");+ hash.addData(creds.password.toUtf8());+ return QString::fromLatin1(hash.result().toHex().left(16));+}++void ExchangeDaemonPool::forget_credentials(const QString& exchange) {+ QMutexLocker lock(&mutex_);+ creds_sent_.remove(exchange);+}++void ExchangeDaemonPool::send_credentials_if_needed(const QString& exchange, const ExchangeCredentials& creds) {+ // Caller must hold no locks. Runs on the owner thread only.+ const QString fp = credential_fingerprint(creds);+ if (fp.isEmpty())+ return;+ {+ QMutexLocker lock(&mutex_);+ if (creds_sent_.value(exchange) == fp)+ return;+ creds_sent_[exchange] = fp;+ }+ if (!process_)+ return;+ QJsonObject c;+ c["api_key"] = creds.api_key;+ c["secret"] = creds.secret;+ if (!creds.password.isEmpty())+ c["password"] = creds.password;+ QJsonObject req;+ req["id"] = "__creds_" + exchange + "_" + fp;+ req["method"] = "set_credentials";+ req["exchange"] = exchange;+ req["args"] = c;+ process_->write(QJsonDocument(req).toJson(QJsonDocument::Compact) + "\n");+}++void ExchangeDaemonPool::drain_buffer() {+ if (!process_)+ return;+ while (process_->canReadLine()) {+ const QString line = QString::fromUtf8(process_->readLine()).trimmed();+ if (line.isEmpty() || line[0] != '{')+ continue;+ QJsonParseError err;+ const auto doc = QJsonDocument::fromJson(line.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError)+ continue;+ const auto obj = doc.object();+ const QString id = obj.value("id").toString();++ if (id == "__init__") {+ ready_ = true;+ LOG_INFO(kPoolTag,"Exchange daemon ready (pid=" ++ obj.value("data").toObject().value("pid").toVariant().toString() + ")");+ response_ready_.wakeAll();+ emit ready();+ continue;+ }++ // Ignore credential-ack replies — they carry no caller.+ if (id.startsWith("__creds_"))+ continue;++ {+ QMutexLocker lock(&mutex_);+ responses_[id] = obj;+ }+ response_ready_.wakeAll();+ }+}++QJsonObject ExchangeDaemonPool::call(const QString& exchange,+ const QString& method,+ const QJsonObject& args,+ const ExchangeCredentials& credentials,+ int timeout_ms) {+ if (!ready_.load()) {+ if (!wait_for_ready(std::min(timeout_ms, 8000))) {+ LOG_WARN(kPoolTag,QString("Daemon not ready for %1/%2").arg(exchange, method));+ return {{"error", "Daemon not ready"}};+ }+ }++ const QString req_id = QString("r_%1").arg(next_req_id_.fetch_add(1));+ QJsonObject req;+ req["id"] = req_id;+ req["method"] = method;+ req["exchange"] = exchange;+ req["args"] = args;+ const QByteArray payload = QJsonDocument(req).toJson(QJsonDocument::Compact) + "\n";++ // Marshal the write + any credential send to the owner thread. Returns+ // immediately — the worker then blocks on the response wait below.+ QMetaObject::invokeMethod(+ this,+ [this, exchange, credentials, payload]() {+ if (!process_)+ return;+ send_credentials_if_needed(exchange, credentials);+ process_->write(payload);+ },+ Qt::QueuedConnection);++ QMutexLocker lock(&mutex_);+ QElapsedTimer elapsed;+ elapsed.start();+ while (elapsed.elapsed() < timeout_ms) {+ auto it = responses_.find(req_id);+ if (it != responses_.end()) {+ const QJsonObject resp = it.value();+ responses_.erase(it);+ lock.unlock();+ // Unwrap {"success":true,"data":{...}} when the data is an object.+ if (resp.value("success").toBool(false) && resp.contains("data")) {+ const auto d = resp.value("data");+ if (d.isObject())+ return d.toObject();+ }+ return resp;+ }+ response_ready_.wait(&mutex_, 50);+ }+ lock.unlock();+ LOG_WARN(kPoolTag,QString("Daemon call timed out: %1/%2").arg(exchange, method));+ return {{"error", QString("Daemon call timed out: %1/%2").arg(exchange, method)}};+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeDaemonPool.h b/fincept-qt/src/trading/ExchangeDaemonPool.hnew file mode 100644index 000000000..1a455eb0a--- /dev/null+++ b/fincept-qt/src/trading/ExchangeDaemonPool.h@@ -0,0 +1,98 @@+#pragma once+// ExchangeDaemonPool — shared persistent ccxt daemon (Phase 1 of multi-broker refactor).+//+// Owns the single long-running `exchange_daemon.py` subprocess that serves+// ccxt requests for every exchange id. Keeping one daemon (not one per+// exchange) matches the daemon's own design — each JSON request carries an+// `"exchange"` field, and the daemon reuses the imported `ccxt` module across+// calls, paying the 600–1200ms import cost exactly once per app run.+//+// This class is intentionally exchange-agnostic: callers pass the exchange+// id and credentials per call, so multiple `ExchangeSession` instances can+// share one daemon without stepping on each other.+//+// Threading model: the `QProcess` lives on the thread that created the+// singleton (the main thread via `instance()`). Worker threads call `call()`+// synchronously; writes are marshalled to the owner thread via+// `QMetaObject::invokeMethod(Qt::QueuedConnection)` and responses are+// delivered back through a `QWaitCondition`.++#include "trading/TradingTypes.h"++#include <QElapsedTimer>+#include <QHash>+#include <QJsonObject>+#include <QMutex>+#include <QObject>+#include <QProcess>+#include <QWaitCondition>++#include <atomic>++namespace fincept::trading {++class ExchangeDaemonPool : public QObject {+ Q_OBJECT+ public:+ static ExchangeDaemonPool& instance();++ /// Non-blocking start. Caller may hook `ready()` or call `wait_for_ready()`+ /// from a worker thread. Safe to call multiple times — no-op if already+ /// running.+ void start();++ /// Graceful shutdown — closes stdin, kills after 2s if still alive.+ void stop();++ /// Blocking wait on a worker thread. Returns true if daemon is ready+ /// before `timeout_ms`. NEVER call from the UI thread (P1) — this blocks.+ bool wait_for_ready(int timeout_ms = 8000);++ /// Snapshot state query.+ bool is_ready() const { return ready_.load(); }++ /// Synchronous RPC. Call from a worker thread only (may block up to+ /// `timeout_ms`). Returns the daemon's reply object verbatim — caller+ /// checks `success`/`error` fields per the daemon protocol.+ ///+ /// `exchange` is the ccxt id (e.g. "kraken"). `credentials`, if set, are+ /// sent to the daemon once per `(exchange, credentials-fingerprint)`+ /// pair — passing the same creds on later calls is free.+ QJsonObject call(const QString& exchange,+ const QString& method,+ const QJsonObject& args,+ const ExchangeCredentials& credentials = {},+ int timeout_ms = 15000);++ /// Drop cached credential-sent state for a given exchange — use this+ /// after an API-key rotation so the next `call()` re-sends creds.+ void forget_credentials(const QString& exchange);++ ExchangeDaemonPool(const ExchangeDaemonPool&) = delete;+ ExchangeDaemonPool& operator=(const ExchangeDaemonPool&) = delete;++ signals:+ /// Emitted (from the owner thread) when the daemon's `__init__` line+ /// arrives. Useful for screens that want to fire opening fetches only+ /// after the daemon is warm.+ void ready();++ private:+ ExchangeDaemonPool();+ ~ExchangeDaemonPool();++ void drain_buffer();+ void send_credentials_if_needed(const QString& exchange, const ExchangeCredentials& creds);+ static QString credential_fingerprint(const ExchangeCredentials& creds);++ QProcess* process_ = nullptr;+ std::atomic<bool> ready_{false};+ std::atomic<int> next_req_id_{0};++ QMutex mutex_; // guards responses_ + creds_sent_+ QWaitCondition response_ready_; // signalled when any response arrives+ QHash<QString, QJsonObject> responses_; // id -> full response obj+ QHash<QString, QString> creds_sent_; // exchange_id -> fingerprint of last-sent creds+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeService.cpp b/fincept-qt/src/trading/ExchangeService.cppindex e124a645d..53f91d63d 100644--- a/fincept-qt/src/trading/ExchangeService.cpp+++ b/fincept-qt/src/trading/ExchangeService.cpp@@ -1,59 +1,27 @@-// ExchangeService — Bridge between Python ccxt and C++ paper trading engine-// Uses QProcess for subprocess management+// ExchangeService — facade over ExchangeSessionManager (Phase 2).+//+// See header for design notes. This file intentionally contains no WS /+// daemon / cache state of its own — every non-trivial call is a one-line+// forward to the active session.#include "trading/ExchangeService.h"-#include "core/events/EventBus.h"#include "core/logging/Logger.h"-#include "python/PythonRunner.h"-#include "trading/BrokerRegistry.h"+#include "trading/ExchangeDaemonPool.h"+#include "trading/ExchangeSession.h"+#include "trading/ExchangeSessionManager.h"#include "trading/OrderMatcher.h"#include "trading/PaperTrading.h"-# include "datahub/DataHub.h"-# include "datahub/DataHubMetaTypes.h"--#include <QCoreApplication>-#include <QJsonArray>-#include <QJsonDocument>#include <QMutexLocker>-#include <QThread>+#include <QPointer>#include <QtConcurrent/QtConcurrent>-// Adapter: PythonRunner uses scripts_dir(), not resolve_script()-namespace {-QString resolve_script_path(const QString& relative) {- QString dir = fincept::python::PythonRunner::instance().scripts_dir();- if (dir.isEmpty())- return {};- return dir + "/" + relative;-}--bool is_broker_stream(const QString& id) {- return fincept::trading::BrokerRegistry::instance().has(id);-}--QStringList to_broker_symbol_args(const QStringList& symbols) {- QStringList out;- out.reserve(symbols.size());- for (const auto& s : symbols) {- QString sym = s.trimmed();- if (sym.isEmpty())- continue;- QString exchange = "NSE";- if (sym.contains(':')) {- exchange = sym.section(':', 0, 0).trimmed().toUpper();- sym = sym.section(':', 1).trimmed();- }- out << (sym + ":" + exchange + ":0");- }- return out;-}-} // anonymous namespace-namespace fincept::trading {-static const QString TAG = "ExchangeService";+namespace {+const QString kServiceTag = "ExchangeService";+} // namespace// ============================================================================// Singleton@@ -68,29 +36,47 @@ ExchangeService::ExchangeService() {feed_timer_ = new QTimer(this);connect(feed_timer_, &QTimer::timeout, this, &ExchangeService::poll_prices);- // Pre-warm daemon in background so it's ready by the time the user opens Crypto Trading.- // QTimer::singleShot(0) defers until after QApplication::exec() is running so PythonRunner- // is fully initialised before we spawn the daemon process.- QTimer::singleShot(0, this, [this]() {- if (!is_daemon_running())- start_daemon();- });+ // Re-emit the pool's ready() signal as our own daemon_ready() so existing+ // consumers (e.g. CryptoTradingScreen) need no changes.+ connect(&ExchangeDaemonPool::instance(), &ExchangeDaemonPool::ready, this,+ [this]() { emit daemon_ready(); });}ExchangeService::~ExchangeService() {- stop_ws_stream();- stop_price_feed();- stop_daemon();+ // Session lifecycles are owned by ExchangeSessionManager. Nothing to do.+ if (feed_timer_)+ feed_timer_->stop();+}++// ============================================================================+// Session resolution+// ============================================================================++ExchangeSession* ExchangeService::active_session() const {+ QString id;+ {+ QMutexLocker lock(&mutex_);+ id = exchange_id_;+ }+ return ExchangeSessionManager::instance().session(id);}// ============================================================================// Configuration// ============================================================================+void ExchangeService::ensure_registered_with_hub() {+ ExchangeSessionManager::instance().ensure_registered_with_hub();+}+void ExchangeService::set_exchange(const QString& exchange_id) {- QMutexLocker lock(&mutex_);- exchange_id_ = exchange_id;- LOG_INFO(TAG, "Exchange set to: " + exchange_id);+ {+ QMutexLocker lock(&mutex_);+ exchange_id_ = exchange_id;+ }+ // Touch the session so it exists by the time subsequent calls arrive.+ ExchangeSessionManager::instance().session(exchange_id);+ LOG_INFO(kServiceTag, "Exchange set to: " + exchange_id);}QString ExchangeService::get_exchange() const {@@ -99,9 +85,11 @@ QString ExchangeService::get_exchange() const {}void ExchangeService::set_credentials(const ExchangeCredentials& creds) {- QMutexLocker lock(&mutex_);- credentials_ = creds;- credentials_sent_to_daemon_ = false; // Will be sent on next daemon_call()+ active_session()->set_credentials(creds);+}++bool ExchangeService::wait_for_daemon_ready(int timeout_ms) {+ return ExchangeDaemonPool::instance().wait_for_ready(timeout_ms);}// ============================================================================@@ -109,29 +97,22 @@ void ExchangeService::set_credentials(const ExchangeCredentials& creds) {// ============================================================================void ExchangeService::watch_symbol(const QString& symbol, const QString& portfolio_id) {- QMutexLocker lock(&mutex_);- watched_[symbol].insert(portfolio_id);+ active_session()->watch_symbol(symbol, portfolio_id);}void ExchangeService::unwatch_symbol(const QString& symbol, const QString& portfolio_id) {- QMutexLocker lock(&mutex_);- auto it = watched_.find(symbol);- if (it != watched_.end()) {- it->remove(portfolio_id);- if (it->isEmpty())- watched_.erase(it);- }+ active_session()->unwatch_symbol(symbol, portfolio_id);}// ============================================================================-// Price Feed (polling via QTimer)+// Price Feed (polling)// ============================================================================void ExchangeService::start_price_feed(int interval_seconds) {feed_interval_ = interval_seconds;feed_running_ = true;feed_timer_->start(interval_seconds * 1000);- LOG_INFO(TAG, QString("Price feed started (interval=%1s)").arg(interval_seconds));+ LOG_INFO(kServiceTag, QString("Price feed started (interval=%1s)").arg(interval_seconds));}void ExchangeService::stop_price_feed() {@@ -145,1060 +126,119 @@ bool ExchangeService::is_feed_running() const {}void ExchangeService::poll_prices() {- // Guard: skip if a previous poll is still running (avoid piling up threads)if (poll_in_progress_.exchange(true))return;- QMutexLocker lock(&mutex_);- if (watched_.isEmpty()) {+ ExchangeSession* sess = active_session();+ const auto watched = sess->snapshot_watched();+ if (watched.isEmpty()) {poll_in_progress_ = false;return;}QStringList symbols;- // Snapshot watched portfolios per symbol for use after mutex release- QHash<QString, QSet<QString>> watched_snapshot = watched_;- for (auto it = watched_snapshot.constBegin(); it != watched_snapshot.constEnd(); ++it)+ symbols.reserve(watched.size());+ for (auto it = watched.constBegin(); it != watched.constEnd(); ++it)symbols.append(it.key());- QString exchange_id = exchange_id_;- lock.unlock();- // Run the blocking fetch_tickers() in a background thread (P1: never block UI)QPointer<ExchangeService> self = this;- QtConcurrent::run([self, symbols, watched_snapshot, exchange_id]() {- if (!self)+ QPointer<ExchangeSession> session_ptr = sess;+ QtConcurrent::run([self, session_ptr, symbols, watched]() {+ if (!self || !session_ptr)return;-- // fetch_tickers uses call_script which does blocking QProcess — safe in background thread- auto tickers = self->fetch_tickers(symbols);-+ auto tickers = session_ptr->fetch_tickers(symbols);if (!self)return;- // Process results: update cache and feed OrderMatcher (all outside UI thread)- // Collect callbacks to invoke on UI thread- struct TickerResult {- TickerData ticker;- QVector<QString> portfolio_ids;- };- QVector<TickerResult> results;- results.reserve(tickers.size());-+ // Feed paper-trading engine with fresh prices (worker thread — these+ // are SQLite writes; keeping them off the UI thread is P1).for (const auto& ticker : tickers) {- TickerResult r;- r.ticker = ticker;-- auto it = watched_snapshot.find(ticker.symbol);- if (it != watched_snapshot.end()) {- PriceData pd;- pd.last = ticker.last;- pd.bid = ticker.bid;- pd.ask = ticker.ask;- pd.high = ticker.high;- pd.low = ticker.low;- pd.volume = ticker.base_volume;- pd.change = ticker.change;- pd.change_percent = ticker.percentage;- pd.timestamp = ticker.timestamp;-- for (const auto& portfolio_id : *it) {- OrderMatcher::instance().check_orders(ticker.symbol, pd, portfolio_id);- OrderMatcher::instance().check_sl_tp_triggers(portfolio_id, ticker.symbol, ticker.last);- pt_update_position_price(portfolio_id, ticker.symbol, ticker.last);- r.portfolio_ids.append(portfolio_id);- }+ auto it = watched.find(ticker.symbol);+ if (it == watched.end())+ continue;+ PriceData pd;+ pd.last = ticker.last;+ pd.bid = ticker.bid;+ pd.ask = ticker.ask;+ pd.high = ticker.high;+ pd.low = ticker.low;+ pd.volume = ticker.base_volume;+ pd.change = ticker.change;+ pd.change_percent = ticker.percentage;+ pd.timestamp = ticker.timestamp;+ for (const auto& portfolio_id : *it) {+ OrderMatcher::instance().check_orders(ticker.symbol, pd, portfolio_id);+ OrderMatcher::instance().check_sl_tp_triggers(portfolio_id, ticker.symbol, ticker.last);+ pt_update_position_price(portfolio_id, ticker.symbol, ticker.last);}- results.append(std::move(r));}- if (!self)- return;-- // Post cache update + callback invocation back to UI thread- QMetaObject::invokeMethod(- self,- [self, results]() {- if (!self)- return;-- for (const auto& r : results) {- {- QMutexLocker lock(&self->mutex_);- self->price_cache_[r.ticker.symbol] = r.ticker;- }-- // Copy callbacks out, release mutex, then invoke- QVector<PriceUpdateCallback> cbs;- {- QMutexLocker lock(&self->mutex_);- cbs.reserve(self->price_callbacks_.size());- for (auto cb_it = self->price_callbacks_.constBegin();- cb_it != self->price_callbacks_.constEnd(); ++cb_it)- cbs.append(cb_it.value());- }- for (const auto& cb : cbs) {- try {- cb(r.ticker.symbol, r.ticker);- } catch (...) {- LOG_WARN("ExchangeService", "Price update callback threw an exception");- }- }- }-- LOG_DEBUG("ExchangeService", QString("Poll complete: %1 tickers updated").arg(results.size()));- self->poll_in_progress_ = false;- },- Qt::QueuedConnection);+ // Poll results land in the session's WS price_cache_ on subsequent+ // pushes from WS; we intentionally do NOT stuff them into the+ // session's cache here (the cache is authoritative for WS, polling+ // is a fallback for when WS isn't up).+ if (self)+ self->poll_in_progress_ = false;});}// ============================================================================-// Callbacks-// ============================================================================--int ExchangeService::on_price_update(PriceUpdateCallback callback) {- QMutexLocker lock(&mutex_);- int id = next_callback_id_++;- price_callbacks_[id] = std::move(callback);- return id;-}--void ExchangeService::remove_price_callback(int id) {- QMutexLocker lock(&mutex_);- price_callbacks_.remove(id);-}--int ExchangeService::on_orderbook_update(OrderBookCallback callback) {- QMutexLocker lock(&mutex_);- int id = next_callback_id_++;- orderbook_callbacks_[id] = std::move(callback);- return id;-}--void ExchangeService::remove_orderbook_callback(int id) {- QMutexLocker lock(&mutex_);- orderbook_callbacks_.remove(id);-}--int ExchangeService::on_candle_update(CandleCallback callback) {- QMutexLocker lock(&mutex_);- int id = next_callback_id_++;- candle_callbacks_[id] = std::move(callback);- return id;-}--void ExchangeService::remove_candle_callback(int id) {- QMutexLocker lock(&mutex_);- candle_callbacks_.remove(id);-}--int ExchangeService::on_trade_update(TradeCallback callback) {- QMutexLocker lock(&mutex_);- int id = next_callback_id_++;- trade_callbacks_[id] = std::move(callback);- return id;-}--void ExchangeService::remove_trade_callback(int id) {- QMutexLocker lock(&mutex_);- trade_callbacks_.remove(id);-}--// ============================================================================-// Persistent Daemon (eliminates 600-1200ms Python startup per request)+// WebSocket streaming — delegated// ============================================================================-void ExchangeService::start_daemon() {- if (daemon_process_ && daemon_process_->state() == QProcess::Running)- return;-- QString python_path = python::PythonRunner::instance().python_path();- QString script_path = resolve_script_path("exchange/exchange_daemon.py");-- if (python_path.isEmpty() || script_path.isEmpty()) {- LOG_WARN(TAG, "Cannot start daemon: Python or script not found");- return;- }-- daemon_process_ = new QProcess(this);- daemon_process_->setProcessChannelMode(QProcess::SeparateChannels);-- connect(daemon_process_, &QProcess::readyReadStandardOutput, this, &ExchangeService::drain_daemon_buffer);- connect(daemon_process_, &QProcess::readyReadStandardError, this, [this]() {- if (daemon_process_) {- QString err = QString::fromUtf8(daemon_process_->readAllStandardError()).trimmed();- if (!err.isEmpty())- LOG_DEBUG(TAG, "Daemon stderr: " + err);- }- });- connect(daemon_process_, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,- [this](int code, QProcess::ExitStatus status) {- LOG_WARN(- TAG,- QString("Daemon exited (code=%1, status=%2), will restart on next call").arg(code).arg(status));- daemon_ready_ = false;- if (daemon_process_) {- daemon_process_->deleteLater();- daemon_process_ = nullptr;- }- });-- QStringList args;- args << "-u" << "-B" << script_path;- daemon_process_->start(python_path, args);- LOG_INFO(TAG, "Exchange daemon starting...");-}--void ExchangeService::stop_daemon() {- if (daemon_process_) {- daemon_ready_ = false;- daemon_process_->closeWriteChannel();- // Give it a moment to exit cleanly, then force kill- auto* proc = daemon_process_;- daemon_process_ = nullptr;- connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), proc, &QObject::deleteLater);- QTimer::singleShot(2000, proc, [proc]() {- if (proc->state() != QProcess::NotRunning)- proc->kill();- });- }-}--bool ExchangeService::is_daemon_running() const {- return daemon_process_ && daemon_process_->state() == QProcess::Running && daemon_ready_.load();-}--bool ExchangeService::wait_for_daemon_ready(int timeout_ms) {- // Fast path — already up.- if (daemon_ready_.load())- return true;-- // Kick the daemon start if the process hasn't been spawned yet. start_daemon- // must run on the main thread because it owns daemon_process_.- if (!daemon_process_) {- if (QThread::currentThread() == thread()) {- start_daemon();- } else {- QMetaObject::invokeMethod(this, [this]() { start_daemon(); }, Qt::QueuedConnection);- }- }-- // Wait on the ready condition (signalled from drain_daemon_buffer when the- // __init__ line arrives). Safe to call from worker threads only.- QMutexLocker lock(&daemon_mutex_);- QElapsedTimer elapsed;- elapsed.start();- while (!daemon_ready_.load() && elapsed.elapsed() < timeout_ms) {- const int remaining = timeout_ms - static_cast<int>(elapsed.elapsed());- daemon_response_ready_.wait(&daemon_mutex_, std::max(remaining, 50));- }- return daemon_ready_.load();-}--void ExchangeService::drain_daemon_buffer() {- if (!daemon_process_)- return;- while (daemon_process_->canReadLine()) {- QString line = QString::fromUtf8(daemon_process_->readLine()).trimmed();- if (line.isEmpty() || line[0] != '{')- continue;-- QJsonParseError err;- auto doc = QJsonDocument::fromJson(line.toUtf8(), &err);- if (err.error != QJsonParseError::NoError)- continue;-- auto obj = doc.object();- QString id = obj.value("id").toString();-- // Handle the init response- if (id == "__init__") {- daemon_ready_ = true;- LOG_INFO(TAG, "Exchange daemon ready (pid=" +- obj.value("data").toObject().value("pid").toVariant().toString() + ")");- // Send credentials if we have them- if (!credentials_.api_key.isEmpty()) {- QJsonObject creds;- creds["api_key"] = credentials_.api_key;- creds["secret"] = credentials_.secret;- if (!credentials_.password.isEmpty())- creds["password"] = credentials_.password;-- QJsonObject req;- req["id"] = "__creds__";- req["method"] = "set_credentials";- req["exchange"] = exchange_id_;- req["args"] = creds;- QByteArray data = QJsonDocument(req).toJson(QJsonDocument::Compact) + "\n";- daemon_process_->write(data);- credentials_sent_to_daemon_ = true;- }- // Wake any thread waiting for daemon readiness and notify subscribers- daemon_response_ready_.wakeAll();- emit daemon_ready();- continue;- }-- // Store response and wake waiting thread- {- QMutexLocker lock(&daemon_mutex_);- daemon_responses_[id] = obj;- }- daemon_response_ready_.wakeAll();- }-}--QJsonObject ExchangeService::daemon_call(const QString& method, const QJsonObject& args, int timeout_ms) {- // daemon_call() is called from background threads (QtConcurrent::run).- // The daemon process lives on the main thread, so all writes are marshalled- // there via a non-blocking queued invocation. Responses arrive via- // drain_daemon_buffer() on the main thread and are stored in- // daemon_responses_ under mutex. We sleep on a wait condition until our- // response arrives or `timeout_ms` elapses.-- // Auto-start + wait for ready. Uses QueuedConnection internally — never- // blocks a worker on the main event loop.- if (!daemon_ready_.load()) {- if (!wait_for_daemon_ready(std::min(timeout_ms, 8000))) {- LOG_WARN(TAG, "Daemon not ready, falling back to script for: " + method);- return {{"error", "Daemon not ready"}};- }- }-- // Generate unique request ID (atomic, safe from any thread)- QString req_id = QString("r_%1").arg(daemon_req_id_.fetch_add(1));-- // Build request JSON- QJsonObject req;- req["id"] = req_id;- req["method"] = method;- req["exchange"] = exchange_id_;- req["args"] = args;- QByteArray data = QJsonDocument(req).toJson(QJsonDocument::Compact) + "\n";-- // Send credentials + request via QueuedConnection — returns immediately to- // the worker, which then sleeps on the wait condition below. Previously- // this used BlockingQueuedConnection, which stalled the worker waiting for- // the UI event loop to drain (H4).- QMetaObject::invokeMethod(- this,- [this, data]() {- if (!daemon_process_)- return;- // Send credentials if not yet sent- if (!credentials_sent_to_daemon_ && !credentials_.api_key.isEmpty()) {- QJsonObject creds;- creds["api_key"] = credentials_.api_key;- creds["secret"] = credentials_.secret;- if (!credentials_.password.isEmpty())- creds["password"] = credentials_.password;-- QJsonObject cred_req;- cred_req["id"] = "__creds__";- cred_req["method"] = "set_credentials";- cred_req["exchange"] = exchange_id_;- cred_req["args"] = creds;- daemon_process_->write(QJsonDocument(cred_req).toJson(QJsonDocument::Compact) + "\n");- credentials_sent_to_daemon_ = true;- }- daemon_process_->write(data);- },- Qt::QueuedConnection);-- // Wait for response using QWaitCondition (proper cross-thread signaling)- QMutexLocker lock(&daemon_mutex_);- QElapsedTimer elapsed;- elapsed.start();- while (elapsed.elapsed() < timeout_ms) {- auto it = daemon_responses_.find(req_id);- if (it != daemon_responses_.end()) {- QJsonObject resp = it.value();- daemon_responses_.erase(it);- lock.unlock();-- // Unwrap: {"id":"...", "success":true, "data":{...}}- if (resp.value("success").toBool(false) && resp.contains("data")) {- auto d = resp.value("data");- if (d.isObject())- return d.toObject();- }- if (resp.contains("error"))- return resp;- return resp;- }- // Sleep until signaled or 50ms timeout (re-check elapsed)- daemon_response_ready_.wait(&daemon_mutex_, 50);- }- lock.unlock();-- LOG_WARN(TAG, "Daemon call timed out: " + method);- return {{"error", "Daemon call timed out: " + method}};-}--// ============================================================================-// WebSocket Stream (QProcess-based)-// ============================================================================--void ExchangeService::start_ws_stream(const QString& primary_symbol, const QStringList& all_symbols) {- stop_ws_stream();-- ws_primary_symbol_ = primary_symbol;- ws_all_symbols_ = all_symbols;-- // Find Python and script paths via PythonRunner- QString python_path = python::PythonRunner::instance().python_path();- QString script_path;- QStringList args;-- if (is_broker_stream(exchange_id_)) {- script_path = resolve_script_path("exchange/broker_ws_bridge.py");- if (python_path.isEmpty() || script_path.isEmpty()) {- LOG_ERROR(TAG, "Python or broker_ws_bridge.py not found");- return;- }-- auto* broker = BrokerRegistry::instance().get(exchange_id_);- if (!broker) {- LOG_ERROR(TAG, "Broker stream requested but broker is not registered: " + exchange_id_);- return;- }-- auto creds = broker->load_credentials();- if (creds.api_key.isEmpty() || creds.access_token.isEmpty()) {- LOG_ERROR(TAG, "Broker stream credentials missing for " + exchange_id_);- return;- }-- QString feed_token;- QString user_id = creds.user_id;- if (!creds.additional_data.isEmpty()) {- auto ad = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();- if (user_id.isEmpty())- user_id = ad.value("client_code").toString();- feed_token = ad.value("feed_token").toString();- }- if (user_id.isEmpty())- user_id = creds.api_key;-- QStringList broker_symbols = to_broker_symbol_args(all_symbols);- if (broker_symbols.isEmpty())- broker_symbols = to_broker_symbol_args({primary_symbol});- if (broker_symbols.isEmpty()) {- LOG_ERROR(TAG, "No symbols provided for broker websocket stream");- return;- }-- args << "-u" << "-B" << script_path << exchange_id_ << creds.api_key << creds.access_token << user_id;- if (!feed_token.isEmpty())- args << "--feed-token" << feed_token;- args << "--symbols";- args.append(broker_symbols);- } else {- script_path = resolve_script_path("exchange/ws_stream.py");- if (python_path.isEmpty() || script_path.isEmpty()) {- LOG_ERROR(TAG, "Python or ws_stream.py not found");- return;- }-- args << "-u" << "-B" << script_path << exchange_id_;- for (const auto& sym : all_symbols)- args << sym;- }-- ws_process_ = new QProcess(this);- // Throttle: process max 8 lines per event loop cycle via drain_ws_buffer()- // This prevents 50+ synchronous JSON parses from starving the event loop- connect(ws_process_, &QProcess::readyReadStandardOutput, this, &ExchangeService::drain_ws_buffer);- connect(ws_process_, &QProcess::readyReadStandardError, this, [this]() {- QString err = QString::fromUtf8(ws_process_->readAllStandardError()).trimmed();- if (!err.isEmpty())- LOG_WARN(TAG, "WS stderr: " + err);- });-- ws_process_->start(python_path, args);- LOG_INFO(TAG, "WS stream started for " + primary_symbol);+bool ExchangeService::start_ws_stream(const QString& primary_symbol, const QStringList& all_symbols) {+ return active_session()->start_ws(primary_symbol, all_symbols);}void ExchangeService::stop_ws_stream() {- if (ws_process_) {- auto* proc = ws_process_;- ws_process_ = nullptr;- ws_connected_ = false;-- // Disconnect all signals BEFORE cleanup to prevent stale reads- proc->disconnect(this);-- proc->terminate();- // Non-blocking cleanup: kill after timeout if still running, then deleteLater- connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), proc, &QObject::deleteLater);- // If terminate doesn't work within 3s, force kill- QTimer::singleShot(3000, proc, [proc]() {- if (proc->state() != QProcess::NotRunning) {- proc->kill();- }- });- }- ws_connected_ = false;+ active_session()->stop_ws();}bool ExchangeService::is_ws_connected() const {- return ws_connected_.load();-}--void ExchangeService::set_ws_primary_symbol(const QString& symbol) {- QMutexLocker lock(&mutex_);- ws_primary_symbol_ = symbol;+ return active_session()->is_ws_connected();}-QString ExchangeService::get_ws_primary_symbol() const {- QMutexLocker lock(&mutex_);- return ws_primary_symbol_;+bool ExchangeService::is_ws_active() const {+ return active_session()->is_ws_active();}-void ExchangeService::handle_ws_line(const QString& line) {- if (line.isEmpty() || line[0] != '{')- return;-- QJsonParseError err;- auto doc = QJsonDocument::fromJson(line.toUtf8(), &err);- if (err.error != QJsonParseError::NoError)- return;-- auto msg = doc.object();- QString type = msg.value("type").toString();-- if (type == "status") {- ws_connected_ = msg.value("connected").toBool(false);- if (!msg.value("connected").toBool(false)) {- // Clear symbol map on disconnect so stale remaps don't persist- QMutexLocker lock(&mutex_);- ws_symbol_map_.clear();- }- return;- }-- if (type == "symbol_map") {- // ws_stream.py emits this after resolving symbols — e.g. BTC/USDT → BTC/USDC:USDC- // on Hyperliquid. Store the reverse map so incoming tickers get remapped to the- // originally requested symbol before going into price_cache_.- QMutexLocker lock(&mutex_);- ws_symbol_map_.clear();- const auto map_obj = msg.value("map").toObject();- for (auto it = map_obj.constBegin(); it != map_obj.constEnd(); ++it)- ws_symbol_map_[it.key()] = it.value().toString();- LOG_INFO(TAG, QString("Symbol map updated: %1 remaps").arg(ws_symbol_map_.size()));- return;- }-- if (type == "ticker" || type == "tick") {- TickerData ticker;- if (type == "tick") {- // broker_ws_bridge.py emits "tick" with equity field names.- ticker.symbol = msg.value("symbol").toString();- ticker.last = msg.value("ltp").toDouble();- ticker.bid = msg.value("bid").toDouble();- ticker.ask = msg.value("ask").toDouble();- ticker.high = msg.value("high").toDouble();- ticker.low = msg.value("low").toDouble();- ticker.open = msg.value("open").toDouble();- ticker.close = msg.value("close").toDouble();- ticker.base_volume = msg.value("volume").toDouble();- ticker.timestamp = msg.value("timestamp").toVariant().toLongLong();- } else {- // ws_stream.py emits snake_case fields; REST parse_ticker uses camelCase- QJsonObject normalised = msg;- if (!msg.contains("baseVolume") && msg.contains("base_volume"))- normalised["baseVolume"] = msg.value("base_volume");- if (!msg.contains("quoteVolume") && msg.contains("quote_volume"))- normalised["quoteVolume"] = msg.value("quote_volume");- ticker = parse_ticker(normalised);- }-- if (ticker.symbol.isEmpty() || ticker.last <= 0.0)- return;-- // Remap exchange symbol → originally requested symbol.- // e.g. on Hyperliquid: "BTC/USDC:USDC" → "BTC/USDT"- // ws_stream.py emits a "symbol_map" message after resolution that populates ws_symbol_map_.- {- QMutexLocker lock(&mutex_);- auto it = ws_symbol_map_.constFind(ticker.symbol);- if (it != ws_symbol_map_.constEnd())- ticker.symbol = it.value();- }-- // Copy callbacks out, then release mutex BEFORE firing- QVector<PriceUpdateCallback> cbs;- {- QMutexLocker lock(&mutex_);- price_cache_[ticker.symbol] = ticker;- cbs.reserve(price_callbacks_.size());- for (auto it = price_callbacks_.constBegin(); it != price_callbacks_.constEnd(); ++it)- cbs.append(it.value());- }- for (const auto& cb : cbs) {- try {- cb(ticker.symbol, ticker);- } catch (...) {- LOG_WARN("ExchangeService", "Price callback threw an exception for " + ticker.symbol);- }- }- publish_ticker_to_hub(exchange_id_, ticker.symbol, ticker);- return;- }-- if (type == "orderbook") {- OrderBookData ob = parse_orderbook(msg);- QVector<OrderBookCallback> cbs;- {- QMutexLocker lock(&mutex_);- cbs.reserve(orderbook_callbacks_.size());- for (auto it = orderbook_callbacks_.constBegin(); it != orderbook_callbacks_.constEnd(); ++it)- cbs.append(it.value());- }- for (const auto& cb : cbs) {- try {- cb(ob.symbol, ob);- } catch (...) {- LOG_WARN("ExchangeService", "Orderbook callback threw an exception for " + ob.symbol);- }- }- publish_orderbook_to_hub(exchange_id_, ob.symbol, ob);- return;- }-- if (type == "candle" || type == "ohlcv") {- QJsonObject candle_obj = (type == "ohlcv") ? msg.value("candle").toObject() : msg;- Candle c = parse_candle(candle_obj);- QString sym = msg.value("symbol").toString();- if (sym.isEmpty() || c.timestamp == 0)- return;- QVector<CandleCallback> cbs;- {- QMutexLocker lock(&mutex_);- cbs.reserve(candle_callbacks_.size());- for (auto it = candle_callbacks_.constBegin(); it != candle_callbacks_.constEnd(); ++it)- cbs.append(it.value());- }- for (const auto& cb : cbs) {- try {- cb(sym, c);- } catch (...) {- LOG_WARN("ExchangeService", "Candle callback threw an exception for " + sym);- }- }- // Interval is not currently emitted by ws_stream.py — default to "1m".- // When ws_stream starts publishing `interval` in the message, read it here.- const QString interval = msg.value("interval").toString("1m");- publish_candle_to_hub(exchange_id_, sym, interval, c);- return;- }-- if (type == "trade") {- TradeData td;- td.symbol = msg.value("symbol").toString();- td.side = msg.value("side").toString();- td.price = msg.value("price").toDouble();- td.amount = msg.value("amount").toDouble();- td.timestamp = msg.value("timestamp").toVariant().toLongLong();-- QVector<TradeCallback> trade_cbs;- QVector<PriceUpdateCallback> price_cbs;- TickerData fast_ticker;- bool emit_price = false;-- {- QMutexLocker lock(&mutex_);- // Use trade price to keep price_cache_ current — this is the fast path- // for exchanges where watch_ticker is slow (e.g. Kraken spot ~2/15s).- if (!td.symbol.isEmpty() && td.price > 0.0) {- auto& cached = price_cache_[td.symbol];- cached.symbol = td.symbol;- cached.last = td.price;- if (cached.bid <= 0.0)- cached.bid = td.price;- if (cached.ask <= 0.0)- cached.ask = td.price;- fast_ticker = cached;- emit_price = true;- }- trade_cbs.reserve(trade_callbacks_.size());- for (auto it = trade_callbacks_.constBegin(); it != trade_callbacks_.constEnd(); ++it)- trade_cbs.append(it.value());- if (emit_price) {- price_cbs.reserve(price_callbacks_.size());- for (auto it = price_callbacks_.constBegin(); it != price_callbacks_.constEnd(); ++it)- price_cbs.append(it.value());- }- }-- for (const auto& cb : trade_cbs) {- try {- cb(td.symbol, td);- } catch (...) {- LOG_WARN("ExchangeService", "Trade callback threw an exception for " + td.symbol);- }- }- // Fire price callbacks so the ticker bar and order entry update on every trade- if (emit_price) {- for (const auto& cb : price_cbs) {- try {- cb(fast_ticker.symbol, fast_ticker);- } catch (...) {- LOG_WARN("ExchangeService",- "Price callback (from trade) threw an exception for " + fast_ticker.symbol);- }- }- }- if (!td.symbol.isEmpty()) {- publish_trade_to_hub(exchange_id_, td.symbol, td);- if (emit_price)- publish_ticker_to_hub(exchange_id_, fast_ticker.symbol, fast_ticker);- }- }-}--void ExchangeService::drain_ws_buffer() {- if (!ws_process_)- return;-- // Process up to 50 lines OR 4ms, whichever comes first.- // Old limit of 8 lines caused unbounded buffer buildup during volatility.- // The 4ms time cap prevents UI starvation if lines are expensive to parse.- int processed = 0;- constexpr int MAX_LINES_PER_CYCLE = 50;- constexpr qint64 MAX_MS_PER_CYCLE = 4;- QElapsedTimer elapsed;- elapsed.start();-- while (ws_process_->canReadLine() && processed < MAX_LINES_PER_CYCLE) {- QString line = QString::fromUtf8(ws_process_->readLine()).trimmed();- if (!line.isEmpty())- handle_ws_line(line);- ++processed;- if (elapsed.elapsed() >= MAX_MS_PER_CYCLE)- break;- }- // Reschedule if more data remains — use singleShot(1ms) instead of 0ms- // to yield one event loop iteration for UI repaints- if (ws_process_ && ws_process_->canReadLine())- QTimer::singleShot(1, this, &ExchangeService::drain_ws_buffer);-}--// ============================================================================-// Python Script Calls-// ============================================================================--QJsonObject ExchangeService::call_script(const QString& script, const QStringList& args) {- QString python_path = python::PythonRunner::instance().python_path();- QString script_path = resolve_script_path(script);-- if (python_path.isEmpty() || script_path.isEmpty()) {- return {{"error", "Python or script not found: " + script}};- }-- QStringList full_args;- full_args << "-u" << "-B" << script_path << exchange_id_;- full_args.append(args);-- QProcess proc;- proc.start(python_path, full_args);- const bool finished = proc.waitForFinished(30000);- if (!finished) {- LOG_WARN(TAG, QString("call_script timed out after 30s: %1").arg(script));- proc.kill();- proc.waitForFinished(500);- return {{"error", "Script timed out: " + script}};- }-- QString output = proc.readAllStandardOutput().trimmed();- if (output.isEmpty()) {- QString err = proc.readAllStandardError().trimmed();- return {{"error", err.isEmpty() ? "No output from script" : err}};- }-- QJsonParseError parseErr;- auto doc = QJsonDocument::fromJson(output.toUtf8(), &parseErr);- if (parseErr.error != QJsonParseError::NoError) {- return {{"error", "JSON parse error: " + parseErr.errorString()}};- }-- auto obj = doc.object();-- // Python scripts wrap output as {"success": true, "data": {...}}.- // Unwrap the "data" layer so callers can access keys directly.- if (obj.value("success").toBool(false) && obj.contains("data")) {- auto data = obj.value("data");- if (data.isObject())- return data.toObject();- }-- // If there was an error, propagate it directly- if (obj.contains("error"))- return obj;-- // Fallback: return as-is (e.g. scripts that don't use output_success wrapper)- return obj;+void ExchangeService::set_ws_primary_symbol(const QString& symbol) {+ active_session()->set_ws_primary_symbol(symbol);}-QJsonObject ExchangeService::call_script_with_credentials(const QString& script, const QStringList& args) {- // Authenticated scripts expect credentials via stdin JSON, not command-line flags.- // Build the credentials JSON to pipe to the process.- QMutexLocker lock(&mutex_);- QJsonObject creds_json;- if (!credentials_.api_key.isEmpty()) {- creds_json["api_key"] = credentials_.api_key;- creds_json["secret"] = credentials_.secret;- if (!credentials_.password.isEmpty())- creds_json["password"] = credentials_.password;- }- lock.unlock();-- QString python_path = python::PythonRunner::instance().python_path();- QString script_path = resolve_script_path(script);-- if (python_path.isEmpty() || script_path.isEmpty()) {- return {{"error", "Python or script not found: " + script}};- }-- QStringList full_args;- full_args << "-u" << "-B" << script_path << exchange_id_;- full_args.append(args);-- QProcess proc;- proc.start(python_path, full_args);- proc.waitForStarted(5000);-- // Write credentials to stdin- if (!creds_json.isEmpty()) {- QByteArray creds_data = QJsonDocument(creds_json).toJson(QJsonDocument::Compact);- proc.write(creds_data);- }- proc.closeWriteChannel();-- proc.waitForFinished(30000);-- QString output = proc.readAllStandardOutput().trimmed();- if (output.isEmpty()) {- QString err = proc.readAllStandardError().trimmed();- return {{"error", err.isEmpty() ? "No output from script" : err}};- }-- QJsonParseError parseErr;- auto doc = QJsonDocument::fromJson(output.toUtf8(), &parseErr);- if (parseErr.error != QJsonParseError::NoError) {- return {{"error", "JSON parse error: " + parseErr.errorString()}};- }-- auto obj = doc.object();- if (obj.value("success").toBool(false) && obj.contains("data")) {- auto data = obj.value("data");- if (data.isObject())- return data.toObject();- }- if (obj.contains("error"))- return obj;- return obj;+QString ExchangeService::get_ws_primary_symbol() const {+ return active_session()->get_ws_primary_symbol();}// ============================================================================-// One-shot Fetches+// One-shot fetches — delegated// ============================================================================-TickerData ExchangeService::parse_ticker(const QJsonObject& j) {- TickerData t;- t.symbol = j.value("symbol").toString();- t.last = j.value("last").toDouble();- t.bid = j.value("bid").toDouble();- t.ask = j.value("ask").toDouble();- t.high = j.value("high").toDouble();- t.low = j.value("low").toDouble();- t.open = j.value("open").toDouble();- t.close = j.value("close").toDouble();- t.change = j.value("change").toDouble();- t.percentage = j.value("percentage").toDouble();- t.base_volume = j.value("baseVolume").toDouble();- t.quote_volume = j.value("quoteVolume").toDouble();- t.timestamp = j.value("timestamp").toVariant().toLongLong();- return t;-}--OrderBookData ExchangeService::parse_orderbook(const QJsonObject& j) {- OrderBookData ob;- ob.symbol = j.value("symbol").toString();-- auto bids = j.value("bids").toArray();- for (const auto& b : bids) {- auto arr = b.toArray();- if (arr.size() >= 2) {- ob.bids.append({arr[0].toDouble(), arr[1].toDouble()});- }- }-- auto asks = j.value("asks").toArray();- for (const auto& a : asks) {- auto arr = a.toArray();- if (arr.size() >= 2) {- ob.asks.append({arr[0].toDouble(), arr[1].toDouble()});- }- }-- if (!ob.bids.isEmpty())- ob.best_bid = ob.bids.first().first;- if (!ob.asks.isEmpty())- ob.best_ask = ob.asks.first().first;- if (ob.best_bid > 0 && ob.best_ask > 0) {- ob.spread = ob.best_ask - ob.best_bid;- ob.spread_pct = (ob.spread / ob.best_ask) * 100.0;- }- return ob;-}--Candle ExchangeService::parse_candle(const QJsonObject& j) {- Candle c;- c.timestamp = j.value("timestamp").toVariant().toLongLong();- c.open = j.value("open").toDouble();- c.high = j.value("high").toDouble();- c.low = j.value("low").toDouble();- c.close = j.value("close").toDouble();- c.volume = j.value("volume").toDouble();- return c;-}--MarketInfo ExchangeService::parse_market(const QJsonObject& j) {- MarketInfo m;- m.symbol = j.value("symbol").toString();- m.base = j.value("base").toString();- m.quote = j.value("quote").toString();- m.type = j.value("type").toString();- m.active = j.value("active").toBool(true);- m.maker_fee = j.value("maker").toDouble();- m.taker_fee = j.value("taker").toDouble();- m.min_amount = j.value("minAmount").toDouble();- m.min_cost = j.value("minCost").toDouble();- return m;-}-TickerData ExchangeService::fetch_ticker(const QString& symbol) {- // Daemon path: ~100ms (reuses warm ccxt instance)- // Legacy path: ~900ms (spawns Python, imports ccxt, creates exchange)- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_ticker", {{"symbol", symbol}});- if (!j.contains("error"))- return parse_ticker(j);- LOG_WARN(TAG, "Daemon fetch_ticker failed, falling back to script");- }- auto j = call_script("exchange/fetch_ticker.py", {symbol});- if (j.contains("error"))- return {};- return parse_ticker(j);+ return active_session()->fetch_ticker(symbol);}-QVector<TickerData> ExchangeService::fetch_tickers(const QStringList& symbols) {- if (wait_for_daemon_ready()) {- QJsonArray sym_arr;- for (const auto& s : symbols)- sym_arr.append(s);- auto j = daemon_call("fetch_tickers", {{"symbols", sym_arr}});- if (!j.contains("error") && j.contains("tickers")) {- QVector<TickerData> result;- auto arr = j.value("tickers").toArray();- for (const auto& item : arr)- result.append(parse_ticker(item.toObject()));- return result;- }- LOG_WARN(TAG, "Daemon fetch_tickers failed, falling back to script");- }- QStringList args = symbols;- auto j = call_script("exchange/fetch_tickers.py", args);- QVector<TickerData> result;- if (j.contains("tickers")) {- auto arr = j.value("tickers").toArray();- for (const auto& item : arr)- result.append(parse_ticker(item.toObject()));- }- return result;+ return active_session()->fetch_tickers(symbols);}-OrderBookData ExchangeService::fetch_orderbook(const QString& symbol, int limit) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_orderbook", {{"symbol", symbol}, {"limit", limit}});- if (!j.contains("error"))- return parse_orderbook(j);- LOG_WARN(TAG, "Daemon fetch_orderbook failed, falling back to script");- }- auto j = call_script("exchange/fetch_orderbook.py", {symbol, QString::number(limit)});- if (j.contains("error"))- return {};- return parse_orderbook(j);+ return active_session()->fetch_orderbook(symbol, limit);}-QVector<Candle> ExchangeService::fetch_ohlcv(const QString& symbol, const QString& timeframe, int limit) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_ohlcv", {{"symbol", symbol}, {"timeframe", timeframe}, {"limit", limit}});- if (!j.contains("error") && j.contains("candles")) {- QVector<Candle> result;- auto arr = j.value("candles").toArray();- for (const auto& item : arr)- result.append(parse_candle(item.toObject()));- return result;- }- LOG_WARN(TAG, "Daemon fetch_ohlcv failed, falling back to script");- }- auto j = call_script("exchange/fetch_ohlcv.py", {symbol, timeframe, QString::number(limit)});- QVector<Candle> result;- if (j.contains("candles")) {- auto arr = j.value("candles").toArray();- for (const auto& item : arr)- result.append(parse_candle(item.toObject()));- }- return result;+ return active_session()->fetch_ohlcv(symbol, timeframe, limit);}-QVector<MarketInfo> ExchangeService::fetch_markets(const QString& type, const QString& query) {- if (wait_for_daemon_ready()) {- QJsonObject args;- if (!type.isEmpty())- args["type"] = type;- if (!query.isEmpty()) {- args["query"] = query;- args["limit"] = 100; // server-side cap when filtering- }- auto j = daemon_call("fetch_markets", args);- if (!j.contains("error") && j.contains("markets")) {- QVector<MarketInfo> result;- auto arr = j.value("markets").toArray();- for (const auto& item : arr)- result.append(parse_market(item.toObject()));- return result;- }- LOG_WARN(TAG, "Daemon fetch_markets failed, falling back to script");- }- QStringList args;- if (!type.isEmpty())- args << type;- auto j = call_script("exchange/fetch_markets.py", args);- QVector<MarketInfo> result;- if (j.contains("markets")) {- auto arr = j.value("markets").toArray();- for (const auto& item : arr)- result.append(parse_market(item.toObject()));- }- return result;+ return active_session()->fetch_markets(type, query);}QStringList ExchangeService::list_exchange_ids() {- if (wait_for_daemon_ready()) {- auto j = daemon_call("list_exchange_ids", {});- if (!j.contains("error") && j.contains("exchanges")) {- QStringList result;- auto arr = j.value("exchanges").toArray();- for (const auto& item : arr)- result.append(item.toString());- return result;- }- }- auto j = call_script("exchange/list_exchanges.py", {});+ // Exchange-agnostic daemon call — list_exchange_ids returns the ccxt+ // library's exchange directory, independent of any session.+ if (!ExchangeDaemonPool::instance().wait_for_ready(8000))+ return {};+ // Reuse the active session's exchange id as a dummy; the daemon+ // doesn't actually use it for list_exchange_ids.+ const QString exchange = get_exchange();+ auto j = ExchangeDaemonPool::instance().call(exchange, "list_exchange_ids", {}, {}, 15000);QStringList result;if (j.contains("exchanges")) {auto arr = j.value("exchanges").toArray();@@ -1209,314 +249,53 @@ QStringList ExchangeService::list_exchange_ids() {}QVector<TradeData> ExchangeService::fetch_trades(const QString& symbol, int limit) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_trades", {{"symbol", symbol}, {"limit", limit}});- if (!j.contains("error") && j.contains("trades")) {- QVector<TradeData> result;- auto arr = j.value("trades").toArray();- for (const auto& item : arr) {- auto o = item.toObject();- TradeData td;- td.id = o.value("id").toString();- td.symbol = o.value("symbol").toString();- td.side = o.value("side").toString();- td.price = o.value("price").toDouble();- td.amount = o.value("amount").toDouble();- td.cost = o.value("cost").toDouble();- td.timestamp = o.value("timestamp").toVariant().toLongLong();- result.append(td);- }- return result;- }- }- auto j = call_script("exchange/fetch_trades.py", {symbol, QString::number(limit)});- QVector<TradeData> result;- if (j.contains("trades")) {- auto arr = j.value("trades").toArray();- for (const auto& item : arr) {- auto o = item.toObject();- TradeData td;- td.id = o.value("id").toString();- td.symbol = o.value("symbol").toString();- td.side = o.value("side").toString();- td.price = o.value("price").toDouble();- td.amount = o.value("amount").toDouble();- td.cost = o.value("cost").toDouble();- td.timestamp = o.value("timestamp").toVariant().toLongLong();- result.append(td);- }- }- return result;+ return active_session()->fetch_trades(symbol, limit);}-FundingRateData ExchangeService::fetch_funding_rate(const QString& symbol) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_funding_rate", {{"symbol", symbol}});- if (!j.contains("error")) {- FundingRateData fr;- fr.symbol = j.value("symbol").toString();- fr.funding_rate = j.value("funding_rate").toDouble();- fr.mark_price = j.value("mark_price").toDouble();- fr.index_price = j.value("index_price").toDouble();- fr.funding_timestamp = j.value("funding_timestamp").toVariant().toLongLong();- fr.next_funding_timestamp = j.value("next_funding_timestamp").toVariant().toLongLong();- return fr;- }- }- auto j = call_script("exchange/fetch_funding_rate.py", {symbol});- FundingRateData fr;- if (!j.contains("error")) {- fr.symbol = j.value("symbol").toString();- fr.funding_rate = j.value("funding_rate").toDouble();- fr.mark_price = j.value("mark_price").toDouble();- fr.index_price = j.value("index_price").toDouble();- fr.funding_timestamp = j.value("funding_timestamp").toVariant().toLongLong();- fr.next_funding_timestamp = j.value("next_funding_timestamp").toVariant().toLongLong();- }- return fr;+ return active_session()->fetch_funding_rate(symbol);}-OpenInterestData ExchangeService::fetch_open_interest(const QString& symbol) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_open_interest", {{"symbol", symbol}});- if (!j.contains("error")) {- OpenInterestData oi;- oi.symbol = j.value("symbol").toString();- oi.open_interest = j.value("open_interest").toDouble();- oi.open_interest_value = j.value("open_interest_value").toDouble();- oi.timestamp = j.value("timestamp").toVariant().toLongLong();- return oi;- }- }- auto j = call_script("exchange/fetch_open_interest.py", {symbol});- OpenInterestData oi;- if (!j.contains("error")) {- oi.symbol = j.value("symbol").toString();- oi.open_interest = j.value("open_interest").toDouble();- oi.open_interest_value = j.value("open_interest_value").toDouble();- oi.timestamp = j.value("timestamp").toVariant().toLongLong();- }- return oi;+ return active_session()->fetch_open_interest(symbol);}QJsonObject ExchangeService::fetch_balance() {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_balance", {});- if (!j.contains("error"))- return j;- }- return call_script_with_credentials("exchange/fetch_balance.py", {});+ return active_session()->fetch_balance();}-QJsonObject ExchangeService::place_exchange_order(const QString& symbol, const QString& side, const QString& type,double amount, double price) {- if (wait_for_daemon_ready()) {- QJsonObject args;- args["symbol"] = symbol;- args["side"] = side;- args["type"] = type;- args["amount"] = amount;- if (price > 0)- args["price"] = price;- auto j = daemon_call("place_order", args);- if (!j.contains("error"))- return j;- LOG_WARN(TAG, "Daemon place_order failed, falling back to script");- }- QStringList args = {symbol, side, type, QString::number(amount, 'f', 8)};- if (price > 0)- args << QString::number(price, 'f', 8);- return call_script_with_credentials("exchange/place_order.py", args);+ return active_session()->place_exchange_order(symbol, side, type, amount, price);}-QJsonObject ExchangeService::cancel_exchange_order(const QString& order_id, const QString& symbol) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("cancel_order", {{"order_id", order_id}, {"symbol", symbol}});- if (!j.contains("error"))- return j;- }- return call_script_with_credentials("exchange/cancel_order.py", {order_id, symbol});+ return active_session()->cancel_exchange_order(order_id, symbol);}-QJsonObject ExchangeService::fetch_positions_live(const QString& symbol) {- if (wait_for_daemon_ready()) {- QJsonObject args;- if (!symbol.isEmpty())- args["symbol"] = symbol;- auto j = daemon_call("fetch_positions", args);- if (!j.contains("error"))- return j;- }- QStringList args;- if (!symbol.isEmpty())- args << symbol;- return call_script_with_credentials("exchange/fetch_positions.py", args);+ return active_session()->fetch_positions_live(symbol);}-QJsonObject ExchangeService::fetch_open_orders_live(const QString& symbol) {- if (wait_for_daemon_ready()) {- QJsonObject args;- if (!symbol.isEmpty())- args["symbol"] = symbol;- auto j = daemon_call("fetch_open_orders", args);- if (!j.contains("error"))- return j;- }- QStringList args;- if (!symbol.isEmpty())- args << symbol;- return call_script_with_credentials("exchange/fetch_open_orders.py", args);-}--MarkPriceData ExchangeService::fetch_mark_price(const QString& symbol) {- MarkPriceData mp;- mp.symbol = symbol;- QJsonObject j;- if (wait_for_daemon_ready()) {- j = daemon_call("fetch_mark_price", {{"symbol", symbol}});- if (j.contains("error"))- j = {};- }- if (j.isEmpty())- j = call_script("exchange/fetch_mark_price.py", {symbol});- if (!j.isEmpty()) {- mp.mark_price = j.value("mark_price").toDouble();- mp.index_price = j.value("index_price").toDouble();- mp.timestamp = j.value("timestamp").toVariant().toLongLong();- }- return mp;+ return active_session()->fetch_open_orders_live(symbol);}-QJsonObject ExchangeService::fetch_my_trades(const QString& symbol, int limit) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("fetch_my_trades", {{"symbol", symbol}, {"limit", limit}});- if (!j.contains("error"))- return j;- LOG_WARN(TAG, "Daemon fetch_my_trades failed, falling back to script");- }- return call_script_with_credentials("exchange/fetch_my_trades.py", {symbol, QString::number(limit)});+ return active_session()->fetch_my_trades(symbol, limit);}-QJsonObject ExchangeService::fetch_trading_fees(const QString& symbol) {- if (wait_for_daemon_ready()) {- QJsonObject args;- if (!symbol.isEmpty())- args["symbol"] = symbol;- auto j = daemon_call("fetch_trading_fees", args);- if (!j.contains("error"))- return j;- LOG_WARN(TAG, "Daemon fetch_trading_fees failed, falling back to script");- }- QStringList args;- if (!symbol.isEmpty())- args << symbol;- return call_script("exchange/fetch_trading_fees.py", args);+ return active_session()->fetch_trading_fees(symbol);}-QJsonObject ExchangeService::set_leverage(const QString& symbol, int leverage) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("set_leverage", {{"symbol", symbol}, {"leverage", leverage}});- if (!j.contains("error"))- return j;- LOG_WARN(TAG, "Daemon set_leverage failed, falling back to script");- }- return call_script_with_credentials("exchange/set_leverage.py", {symbol, QString::number(leverage)});+ return active_session()->set_leverage(symbol, leverage);}-QJsonObject ExchangeService::set_margin_mode(const QString& symbol, const QString& mode) {- if (wait_for_daemon_ready()) {- auto j = daemon_call("set_margin_mode", {{"symbol", symbol}, {"mode", mode}});- if (!j.contains("error"))- return j;- LOG_WARN(TAG, "Daemon set_margin_mode failed, falling back to script");- }- return call_script_with_credentials("exchange/set_margin_mode.py", {symbol, mode});-}--const QHash<QString, TickerData>& ExchangeService::get_price_cache() const {- return price_cache_;-}--TickerData ExchangeService::get_cached_price(const QString& symbol) const {- QMutexLocker lock(&mutex_);- return price_cache_.value(symbol);-}--// ── DataHub producer wiring ────────────────────────────────────────────────--QStringList ExchangeService::topic_patterns() const {- return {"ws:kraken:*", "ws:hyperliquid:*"};+ return active_session()->set_margin_mode(symbol, mode);}--void ExchangeService::refresh(const QStringList& /*topics*/) {- // push_only: scheduler never calls this. Fan-out happens in handle_ws_line.-}--int ExchangeService::max_requests_per_sec() const {- return 0; // unlimited — push only, no REST pacing-}--void ExchangeService::ensure_registered_with_hub() {- if (hub_registered_) return;- auto& hub = fincept::datahub::DataHub::instance();- hub.register_producer(this);-- fincept::datahub::TopicPolicy push_only;- push_only.push_only = true;- push_only.ttl_ms = 0;- push_only.min_interval_ms = 0;-- fincept::datahub::TopicPolicy coalesced_ticker = push_only;- coalesced_ticker.coalesce_within_ms = 50; // cap fan-out at 20 Hz-- // Ticker families — coalesced (high-rate feeds)- hub.set_policy_pattern("ws:kraken:ticker:*", coalesced_ticker);- hub.set_policy_pattern("ws:hyperliquid:ticker:*", coalesced_ticker);-- // Orderbook / trades / ohlc — push-only, no coalescing- hub.set_policy_pattern("ws:kraken:orderbook:*", push_only);- hub.set_policy_pattern("ws:kraken:trades:*", push_only);- hub.set_policy_pattern("ws:kraken:ohlc:*", push_only);- hub.set_policy_pattern("ws:hyperliquid:orderbook:*", push_only);- hub.set_policy_pattern("ws:hyperliquid:trades:*", push_only);- hub.set_policy_pattern("ws:hyperliquid:ohlc:*", push_only);-- hub_registered_ = true;- LOG_INFO("ExchangeService", "Registered with DataHub (ws:kraken:*, ws:hyperliquid:*)");-}--static bool hub_exchange_supported(const QString& id) {- return id == QLatin1String("kraken") || id == QLatin1String("hyperliquid");-}--void ExchangeService::publish_ticker_to_hub(const QString& exchange, const QString& pair,- const TickerData& ticker) {- if (!hub_exchange_supported(exchange) || pair.isEmpty()) return;- const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":ticker:") + pair;- fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(ticker));-}--void ExchangeService::publish_orderbook_to_hub(const QString& exchange, const QString& pair,- const OrderBookData& ob) {- if (!hub_exchange_supported(exchange) || pair.isEmpty()) return;- const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":orderbook:") + pair;- fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(ob));+MarkPriceData ExchangeService::fetch_mark_price(const QString& symbol) {+ return active_session()->fetch_mark_price(symbol);}-void ExchangeService::publish_trade_to_hub(const QString& exchange, const QString& pair,- const TradeData& trade) {- if (!hub_exchange_supported(exchange) || pair.isEmpty()) return;- const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":trades:") + pair;- fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(trade));-}+// ============================================================================+// Cache+// ============================================================================-void ExchangeService::publish_candle_to_hub(const QString& exchange, const QString& pair,- const QString& interval, const Candle& candle) {- if (!hub_exchange_supported(exchange) || pair.isEmpty()) return;- const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":ohlc:") + pair +- QLatin1Char(':') + interval;- fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(candle));+TickerData ExchangeService::get_cached_price(const QString& symbol) const {+ return active_session()->get_cached_price(symbol);}-} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeService.h b/fincept-qt/src/trading/ExchangeService.hindex 794406fc4..f94c42342 100644--- a/fincept-qt/src/trading/ExchangeService.h+++ b/fincept-qt/src/trading/ExchangeService.h@@ -1,98 +1,75 @@#pragma once-// ExchangeService — Bridge between Python ccxt scripts and C++ paper trading-// Qt-adapted port using QProcess for subprocess management.+// ExchangeService — facade over ExchangeSessionManager.+//+// Coordinates the "which exchange is currently active" state for legacy+// screens that haven't been ported to subscribe to DataHub topics directly.+// All data streaming is consumed via the hub — this facade only wraps the+// one-shot REST fetches, configuration, credentials, and WS lifecycle.+//+// Notes:+// - `set_exchange(id)` only flips which session is "active" for these+// facade calls. It does NOT stop the previous session's WS process —+// that session stays warm so switching back is sub-second.+// - Streaming data (ticker / orderbook / trades / ohlc) is NOT surfaced+// here any more. Subscribe to `ws:<exchange>:<family>:<pair>` on+// DataHub instead (see ExchangeSessionManager).#include "trading/TradingTypes.h"-# include "datahub/Producer.h"--#include <QElapsedTimer>-#include <QHash>#include <QMutex>#include <QObject>-#include <QProcess>-#include <QSet>+#include <QString>#include <QTimer>-#include <QWaitCondition>#include <atomic>-#include <functional>namespace fincept::trading {-using PriceUpdateCallback = std::function<void(const QString& symbol, const TickerData& ticker)>;-using OrderBookCallback = std::function<void(const QString& symbol, const OrderBookData& ob)>;-using CandleCallback = std::function<void(const QString& symbol, const Candle& candle)>;-using TradeCallback = std::function<void(const QString& symbol, const TradeData& trade)>;--/// ExchangeService streams Kraken / HyperLiquid / broker WS data via a-/// Python subprocess. Phase 4 — DataHub producer for the `ws:*` topic-/// family. See fincept-qt/docs/datahub-phases/phase-04-websocket-producers.md.-///-/// The WS subprocess model predates the hub: one subprocess per exchange-/// kick-started via `start_ws_stream()`. For now the producer *publishes-/// alongside* the existing callbacks (dual-fire). Consumers migrate one-/// at a time; legacy callback API stays alive for a grace release.-class ExchangeService : public QObject- , public fincept::datahub::Producer-{+class ExchangeSession;++class ExchangeService : public QObject {Q_OBJECTpublic:static ExchangeService& instance();- /// Register this service as a DataHub producer + install default- /// `ws:kraken:*` / `ws:hyperliquid:*` policies. Idempotent.- /// Called from main.cpp after `datahub::register_metatypes()`.+ /// Back-compat shim — delegates to+ /// ExchangeSessionManager::ensure_registered_with_hub().void ensure_registered_with_hub();- // ── fincept::datahub::Producer ────────────────────────────────────────- QStringList topic_patterns() const override;- void refresh(const QStringList& topics) override; // no-op: push_only- int max_requests_per_sec() const override; // 0 (unlimited: WS)-// Configurationvoid set_exchange(const QString& exchange_id);QString get_exchange() const;void set_credentials(const ExchangeCredentials& creds);- // Daemon readiness — block (in background thread only!) up to `timeout_ms`- // for the persistent ccxt daemon to finish booting. Returns true if ready.- // Avoids per-call raw QProcess fallback when daemon is still starting.bool wait_for_daemon_ready(int timeout_ms = 8000);signals:- // Emitted (from main thread) when the ccxt daemon has finished booting and- // is ready to serve fetch requests. Subscribers can defer first data- // fetches until this fires to avoid racing the cold-boot path.+ /// Forwarded from ExchangeDaemonPool::ready() — first time the daemon+ /// finishes its cold-boot. Subsequent daemon restarts also emit this.void daemon_ready();public:-- // Price feed+ // Price feed (service-level; polls the active session's cached data)void watch_symbol(const QString& symbol, const QString& portfolio_id);void unwatch_symbol(const QString& symbol, const QString& portfolio_id);void start_price_feed(int interval_seconds = 5);void stop_price_feed();bool is_feed_running() const;- // Callbacks- int on_price_update(PriceUpdateCallback callback);- void remove_price_callback(int id);- int on_orderbook_update(OrderBookCallback callback);- void remove_orderbook_callback(int id);- int on_candle_update(CandleCallback callback);- void remove_candle_callback(int id);- int on_trade_update(TradeCallback callback);- void remove_trade_callback(int id);-- // WebSocket streaming- void start_ws_stream(const QString& primary_symbol, const QStringList& all_symbols);+ // WebSocket streaming (delegated to current session). Data consumers+ // subscribe to DataHub topics — these entry points are for lifecycle+ // control (start/stop/status) only.+ bool start_ws_stream(const QString& primary_symbol, const QStringList& all_symbols);void stop_ws_stream();bool is_ws_connected() const;+ /// Process-level check — does the current session already have a running+ /// WS subprocess. Screens use this to skip re-spawning when flipping+ /// back to an already-warm exchange.+ bool is_ws_active() const;void set_ws_primary_symbol(const QString& symbol);QString get_ws_primary_symbol() const;- // One-shot data fetches (synchronous — call from background thread only)+ // One-shot data fetches — delegated to current session (synchronous; worker thread only).TickerData fetch_ticker(const QString& symbol);QVector<TickerData> fetch_tickers(const QStringList& symbols);OrderBookData fetch_orderbook(const QString& symbol, int limit = 20);@@ -103,7 +80,7 @@ class ExchangeService : public QObjectFundingRateData fetch_funding_rate(const QString& symbol);OpenInterestData fetch_open_interest(const QString& symbol);- // Authenticated operations (synchronous — call from background thread only)+ // Authenticated operations — current session, worker thread only.QJsonObject fetch_balance();QJsonObject place_exchange_order(const QString& symbol, const QString& side, const QString& type, double amount,double price = 0.0);@@ -115,11 +92,9 @@ class ExchangeService : public QObjectQJsonObject set_leverage(const QString& symbol, int leverage);QJsonObject set_margin_mode(const QString& symbol, const QString& mode);- // Derivatives data (synchronous — call from background thread only)MarkPriceData fetch_mark_price(const QString& symbol);- // Cache- const QHash<QString, TickerData>& get_price_cache() const;+ // Cache (reads the active session's cache)TickerData get_cached_price(const QString& symbol) const;ExchangeService(const ExchangeService&) = delete;@@ -129,73 +104,20 @@ class ExchangeService : public QObjectExchangeService();~ExchangeService();- void poll_prices();+ /// Resolve the active session through the manager. Never null.+ ExchangeSession* active_session() const;- /// Publish a ticker/orderbook/candle/trade to the hub alongside the- /// existing callback fan-out. Called from `handle_ws_line`.- void publish_ticker_to_hub(const QString& exchange, const QString& pair,- const TickerData& ticker);- void publish_orderbook_to_hub(const QString& exchange, const QString& pair,- const OrderBookData& ob);- void publish_trade_to_hub(const QString& exchange, const QString& pair,- const TradeData& trade);- void publish_candle_to_hub(const QString& exchange, const QString& pair,- const QString& interval, const Candle& candle);- bool hub_registered_ = false;-- // Legacy one-shot script calls (fallback if daemon is unavailable)- QJsonObject call_script(const QString& script, const QStringList& args);- QJsonObject call_script_with_credentials(const QString& script, const QStringList& args);-- // Persistent daemon — keeps ccxt loaded, eliminates per-request startup- void start_daemon();- void stop_daemon();- bool is_daemon_running() const;- QJsonObject daemon_call(const QString& method, const QJsonObject& args, int timeout_ms = 15000);- void drain_daemon_buffer();-- QProcess* daemon_process_ = nullptr;- std::atomic<bool> daemon_ready_{false};- std::atomic<int> daemon_req_id_{0};- QHash<QString, QJsonObject> daemon_responses_; // id -> response- QMutex daemon_mutex_;- QWaitCondition daemon_response_ready_; // signaled when any response arrives- bool credentials_sent_to_daemon_ = false;-- static TickerData parse_ticker(const QJsonObject& j);- static OrderBookData parse_orderbook(const QJsonObject& j);- static Candle parse_candle(const QJsonObject& j);- static MarketInfo parse_market(const QJsonObject& j);+ void poll_prices();+ mutable QMutex mutex_;QString exchange_id_ = "kraken";- ExchangeCredentials credentials_;-- QHash<QString, QSet<QString>> watched_;- QHash<QString, TickerData> price_cache_;-- QHash<int, PriceUpdateCallback> price_callbacks_;- QHash<int, OrderBookCallback> orderbook_callbacks_;- QHash<int, CandleCallback> candle_callbacks_;- QHash<int, TradeCallback> trade_callbacks_;- int next_callback_id_ = 1;+ // Price feed timer (facade-level; iterates active session's cache / does+ // a small fetch_tickers to refresh)QTimer* feed_timer_ = nullptr;std::atomic<bool> feed_running_{false};std::atomic<bool> poll_in_progress_{false};int feed_interval_ = 5;-- // WebSocket subprocess- QProcess* ws_process_ = nullptr;- std::atomic<bool> ws_connected_{false};- QString ws_primary_symbol_;- QStringList ws_all_symbols_;- // Symbol remap: exchange_symbol → requested_symbol (e.g. "BTC/USDC:USDC" → "BTC/USDT")- // Populated from the "symbol_map" message emitted by ws_stream.py after resolution.- QHash<QString, QString> ws_symbol_map_;- void handle_ws_line(const QString& line);- void drain_ws_buffer();-- mutable QMutex mutex_;};} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeSession.cpp b/fincept-qt/src/trading/ExchangeSession.cppnew file mode 100644index 000000000..14e490d9b--- /dev/null+++ b/fincept-qt/src/trading/ExchangeSession.cpp@@ -0,0 +1,703 @@+#include "trading/ExchangeSession.h"++#include "core/logging/Logger.h"+#include "python/PythonRunner.h"+#include "storage/secure/SecureStorage.h"+#include "trading/BrokerRegistry.h"+#include "trading/ExchangeDaemonPool.h"++#include <QElapsedTimer>+#include <QJsonArray>+#include <QJsonDocument>+#include <QMutexLocker>+#include <QPointer>+#include <QTimer>++namespace fincept::trading {++namespace {+const QString kSessionTag = "ExchangeSession";++// 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.+QString creds_key(const QString& exchange, const QString& field) {+ return QStringLiteral("crypto:") + exchange + QLatin1Char(':') + field;+}++QString session_resolve_script_path(const QString& relative) {+ const QString dir = fincept::python::PythonRunner::instance().scripts_dir();+ if (dir.isEmpty())+ return {};+ return dir + "/" + relative;+}++bool session_is_broker_stream(const QString& id) {+ return fincept::trading::BrokerRegistry::instance().has(id);+}++QStringList session_to_broker_symbol_args(const QStringList& symbols) {+ QStringList out;+ out.reserve(symbols.size());+ for (const auto& s : symbols) {+ QString sym = s.trimmed();+ if (sym.isEmpty())+ continue;+ QString exchange = "NSE";+ if (sym.contains(':')) {+ exchange = sym.section(':', 0, 0).trimmed().toUpper();+ sym = sym.section(':', 1).trimmed();+ }+ out << (sym + ":" + exchange + ":0");+ }+ return out;+}+} // namespace++ExchangeSession::ExchangeSession(const QString& exchange_id, SessionPublisher publisher, QObject* parent)+ : QObject(parent), exchange_id_(exchange_id), publisher_(std::move(publisher)) {+ // Phase 5: rehydrate any previously-saved credentials for this exchange+ // so users don't have to re-enter API keys on every launch.+ load_stored_credentials();+}++ExchangeSession::~ExchangeSession() {+ stop_ws();+}++// ── Credentials ────────────────────────────────────────────────────────────++void ExchangeSession::set_credentials(const ExchangeCredentials& creds) {+ {+ QMutexLocker lock(&mutex_);+ credentials_ = creds;+ }+ // Tell the shared daemon pool to resend on next call (it fingerprints+ // per-exchange, so no wasted writes if the key didn't actually change).+ ExchangeDaemonPool::instance().forget_credentials(exchange_id_);++ // Persist to OS-native encrypted storage so the next launch recovers+ // these without prompting. Empty fields map to a remove() so clearing+ // credentials actually wipes them from disk. A failure to persist is+ // non-fatal — the in-memory credentials still drive this session.+ auto& ss = fincept::SecureStorage::instance();+ const QString k_api = creds_key(exchange_id_, "api_key");+ const QString k_sec = creds_key(exchange_id_, "secret");+ const QString k_pw = creds_key(exchange_id_, "password");++ auto put_or_remove = [&](const QString& key, const QString& value) {+ if (value.isEmpty()) {+ (void) ss.remove(key);+ } else {+ auto r = ss.store(key, value);+ if (r.is_err())+ LOG_WARN(kSessionTag, QString("SecureStorage: failed to persist %1").arg(key));+ }+ };+ put_or_remove(k_api, creds.api_key);+ put_or_remove(k_sec, creds.secret);+ put_or_remove(k_pw, creds.password);++ LOG_INFO(kSessionTag, QString("Credentials updated for %1 (persisted=%2)")+ .arg(exchange_id_, creds.api_key.isEmpty() ? "no" : "yes"));+}++void ExchangeSession::load_stored_credentials() {+ auto& ss = fincept::SecureStorage::instance();+ ExchangeCredentials next;+ {+ QMutexLocker lock(&mutex_);+ next = credentials_;+ }+ const auto r_api = ss.retrieve(creds_key(exchange_id_, "api_key"));+ if (r_api.is_ok() && !r_api.value().isEmpty())+ next.api_key = r_api.value();+ const auto r_sec = ss.retrieve(creds_key(exchange_id_, "secret"));+ if (r_sec.is_ok() && !r_sec.value().isEmpty())+ next.secret = r_sec.value();+ const auto r_pw = ss.retrieve(creds_key(exchange_id_, "password"));+ if (r_pw.is_ok() && !r_pw.value().isEmpty())+ next.password = r_pw.value();++ if (next.api_key.isEmpty() && next.secret.isEmpty() && next.password.isEmpty())+ return; // nothing stored — leave session state as-is++ {+ QMutexLocker lock(&mutex_);+ credentials_ = next;+ }+ // Invalidate any cached "already sent" state on the daemon so the next+ // RPC picks up the restored keys.+ ExchangeDaemonPool::instance().forget_credentials(exchange_id_);+ LOG_INFO(kSessionTag, "Restored stored credentials for " + exchange_id_);+}++ExchangeCredentials ExchangeSession::get_credentials() const {+ QMutexLocker lock(&mutex_);+ return credentials_;+}++// ── Daemon RPC helper ──────────────────────────────────────────────────────++QJsonObject ExchangeSession::daemon_call(const QString& method, const QJsonObject& args, int timeout_ms) {+ ExchangeCredentials creds;+ {+ QMutexLocker lock(&mutex_);+ creds = credentials_;+ }+ return ExchangeDaemonPool::instance().call(exchange_id_, method, args, creds, timeout_ms);+}++// ── Watch management ───────────────────────────────────────────────────────++void ExchangeSession::watch_symbol(const QString& symbol, const QString& portfolio_id) {+ QMutexLocker lock(&mutex_);+ watched_[symbol].insert(portfolio_id);+}++void ExchangeSession::unwatch_symbol(const QString& symbol, const QString& portfolio_id) {+ QMutexLocker lock(&mutex_);+ auto it = watched_.find(symbol);+ if (it != watched_.end()) {+ it->remove(portfolio_id);+ if (it->isEmpty())+ watched_.erase(it);+ }+}++QHash<QString, QSet<QString>> ExchangeSession::snapshot_watched() const {+ QMutexLocker lock(&mutex_);+ return watched_;+}++// ── Callbacks ──────────────────────────────────────────────────────────────++// ── WS lifecycle ───────────────────────────────────────────────────────────++bool ExchangeSession::start_ws(const QString& primary_symbol, const QStringList& all_symbols) {+ stop_ws();++ ws_primary_symbol_ = primary_symbol;+ ws_all_symbols_ = all_symbols;++ const QString python_path = python::PythonRunner::instance().python_path();+ QString script_path;+ QStringList args;++ if (session_is_broker_stream(exchange_id_)) {+ script_path = session_resolve_script_path("exchange/broker_ws_bridge.py");+ if (python_path.isEmpty() || script_path.isEmpty()) {+ LOG_ERROR(kSessionTag, "Python or broker_ws_bridge.py not found");+ return false;+ }+ auto* broker = BrokerRegistry::instance().get(exchange_id_);+ if (!broker) {+ LOG_ERROR(kSessionTag, "Broker stream requested but broker is not registered: " + exchange_id_);+ return false;+ }+ auto creds = broker->load_credentials();+ if (creds.api_key.isEmpty() || creds.access_token.isEmpty()) {+ LOG_ERROR(kSessionTag, "Broker stream credentials missing for " + exchange_id_);+ return false;+ }+ QString feed_token;+ QString user_id = creds.user_id;+ if (!creds.additional_data.isEmpty()) {+ const auto ad = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();+ if (user_id.isEmpty())+ user_id = ad.value("client_code").toString();+ feed_token = ad.value("feed_token").toString();+ }+ if (user_id.isEmpty())+ user_id = creds.api_key;++ QStringList broker_symbols = session_to_broker_symbol_args(all_symbols);+ if (broker_symbols.isEmpty())+ broker_symbols = session_to_broker_symbol_args({primary_symbol});+ if (broker_symbols.isEmpty()) {+ LOG_ERROR(kSessionTag, "No symbols provided for broker websocket stream");+ return false;+ }+ args << "-u" << "-B" << script_path << exchange_id_ << creds.api_key << creds.access_token << user_id;+ if (!feed_token.isEmpty())+ args << "--feed-token" << feed_token;+ args << "--symbols";+ args.append(broker_symbols);+ } else {+ script_path = session_resolve_script_path("exchange/ws_stream.py");+ if (python_path.isEmpty() || script_path.isEmpty()) {+ LOG_ERROR(kSessionTag, "Python or ws_stream.py not found");+ return false;+ }+ args << "-u" << "-B" << script_path << exchange_id_;+ for (const auto& sym : all_symbols)+ args << sym;+ }++ ws_process_ = new QProcess(this);+ connect(ws_process_, &QProcess::readyReadStandardOutput, this, &ExchangeSession::drain_ws_buffer);+ connect(ws_process_, &QProcess::readyReadStandardError, this, [this]() {+ if (!ws_process_)+ return;+ const QString err = QString::fromUtf8(ws_process_->readAllStandardError()).trimmed();+ if (!err.isEmpty())+ LOG_WARN(kSessionTag, QString("[%1] WS stderr: %2").arg(exchange_id_, err));+ });+ connect(ws_process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {+ LOG_ERROR(kSessionTag, QString("[%1] WS process errorOccurred: %2")+ .arg(exchange_id_)+ .arg(static_cast<int>(err)));+ ws_connected_ = false;+ });++ ws_process_->start(python_path, args);+ LOG_INFO(kSessionTag, QString("WS stream start requested for %1/%2").arg(exchange_id_, primary_symbol));+ return true;+}++bool ExchangeSession::is_ws_active() const {+ return ws_process_ != nullptr && ws_process_->state() != QProcess::NotRunning;+}++void ExchangeSession::stop_ws() {+ if (!ws_process_)+ return;+ auto* proc = ws_process_;+ ws_process_ = nullptr;+ ws_connected_ = false;+ proc->disconnect(this);+ proc->terminate();+ connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), proc, &QObject::deleteLater);+ QTimer::singleShot(3000, proc, [proc]() {+ if (proc->state() != QProcess::NotRunning)+ proc->kill();+ });+}++void ExchangeSession::set_ws_primary_symbol(const QString& symbol) {+ QMutexLocker lock(&mutex_);+ ws_primary_symbol_ = symbol;+}++QString ExchangeSession::get_ws_primary_symbol() const {+ QMutexLocker lock(&mutex_);+ return ws_primary_symbol_;+}++// ── WS line handler (ported from ExchangeService::handle_ws_line) ──────────++QString ExchangeSession::remap_symbol(const QString& exchange_symbol) const {+ QMutexLocker lock(&mutex_);+ auto it = ws_symbol_map_.constFind(exchange_symbol);+ return (it == ws_symbol_map_.constEnd()) ? exchange_symbol : it.value();+}++void ExchangeSession::handle_ws_line(const QString& line) {+ if (line.isEmpty() || line[0] != '{')+ return;+ QJsonParseError err;+ const auto doc = QJsonDocument::fromJson(line.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError)+ return;+ const auto msg = doc.object();+ const QString type = msg.value("type").toString();++ if (type == "status") {+ const bool connected = msg.value("connected").toBool(false);+ const bool prev = ws_connected_.exchange(connected);+ if (connected != prev) {+ LOG_INFO(kSessionTag,+ QString("[%1] WS status: %2").arg(exchange_id_, connected ? "CONNECTED" : "DISCONNECTED"));+ }+ if (!connected) {+ QMutexLocker lock(&mutex_);+ ws_symbol_map_.clear();+ }+ return;+ }++ if (type == "symbol_map") {+ QMutexLocker lock(&mutex_);+ ws_symbol_map_.clear();+ const auto map_obj = msg.value("map").toObject();+ for (auto it = map_obj.constBegin(); it != map_obj.constEnd(); ++it)+ ws_symbol_map_[it.key()] = it.value().toString();+ LOG_INFO(kSessionTag,+ QString("[%1] Symbol map updated: %2 remaps").arg(exchange_id_).arg(ws_symbol_map_.size()));+ return;+ }++ if (type == "ticker" || type == "tick") {+ TickerData ticker;+ if (type == "tick") {+ ticker.symbol = msg.value("symbol").toString();+ ticker.last = msg.value("ltp").toDouble();+ ticker.bid = msg.value("bid").toDouble();+ ticker.ask = msg.value("ask").toDouble();+ ticker.high = msg.value("high").toDouble();+ ticker.low = msg.value("low").toDouble();+ ticker.open = msg.value("open").toDouble();+ ticker.close = msg.value("close").toDouble();+ ticker.base_volume = msg.value("volume").toDouble();+ ticker.timestamp = msg.value("timestamp").toVariant().toLongLong();+ } else {+ QJsonObject normalised = msg;+ if (!msg.contains("baseVolume") && msg.contains("base_volume"))+ normalised["baseVolume"] = msg.value("base_volume");+ if (!msg.contains("quoteVolume") && msg.contains("quote_volume"))+ normalised["quoteVolume"] = msg.value("quote_volume");+ ticker = parse_ticker(normalised);+ }+ if (ticker.symbol.isEmpty() || ticker.last <= 0.0)+ return;+ // Remap exchange_symbol → requested_symbol so downstream consumers+ // (cache, hub topics) all key by the symbol the caller asked for.+ // e.g. on Hyperliquid: "BTC/USDC:USDC" → "BTC/USDT".+ ticker.symbol = remap_symbol(ticker.symbol);+ {+ QMutexLocker lock(&mutex_);+ price_cache_[ticker.symbol] = ticker;+ }+ if (publisher_.publish_ticker)+ publisher_.publish_ticker(exchange_id_, ticker.symbol, ticker);+ return;+ }++ if (type == "orderbook") {+ OrderBookData ob = parse_orderbook(msg);+ // Apply the same exchange→requested symbol remap as tickers, so+ // per-symbol topics are consistent across all WS message types.+ ob.symbol = remap_symbol(ob.symbol);+ if (publisher_.publish_orderbook)+ publisher_.publish_orderbook(exchange_id_, ob.symbol, ob);+ return;+ }++ if (type == "candle" || type == "ohlcv") {+ QJsonObject candle_obj = (type == "ohlcv") ? msg.value("candle").toObject() : msg;+ Candle c = parse_candle(candle_obj);+ const QString raw_sym = msg.value("symbol").toString();+ if (raw_sym.isEmpty() || c.timestamp == 0)+ return;+ const QString sym = remap_symbol(raw_sym);+ const QString interval = msg.value("interval").toString("1m");+ if (publisher_.publish_candle)+ publisher_.publish_candle(exchange_id_, sym, interval, c);+ return;+ }++ if (type == "trade") {+ TradeData td;+ td.symbol = remap_symbol(msg.value("symbol").toString());+ td.side = msg.value("side").toString();+ td.price = msg.value("price").toDouble();+ td.amount = msg.value("amount").toDouble();+ td.timestamp = msg.value("timestamp").toVariant().toLongLong();+ if (td.symbol.isEmpty())+ return;++ // Fast-path ticker update from trade — on exchanges where watch_ticker+ // is slow (e.g. Kraken spot ~2/15s), trade flow keeps price_cache_+ // current. Publish a synthetic ticker alongside so the hub's+ // ticker:<pair> topic stays fresh.+ TickerData fast_ticker;+ bool emit_ticker = false;+ if (td.price > 0.0) {+ QMutexLocker lock(&mutex_);+ auto& cached = price_cache_[td.symbol];+ cached.symbol = td.symbol;+ cached.last = td.price;+ if (cached.bid <= 0.0)+ cached.bid = td.price;+ if (cached.ask <= 0.0)+ cached.ask = td.price;+ fast_ticker = cached;+ emit_ticker = true;+ }++ if (publisher_.publish_trade)+ publisher_.publish_trade(exchange_id_, td.symbol, td);+ if (emit_ticker && publisher_.publish_ticker)+ publisher_.publish_ticker(exchange_id_, fast_ticker.symbol, fast_ticker);+ }+}++void ExchangeSession::drain_ws_buffer() {+ if (!ws_process_)+ return;+ int processed = 0;+ constexpr int MAX_LINES_PER_CYCLE = 50;+ constexpr qint64 MAX_MS_PER_CYCLE = 4;+ QElapsedTimer elapsed;+ elapsed.start();+ while (ws_process_->canReadLine() && processed < MAX_LINES_PER_CYCLE) {+ const QString line = QString::fromUtf8(ws_process_->readLine()).trimmed();+ if (!line.isEmpty())+ handle_ws_line(line);+ ++processed;+ if (elapsed.elapsed() >= MAX_MS_PER_CYCLE)+ break;+ }+ if (ws_process_ && ws_process_->canReadLine()) {+ QPointer<ExchangeSession> self = this;+ QTimer::singleShot(1, this, [self]() {+ if (self) self->drain_ws_buffer();+ });+ }+}++// ── Parsers ────────────────────────────────────────────────────────────────++TickerData ExchangeSession::parse_ticker(const QJsonObject& j) {+ TickerData t;+ t.symbol = j.value("symbol").toString();+ t.last = j.value("last").toDouble();+ t.bid = j.value("bid").toDouble();+ t.ask = j.value("ask").toDouble();+ t.high = j.value("high").toDouble();+ t.low = j.value("low").toDouble();+ t.open = j.value("open").toDouble();+ t.close = j.value("close").toDouble();+ t.change = j.value("change").toDouble();+ t.percentage = j.value("percentage").toDouble();+ t.base_volume = j.value("baseVolume").toDouble();+ t.quote_volume = j.value("quoteVolume").toDouble();+ t.timestamp = j.value("timestamp").toVariant().toLongLong();+ return t;+}++OrderBookData ExchangeSession::parse_orderbook(const QJsonObject& j) {+ OrderBookData ob;+ ob.symbol = j.value("symbol").toString();+ const auto bids = j.value("bids").toArray();+ for (const auto& b : bids) {+ const auto arr = b.toArray();+ if (arr.size() >= 2)+ ob.bids.append({arr[0].toDouble(), arr[1].toDouble()});+ }+ const auto asks = j.value("asks").toArray();+ for (const auto& a : asks) {+ const auto arr = a.toArray();+ if (arr.size() >= 2)+ ob.asks.append({arr[0].toDouble(), arr[1].toDouble()});+ }+ if (!ob.bids.isEmpty())+ ob.best_bid = ob.bids.first().first;+ if (!ob.asks.isEmpty())+ ob.best_ask = ob.asks.first().first;+ if (ob.best_bid > 0 && ob.best_ask > 0) {+ ob.spread = ob.best_ask - ob.best_bid;+ ob.spread_pct = (ob.spread / ob.best_ask) * 100.0;+ }+ return ob;+}++Candle ExchangeSession::parse_candle(const QJsonObject& j) {+ Candle c;+ c.timestamp = j.value("timestamp").toVariant().toLongLong();+ c.open = j.value("open").toDouble();+ c.high = j.value("high").toDouble();+ c.low = j.value("low").toDouble();+ c.close = j.value("close").toDouble();+ c.volume = j.value("volume").toDouble();+ return c;+}++MarketInfo ExchangeSession::parse_market(const QJsonObject& j) {+ MarketInfo m;+ m.symbol = j.value("symbol").toString();+ m.base = j.value("base").toString();+ m.quote = j.value("quote").toString();+ m.type = j.value("type").toString();+ m.active = j.value("active").toBool(true);+ m.maker_fee = j.value("maker").toDouble();+ m.taker_fee = j.value("taker").toDouble();+ m.min_amount = j.value("minAmount").toDouble();+ m.min_cost = j.value("minCost").toDouble();+ return m;+}++// ── One-shot REST fetches — all via the shared daemon pool ─────────────────++TickerData ExchangeSession::fetch_ticker(const QString& symbol) {+ const auto j = daemon_call("fetch_ticker", {{"symbol", symbol}});+ if (j.contains("error"))+ return {};+ return parse_ticker(j);+}++QVector<TickerData> ExchangeSession::fetch_tickers(const QStringList& symbols) {+ QJsonArray sym_arr;+ for (const auto& s : symbols)+ sym_arr.append(s);+ const auto j = daemon_call("fetch_tickers", {{"symbols", sym_arr}});+ QVector<TickerData> result;+ if (j.contains("error") || !j.contains("tickers"))+ return result;+ const auto arr = j.value("tickers").toArray();+ for (const auto& item : arr)+ result.append(parse_ticker(item.toObject()));+ return result;+}++OrderBookData ExchangeSession::fetch_orderbook(const QString& symbol, int limit) {+ const auto j = daemon_call("fetch_orderbook", {{"symbol", symbol}, {"limit", limit}});+ if (j.contains("error"))+ return {};+ return parse_orderbook(j);+}++QVector<Candle> ExchangeSession::fetch_ohlcv(const QString& symbol, const QString& timeframe, int limit) {+ const auto j = daemon_call("fetch_ohlcv", {{"symbol", symbol}, {"timeframe", timeframe}, {"limit", limit}});+ QVector<Candle> result;+ if (j.contains("error") || !j.contains("candles"))+ return result;+ const auto arr = j.value("candles").toArray();+ for (const auto& item : arr)+ result.append(parse_candle(item.toObject()));+ return result;+}++QVector<MarketInfo> ExchangeSession::fetch_markets(const QString& type, const QString& query) {+ QJsonObject args;+ if (!type.isEmpty())+ args["type"] = type;+ if (!query.isEmpty()) {+ args["query"] = query;+ args["limit"] = 100;+ }+ const auto j = daemon_call("fetch_markets", args);+ QVector<MarketInfo> result;+ if (j.contains("error") || !j.contains("markets"))+ return result;+ const auto arr = j.value("markets").toArray();+ for (const auto& item : arr)+ result.append(parse_market(item.toObject()));+ return result;+}++QVector<TradeData> ExchangeSession::fetch_trades(const QString& symbol, int limit) {+ const auto j = daemon_call("fetch_trades", {{"symbol", symbol}, {"limit", limit}});+ QVector<TradeData> result;+ if (j.contains("error") || !j.contains("trades"))+ return result;+ const auto arr = j.value("trades").toArray();+ for (const auto& item : arr) {+ const auto o = item.toObject();+ TradeData td;+ td.id = o.value("id").toString();+ td.symbol = o.value("symbol").toString();+ td.side = o.value("side").toString();+ td.price = o.value("price").toDouble();+ td.amount = o.value("amount").toDouble();+ td.cost = o.value("cost").toDouble();+ td.timestamp = o.value("timestamp").toVariant().toLongLong();+ result.append(td);+ }+ return result;+}++FundingRateData ExchangeSession::fetch_funding_rate(const QString& symbol) {+ const auto j = daemon_call("fetch_funding_rate", {{"symbol", symbol}});+ FundingRateData fr;+ if (!j.contains("error")) {+ fr.symbol = j.value("symbol").toString();+ fr.funding_rate = j.value("funding_rate").toDouble();+ fr.mark_price = j.value("mark_price").toDouble();+ fr.index_price = j.value("index_price").toDouble();+ fr.funding_timestamp = j.value("funding_timestamp").toVariant().toLongLong();+ fr.next_funding_timestamp = j.value("next_funding_timestamp").toVariant().toLongLong();+ }+ return fr;+}++OpenInterestData ExchangeSession::fetch_open_interest(const QString& symbol) {+ const auto j = daemon_call("fetch_open_interest", {{"symbol", symbol}});+ OpenInterestData oi;+ if (!j.contains("error")) {+ oi.symbol = j.value("symbol").toString();+ oi.open_interest = j.value("open_interest").toDouble();+ oi.open_interest_value = j.value("open_interest_value").toDouble();+ oi.timestamp = j.value("timestamp").toVariant().toLongLong();+ }+ return oi;+}++MarkPriceData ExchangeSession::fetch_mark_price(const QString& symbol) {+ const auto j = daemon_call("fetch_mark_price", {{"symbol", symbol}});+ MarkPriceData mp;+ mp.symbol = symbol;+ if (!j.contains("error")) {+ mp.mark_price = j.value("mark_price").toDouble();+ mp.index_price = j.value("index_price").toDouble();+ mp.timestamp = j.value("timestamp").toVariant().toLongLong();+ }+ return mp;+}++QJsonObject ExchangeSession::fetch_balance() {+ return daemon_call("fetch_balance", {});+}++QJsonObject ExchangeSession::place_exchange_order(const QString& symbol, const QString& side, const QString& type,+ double amount, double price) {+ QJsonObject args;+ args["symbol"] = symbol;+ args["side"] = side;+ args["type"] = type;+ args["amount"] = amount;+ if (price > 0)+ args["price"] = price;+ return daemon_call("place_order", args);+}++QJsonObject ExchangeSession::cancel_exchange_order(const QString& order_id, const QString& symbol) {+ return daemon_call("cancel_order", {{"order_id", order_id}, {"symbol", symbol}});+}++QJsonObject ExchangeSession::fetch_positions_live(const QString& symbol) {+ QJsonObject args;+ if (!symbol.isEmpty())+ args["symbol"] = symbol;+ return daemon_call("fetch_positions", args);+}++QJsonObject ExchangeSession::fetch_open_orders_live(const QString& symbol) {+ QJsonObject args;+ if (!symbol.isEmpty())+ args["symbol"] = symbol;+ return daemon_call("fetch_open_orders", args);+}++QJsonObject ExchangeSession::fetch_my_trades(const QString& symbol, int limit) {+ return daemon_call("fetch_my_trades", {{"symbol", symbol}, {"limit", limit}});+}++QJsonObject ExchangeSession::fetch_trading_fees(const QString& symbol) {+ QJsonObject args;+ if (!symbol.isEmpty())+ args["symbol"] = symbol;+ return daemon_call("fetch_trading_fees", args);+}++QJsonObject ExchangeSession::set_leverage(const QString& symbol, int leverage) {+ return daemon_call("set_leverage", {{"symbol", symbol}, {"leverage", leverage}});+}++QJsonObject ExchangeSession::set_margin_mode(const QString& symbol, const QString& mode) {+ return daemon_call("set_margin_mode", {{"symbol", symbol}, {"mode", mode}});+}++// ── Cache accessors ────────────────────────────────────────────────────────++TickerData ExchangeSession::get_cached_price(const QString& symbol) const {+ QMutexLocker lock(&mutex_);+ return price_cache_.value(symbol);+}++QHash<QString, TickerData> ExchangeSession::snapshot_price_cache() const {+ QMutexLocker lock(&mutex_);+ return price_cache_;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeSession.h b/fincept-qt/src/trading/ExchangeSession.hnew file mode 100644index 000000000..d2d24f2cd--- /dev/null+++ b/fincept-qt/src/trading/ExchangeSession.h@@ -0,0 +1,152 @@+#pragma once+// ExchangeSession — one exchange's live state.+//+// Each session owns the WS subprocess, price cache, symbol remap table,+// primary-symbol marker, watched-symbol set, and credentials for exactly+// ONE exchange. Sessions share one `ExchangeDaemonPool` (for REST calls)+// but never share WS pipes — a Kraken session and a Hyperliquid session+// each run their own `ws_stream.py` process.+//+// ExchangeSessionManager holds the live sessions and is responsible for all+// DataHub publishing; a session hands off fan-out data to the manager via a+// SessionPublisher injected at construction. This keeps sessions free of+// DataHub headers and centralises topic policies in the manager.+//+// Threading:+// - session is created and destroyed on the main thread+// - WS I/O is driven by QProcess signals on the main thread+// - REST fetches (`fetch_*` / `place_*` / `cancel_*`) must be called from a+// worker thread; they block up to `ExchangeDaemonPool::call` timeout.++#include "trading/TradingTypes.h"++#include <QHash>+#include <QJsonObject>+#include <QMutex>+#include <QObject>+#include <QProcess>+#include <QSet>+#include <QStringList>++#include <atomic>+#include <functional>++namespace fincept::trading {++/// Thin publisher seam. The manager injects one of these at construction so+/// sessions never pull in DataHub headers themselves.+struct SessionPublisher {+ std::function<void(const QString& exchange, const QString& pair, const TickerData&)> publish_ticker;+ std::function<void(const QString& exchange, const QString& pair, const OrderBookData&)> publish_orderbook;+ std::function<void(const QString& exchange, const QString& pair, const TradeData&)> publish_trade;+ std::function<void(const QString& exchange, const QString& pair, const QString& interval, const Candle&)>+ publish_candle;+};++class ExchangeSession : public QObject {+ Q_OBJECT+ public:+ explicit ExchangeSession(const QString& exchange_id,+ SessionPublisher publisher,+ QObject* parent = nullptr);+ ~ExchangeSession() override;++ QString exchange_id() const { return exchange_id_; }++ // ── Credentials ────────────────────────────────────────────────────────+ /// Store credentials for this exchange. Persists to SecureStorage under+ /// `crypto:<exchange>:{api_key,secret,password}` so the next app launch+ /// picks them up automatically. Pass an empty-fields struct to clear.+ void set_credentials(const ExchangeCredentials& creds);+ ExchangeCredentials get_credentials() const;++ /// Load any previously-persisted credentials for this exchange from+ /// SecureStorage and install them on the session. Idempotent — missing+ /// keys leave the current credential fields untouched. Called+ /// automatically from the constructor; exposed for tests.+ void load_stored_credentials();++ // ── WS lifecycle ───────────────────────────────────────────────────────+ /// Returns true if the WS subprocess was spawned; see+ /// ExchangeService::start_ws_stream for full semantics.+ bool start_ws(const QString& primary_symbol, const QStringList& all_symbols);+ void stop_ws();+ bool is_ws_connected() const { return ws_connected_.load(); }+ /// True once a WS subprocess has been spawned and has not yet exited.+ /// Distinct from `is_ws_connected` — the process may be up but the remote+ /// handshake still pending. Used by the session manager to avoid+ /// re-spawning when switching back to a session that's already live.+ bool is_ws_active() const;+ void set_ws_primary_symbol(const QString& symbol);+ QString get_ws_primary_symbol() const;++ // ── Watch management (for paper-trading bookkeeping) ───────────────────+ void watch_symbol(const QString& symbol, const QString& portfolio_id);+ void unwatch_symbol(const QString& symbol, const QString& portfolio_id);+ QHash<QString, QSet<QString>> snapshot_watched() const;++ // ── One-shot REST fetches via the shared daemon pool.+ // Call from a worker thread only — these block up to ~15s.+ TickerData fetch_ticker(const QString& symbol);+ QVector<TickerData> fetch_tickers(const QStringList& symbols);+ OrderBookData fetch_orderbook(const QString& symbol, int limit = 20);+ QVector<Candle> fetch_ohlcv(const QString& symbol, const QString& timeframe = "1h", int limit = 100);+ QVector<MarketInfo> fetch_markets(const QString& type = "", const QString& query = "");+ QVector<TradeData> fetch_trades(const QString& symbol, int limit = 50);+ FundingRateData fetch_funding_rate(const QString& symbol);+ OpenInterestData fetch_open_interest(const QString& symbol);+ MarkPriceData fetch_mark_price(const QString& symbol);++ // ── Authenticated — need credentials on the daemon.+ QJsonObject fetch_balance();+ QJsonObject place_exchange_order(const QString& symbol, const QString& side, const QString& type, double amount,+ double price = 0.0);+ QJsonObject cancel_exchange_order(const QString& order_id, const QString& symbol);+ QJsonObject fetch_positions_live(const QString& symbol = "");+ QJsonObject fetch_open_orders_live(const QString& symbol = "");+ QJsonObject fetch_my_trades(const QString& symbol, int limit = 50);+ QJsonObject fetch_trading_fees(const QString& symbol = "");+ QJsonObject set_leverage(const QString& symbol, int leverage);+ QJsonObject set_margin_mode(const QString& symbol, const QString& mode);++ // ── Cache ──────────────────────────────────────────────────────────────+ TickerData get_cached_price(const QString& symbol) const;+ QHash<QString, TickerData> snapshot_price_cache() const;++ ExchangeSession(const ExchangeSession&) = delete;+ ExchangeSession& operator=(const ExchangeSession&) = delete;++ private:+ void handle_ws_line(const QString& line);+ void drain_ws_buffer();++ /// 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.+ QString remap_symbol(const QString& exchange_symbol) const;++ QJsonObject daemon_call(const QString& method, const QJsonObject& args, int timeout_ms = 15000);++ static TickerData parse_ticker(const QJsonObject& j);+ static OrderBookData parse_orderbook(const QJsonObject& j);+ static Candle parse_candle(const QJsonObject& j);+ static MarketInfo parse_market(const QJsonObject& j);++ const QString exchange_id_;+ SessionPublisher publisher_;++ ExchangeCredentials credentials_;++ QProcess* ws_process_ = nullptr;+ std::atomic<bool> ws_connected_{false};+ QString ws_primary_symbol_;+ QStringList ws_all_symbols_;+ QHash<QString, QString> ws_symbol_map_; // exchange_symbol → requested_symbol++ QHash<QString, TickerData> price_cache_;+ QHash<QString, QSet<QString>> watched_; // symbol → set of portfolio_ids++ mutable QMutex mutex_;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeSessionManager.cpp b/fincept-qt/src/trading/ExchangeSessionManager.cppnew file mode 100644index 000000000..0775cd36c--- /dev/null+++ b/fincept-qt/src/trading/ExchangeSessionManager.cpp@@ -0,0 +1,135 @@+#include "trading/ExchangeSessionManager.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "datahub/DataHubMetaTypes.h"++#include <QMutexLocker>+#include <QVariant>++namespace fincept::trading {++namespace {+const QString kMgrTag = "ExchangeSessionManager";++// Exchanges whose meta-types are registered with DataHub. Other exchanges+// still work through the session (callbacks + direct consumer reads) — they+// just aren't published on the hub yet. Add here as metatypes land.+bool hub_supported_exchange(const QString& id) {+ return id == QLatin1String("kraken") || id == QLatin1String("hyperliquid");+}+} // namespace++ExchangeSessionManager& ExchangeSessionManager::instance() {+ static ExchangeSessionManager s;+ return s;+}++ExchangeSessionManager::ExchangeSessionManager() = default;++ExchangeSessionManager::~ExchangeSessionManager() {+ // Sessions are owned via Qt parent/child (this). Qt would destroy them+ // automatically at manager destruction, but call their WS teardown now+ // so the Python subprocesses exit cleanly before Qt tears everything down.+ QMutexLocker lock(&mutex_);+ qDeleteAll(sessions_);+ sessions_.clear();+}++ExchangeSession* ExchangeSessionManager::session(const QString& exchange_id) {+ QMutexLocker lock(&mutex_);+ auto it = sessions_.find(exchange_id);+ if (it != sessions_.end())+ return it.value();++ // First touch for this exchange — construct a session with a publisher+ // that routes its fan-out to DataHub via the manager's policies.+ auto* s = new ExchangeSession(exchange_id, build_publisher(), this);+ sessions_.insert(exchange_id, s);+ LOG_INFO(kMgrTag, "Created ExchangeSession for " + exchange_id);+ return s;+}++QStringList ExchangeSessionManager::active_exchange_ids() const {+ QMutexLocker lock(&mutex_);+ QStringList ids;+ ids.reserve(sessions_.size());+ for (auto it = sessions_.constBegin(); it != sessions_.constEnd(); ++it)+ ids << it.key();+ return ids;+}++SessionPublisher ExchangeSessionManager::build_publisher() {+ SessionPublisher p;+ p.publish_ticker = [](const QString& exchange, const QString& pair, const TickerData& t) {+ if (!hub_supported_exchange(exchange) || pair.isEmpty())+ return;+ const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":ticker:") + pair;+ fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(t));+ };+ p.publish_orderbook = [](const QString& exchange, const QString& pair, const OrderBookData& ob) {+ if (!hub_supported_exchange(exchange) || pair.isEmpty())+ return;+ const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":orderbook:") + pair;+ fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(ob));+ };+ p.publish_trade = [](const QString& exchange, const QString& pair, const TradeData& td) {+ if (!hub_supported_exchange(exchange) || pair.isEmpty())+ return;+ const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":trades:") + pair;+ fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(td));+ };+ p.publish_candle = [](const QString& exchange, const QString& pair, const QString& interval, const Candle& c) {+ if (!hub_supported_exchange(exchange) || pair.isEmpty())+ return;+ const QString topic = QStringLiteral("ws:") + exchange + QStringLiteral(":ohlc:") + pair ++ QLatin1Char(':') + interval;+ fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(c));+ };+ return p;+}++// ── Producer ────────────────────────────────────────────────────────────────++QStringList ExchangeSessionManager::topic_patterns() const {+ return {"ws:kraken:*", "ws:hyperliquid:*"};+}++void ExchangeSessionManager::refresh(const QStringList& /*topics*/) {+ // push_only — scheduler never calls this. Fan-out happens via+ // ExchangeSession → SessionPublisher → DataHub.+}++int ExchangeSessionManager::max_requests_per_sec() const {+ return 0; // unlimited, push-only+}++void ExchangeSessionManager::ensure_registered_with_hub() {+ if (hub_registered_)+ return;+ auto& hub = fincept::datahub::DataHub::instance();+ hub.register_producer(this);++ fincept::datahub::TopicPolicy push_only;+ push_only.push_only = true;+ push_only.ttl_ms = 0;+ push_only.min_interval_ms = 0;++ fincept::datahub::TopicPolicy coalesced_ticker = push_only;+ coalesced_ticker.coalesce_within_ms = 50; // 20 Hz fan-out cap++ hub.set_policy_pattern("ws:kraken:ticker:*", coalesced_ticker);+ hub.set_policy_pattern("ws:hyperliquid:ticker:*", coalesced_ticker);++ hub.set_policy_pattern("ws:kraken:orderbook:*", push_only);+ hub.set_policy_pattern("ws:kraken:trades:*", push_only);+ hub.set_policy_pattern("ws:kraken:ohlc:*", push_only);+ hub.set_policy_pattern("ws:hyperliquid:orderbook:*", push_only);+ hub.set_policy_pattern("ws:hyperliquid:trades:*", push_only);+ hub.set_policy_pattern("ws:hyperliquid:ohlc:*", push_only);++ hub_registered_ = true;+ LOG_INFO(kMgrTag, "Registered with DataHub (ws:kraken:*, ws:hyperliquid:*)");+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ExchangeSessionManager.h b/fincept-qt/src/trading/ExchangeSessionManager.hnew file mode 100644index 000000000..2066aa985--- /dev/null+++ b/fincept-qt/src/trading/ExchangeSessionManager.h@@ -0,0 +1,67 @@+#pragma once+// ExchangeSessionManager — registry of live ExchangeSession objects.+//+// Lazy-creates one ExchangeSession per exchange id on demand. Sessions stay+// warm for the application lifetime (Bloomberg-style) — switching exchanges+// does not tear down the previous session's WS stream. This buys sub-500ms+// exchange switches because the daemon + WS handshake were already paid.+//+// This class (not the sessions) is the DataHub `Producer` for the whole+// `ws:*:*` family. When a session has fan-out data, it hands it to the+// manager via the `SessionPublisher` seam; the manager applies hub policies+// and publishes. Keeps topic semantics in one place.++#include "datahub/Producer.h"+#include "trading/ExchangeSession.h"++#include <QHash>+#include <QMutex>+#include <QObject>+#include <QString>+#include <QStringList>++namespace fincept::trading {++class ExchangeSessionManager : public QObject, public fincept::datahub::Producer {+ Q_OBJECT+ public:+ static ExchangeSessionManager& instance();++ /// Register with DataHub + install `ws:*:*` policies for supported+ /// exchanges. Idempotent.+ void ensure_registered_with_hub();++ /// Lazily create (if needed) and return the session for `exchange_id`.+ /// Thread-safe; the session outlives the caller's reference (owned by+ /// the manager).+ ExchangeSession* session(const QString& exchange_id);++ /// Snapshot of currently-live exchange ids.+ QStringList active_exchange_ids() const;++ // ── Producer ───────────────────────────────────────────────────────────+ QStringList topic_patterns() const override;+ void refresh(const QStringList& topics) override; // no-op: push_only+ int max_requests_per_sec() const override; // 0 (unlimited: WS)++ ExchangeSessionManager(const ExchangeSessionManager&) = delete;+ ExchangeSessionManager& operator=(const ExchangeSessionManager&) = delete;++ private:+ ExchangeSessionManager();+ ~ExchangeSessionManager() override;++ // Publisher callbacks injected into each session. Applies per-topic policy+ // gating so unsupported exchanges simply drop to the floor.+ SessionPublisher build_publisher();++ bool hub_registered_ = false;++ mutable QMutex mutex_;+ // Owning pointers. Sessions are parented to `this` (the manager) so Qt+ // parent/child cleanup reaps them at manager destruction if the map+ // isn't explicitly cleared first.+ QHash<QString, ExchangeSession*> sessions_;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cppindex 1265bc21d..710f07ac1 100644--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp@@ -118,7 +118,7 @@ QMap<QString, QString> MotilalBroker::auth_headers(const BrokerCredentials& cred{"devicemodel", "PC"},{"manufacturer", "Generic"},{"productname", "FinceptTerminal"},- {"productversion", "4.0.2"},+ {"productversion", "4.0.1"},{"browsername", "Chrome"},{"browserversion", "120.0"},};@@ -161,7 +161,7 @@ TokenExchangeResponse MotilalBroker::exchange_token(const QString& api_key, cons{"devicemodel", "PC"},{"manufacturer", "Generic"},{"productname", "FinceptTerminal"},- {"productversion", "4.0.2"},+ {"productversion", "4.0.1"},{"browsername", "Chrome"},{"browserversion", "120.0"},};diff --git a/fincept-qt/src/ui/navigation/StatusBar.cpp b/fincept-qt/src/ui/navigation/StatusBar.cppindex 9c7455cf9..01ca121ae 100644--- a/fincept-qt/src/ui/navigation/StatusBar.cpp+++ b/fincept-qt/src/ui/navigation/StatusBar.cpp@@ -19,7 +19,7 @@ StatusBar::StatusBar(QWidget* parent) : QWidget(parent) {return l;};- hl->addWidget(mk("v4.0.2", "sbVersion"));+ hl->addWidget(mk("v4.0.1", "sbVersion"));hl->addWidget(mk(" | ", "sbSep"));const char* feeds[] = {"EQ", "FX", "CM", "FI", "CR"};for (auto& f : feeds) {diff --git a/fincept-qt/src/ui/widgets/SpeedSparkline.cpp b/fincept-qt/src/ui/widgets/SpeedSparkline.cppnew file mode 100644index 000000000..2e3351729--- /dev/null+++ b/fincept-qt/src/ui/widgets/SpeedSparkline.cpp@@ -0,0 +1,85 @@+// src/ui/widgets/SpeedSparkline.cpp+#include "ui/widgets/SpeedSparkline.h"++#include <QPainter>+#include <QPainterPath>+#include <QtGlobal>+#include <algorithm>++namespace fincept::ui {++SpeedSparkline::SpeedSparkline(QWidget* parent) : QWidget(parent) {+ setAttribute(Qt::WA_OpaquePaintEvent, false);+ setMinimumSize(80, 18);+}++void SpeedSparkline::set_line_color(const QColor& c) {+ line_color_ = c;+ update();+}++void SpeedSparkline::set_fill_color(const QColor& c) {+ fill_color_ = c;+ update();+}++void SpeedSparkline::set_capacity(int samples) {+ capacity_ = std::max(4, samples);+ while (samples_.size() > capacity_)+ samples_.pop_front();+ update();+}++void SpeedSparkline::push(qint64 bytes_per_sec) {+ if (bytes_per_sec < 0)+ bytes_per_sec = 0;+ samples_.push_back(bytes_per_sec);+ while (samples_.size() > capacity_)+ samples_.pop_front();+ update();+}++void SpeedSparkline::paintEvent(QPaintEvent*) {+ QPainter p(this);+ const QRectF r = rect().adjusted(1, 1, -1, -1);++ if (samples_.isEmpty() || r.width() < 2 || r.height() < 2)+ return;++ qint64 peak = 0;+ for (qint64 v : samples_)+ peak = std::max(peak, v);+ // Floor so an idle meter still shows a visible baseline instead of a flat+ // spike when the first non-zero sample arrives.+ const double y_max = std::max<double>(peak, 64.0 * 1024.0); // min scale 64 KB/s++ const int n = samples_.size();+ const double x_step = r.width() / static_cast<double>(std::max(1, n - 1));++ QPainterPath line;+ QPainterPath fill;+ fill.moveTo(r.left(), r.bottom());++ for (int i = 0; i < n; ++i) {+ const double x = r.left() + i * x_step;+ const double norm = static_cast<double>(samples_[i]) / y_max;+ const double y = r.bottom() - norm * r.height();+ if (i == 0)+ line.moveTo(x, y);+ else+ line.lineTo(x, y);+ fill.lineTo(x, y);+ }+ fill.lineTo(r.right(), r.bottom());+ fill.closeSubpath();++ p.setRenderHint(QPainter::Antialiasing, true);+ p.fillPath(fill, fill_color_);++ QPen pen(line_color_);+ pen.setWidthF(1.3);+ p.setPen(pen);+ p.drawPath(line);+}++} // namespace fincept::uidiff --git a/fincept-qt/src/ui/widgets/SpeedSparkline.h b/fincept-qt/src/ui/widgets/SpeedSparkline.hnew file mode 100644index 000000000..1ff9577ab--- /dev/null+++ b/fincept-qt/src/ui/widgets/SpeedSparkline.h@@ -0,0 +1,36 @@+// src/ui/widgets/SpeedSparkline.h+//+// Minimal rolling sparkline — paints the last N sample values as a filled+// polyline. Used by SetupScreen to visualise the download throughput during+// the long first-run Python install.+#pragma once++#include <QColor>+#include <QVector>+#include <QWidget>++namespace fincept::ui {++class SpeedSparkline : public QWidget {+ Q_OBJECT+ public:+ explicit SpeedSparkline(QWidget* parent = nullptr);++ /// Push a new sample; oldest is dropped when capacity is exceeded.+ void push(qint64 bytes_per_sec);++ void set_line_color(const QColor& c);+ void set_fill_color(const QColor& c);+ void set_capacity(int samples); // default 60 (=1 minute at 1 Hz)++ protected:+ void paintEvent(QPaintEvent* e) override;++ private:+ QVector<qint64> samples_;+ int capacity_ = 60;+ QColor line_color_ = QColor("#d97706");+ QColor fill_color_ = QColor(217, 119, 6, 40);+};++} // namespace fincept::uidiff --git a/setup.sh b/setup.shindex ab76c690b..70daaf3b2 100755--- a/setup.sh+++ b/setup.sh@@ -126,7 +126,7 @@ elseif [ "$PLATFORM" = "linux" ]; thenAQT_HOST="linux" ; AQT_TARGET="desktop" ; AQT_ARCH="gcc_64"else- AQT_HOST="mac" ; AQT_TARGET="desktop" ; AQT_ARCH="clang_64"+ AQT_HOST="mac" ; AQT_TARGET="desktop" ; AQT_ARCH="macos"fi# Modules required to compile Fincept (match find_package COMPONENTS)AQT_MODULES="qtcharts qtwebsockets qtmultimedia qtspeech"