Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

v4.0.3 update

tilakpatel22c4504343ecae
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index f568b3490..6f1791522 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -544,8 +544,8 @@ jobs:
<key>CFBundleIdentifier</key><string>com.fincept.terminal</string>
<key>CFBundleName</key><string>FinceptTerminal</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>4.0.2</string>
- <key>CFBundleVersion</key><string>4.0.2</string>
+ <key>CFBundleShortVersionString</key><string>4.0.3</string>
+ <key>CFBundleVersion</key><string>4.0.3</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 6563da465..89fbfd6d2 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -432,8 +432,8 @@ jobs:
# Filename must match the regex in update-manifest:
# FinceptTerminal-<version>-linux-x64-setup.run
- # where <version> is CMAKE_PROJECT_VERSION (e.g. 4.0.2), NOT the
- # tag (v4.0.2). Parse project() VERSION from CMakeLists.txt so we
+ # where <version> is CMAKE_PROJECT_VERSION (e.g. 4.0.3), NOT the
+ # tag (v4.0.3). Parse project() VERSION from CMakeLists.txt so we
# stay in sync even when triggered via workflow_dispatch (no tag).
VERSION=$(grep -Po 'project\(FinceptTerminal VERSION \K[0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt)
if [ -z "${VERSION}" ]; then
@@ -632,8 +632,8 @@ jobs:
<key>CFBundleIdentifier</key><string>com.fincept.terminal</string>
<key>CFBundleName</key><string>FinceptTerminal</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>4.0.2</string>
- <key>CFBundleVersion</key><string>4.0.2</string>
+ <key>CFBundleShortVersionString</key><string>4.0.3</string>
+ <key>CFBundleVersion</key><string>4.0.3</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
@@ -896,30 +896,65 @@ jobs:
echo "=== Bundle Frameworks/ contents ==="
ls -la "${FRAMEWORKS}" | head -50
- # ── Deep ad-hoc re-sign the entire bundle ─────────────────────────────
+ # ── Import Developer ID certificate into a temp keychain ──────────────
+ # The cert + private key live in repo secrets (base64-encoded .p12).
+ # We provision a throwaway keychain for this job so the runner's
+ # default login keychain stays untouched and the cert is gone the
+ # moment the job ends.
+ - name: Import Developer ID certificate
+ env:
+ P12_BASE64: ${{ secrets.MACOS_CERT_P12_BASE64 }}
+ P12_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }}
+ run: |
+ set -euo pipefail
+ KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain-db"
+ P12_PATH="$RUNNER_TEMP/cert.p12"
+ echo "$P12_BASE64" | base64 -d > "$P12_PATH"
+ security create-keychain -p "$P12_PASSWORD" "$KEYCHAIN_PATH"
+ security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
+ security unlock-keychain -p "$P12_PASSWORD" "$KEYCHAIN_PATH"
+ security import "$P12_PATH" -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
+ security list-keychains -d user -s "$KEYCHAIN_PATH" $(security list-keychains -d user | sed 's/"//g')
+ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$P12_PASSWORD" "$KEYCHAIN_PATH" >/dev/null
+ security find-identity -v -p codesigning "$KEYCHAIN_PATH"
+ rm -f "$P12_PATH"
+
+ # ── Deep re-sign the entire bundle with Developer ID ─────────────────
# This is the fix for issue #139. macdeployqt's signing of nested
# frameworks is unreliable (known Qt bug — see GDATASoftwareAG fork).
# We strip every existing signature and re-sign the whole bundle from
- # leaves to root with a single identity (`-` = ad-hoc). On macOS 14+
- # on Apple Silicon this is what prevents dyld from killing the process
- # with SIGKILL Code Signature Invalid at launch.
- #
- # Until Apple Developer ID cert + notarization is added (Tier 2),
- # users will still see "unidentified developer" on first launch and
- # must right-click → Open (or `xattr -d com.apple.quarantine`).
- - name: Deep ad-hoc codesign bundle
+ # leaves to root with the Developer ID Application cert, hardened
+ # runtime enabled, and entitlements that permit Python's JIT / dynamic
+ # library loading. Notarization later requires hardened runtime.
+ - name: Codesign bundle (Developer ID + hardened runtime)
working-directory: fincept-qt
+ env:
+ SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
run: |
set -euxo pipefail
APP_BUNDLE="build/${{ env.APP_NAME }}.app"
+ ENT="$RUNNER_TEMP/entitlements.plist"
+ cat > "$ENT" <<'EOF'
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0"><dict>
+ <key>com.apple.security.cs.allow-jit</key><true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/>
+ <key>com.apple.security.cs.allow-dyld-environment-variables</key><true/>
+ <key>com.apple.security.cs.disable-library-validation</key><true/>
+ <key>com.apple.security.network.client</key><true/>
+ <key>com.apple.security.network.server</key><true/>
+ </dict></plist>
+ EOF
+
# Strip extended attributes (quarantine / provenance / Finder info)
# from the whole bundle. macdeployqt copies Qt frameworks out of the
# aqtinstall kit, which may carry com.apple.quarantine from the
- # install-qt-action download. Leftover xattrs on individual pages
- # invalidate the signature the moment the DMG is copied to
- # /Applications on macOS 14+ Apple Silicon (root cause of the
- # SIGKILL "Code Signature Invalid" reports in #139, #173, #191).
+ # install-qt-action download. Leftover xattrs invalidate the
+ # signature the moment the DMG is copied to /Applications on
+ # macOS 14+ Apple Silicon (root cause of SIGKILL reports in #139,
+ # #173, #191).
echo "Stripping extended attributes from bundle..."
xattr -cr "${APP_BUNDLE}" 2>/dev/null || true
@@ -928,10 +963,7 @@ jobs:
# leaf-to-root so nested frameworks are unsigned before we re-sign
# their parents. NOTE: site-packages .so files inside Python.framework
# ship as 0644 (not exec), so -perm +111 misses them — explicitly
- # catch *.so via the filename predicate. Same for *.dylib nested in
- # frameworks. The `file ... Mach-O` check still gates actual action
- # so text files accidentally named .so (none today, but belt and
- # suspenders) won't trigger spurious codesign calls.
+ # catch *.so via the filename predicate.
find "${APP_BUNDLE}" -type f \( -name "*.dylib" -o -name "*.so" -o -perm +111 \) 2>/dev/null | \
while read -r f; do
if file "$f" 2>/dev/null | grep -q "Mach-O"; then
@@ -940,14 +972,10 @@ jobs:
done
codesign --remove-signature "${APP_BUNDLE}" 2>/dev/null || true
- echo "Re-signing bundle ad-hoc (deep)..."
- # Ad-hoc sign ("-"): do NOT pass --preserve-metadata — the bundle has
- # no prior entitlements/requirements to preserve, and the flag will
- # fail with "resource fork, Finder information, or similar detritus
- # not allowed" on fresh macdeployqt output. Entitlements are only
- # needed with a real Developer ID cert + hardened runtime (Tier 2).
- codesign --force --deep --sign - \
- --timestamp=none \
+ echo "Signing bundle with Developer ID..."
+ codesign --force --deep --options runtime --timestamp \
+ --entitlements "$ENT" \
+ --sign "$SIGNING_IDENTITY" \
"${APP_BUNDLE}"
echo "Verifying signature..."
@@ -960,6 +988,47 @@ jobs:
echo "Signature OK:"
codesign --display --verbose=2 "${APP_BUNDLE}" 2>&1 | head -20
+ # Strict Gatekeeper pre-flight. Notarization will reject the bundle
+ # if spctl says no — fail here with a clearer error than the notary
+ # response 30 seconds from now.
+ echo "Running spctl assessment..."
+ spctl --assess --type execute --verbose=4 "${APP_BUNDLE}" || {
+ echo "::error::spctl rejected the bundle — notarization will fail"
+ exit 1
+ }
+
+ # ── Notarize + staple the .app BEFORE building the DMG ───────────────
+ # Stapling the .app means Gatekeeper validates offline on first launch
+ # after the user drags it to /Applications. Without this, the .app
+ # carries no ticket — Gatekeeper would have to phone home, and offline
+ # users would see "Apple could not verify ... is free of malware".
+ # The DMG gets its own notarization + staple in a later step.
+ - name: Notarize and staple .app
+ working-directory: fincept-qt
+ env:
+ APPLE_ID: ${{ secrets.MACOS_NOTARY_APPLE_ID }}
+ TEAM_ID: ${{ secrets.MACOS_NOTARY_TEAM_ID }}
+ NOTARY_PASSWORD: ${{ secrets.MACOS_NOTARY_PASSWORD }}
+ run: |
+ set -euo pipefail
+ APP_BUNDLE="build/${{ env.APP_NAME }}.app"
+ ZIP_PATH="$RUNNER_TEMP/app-for-notary.zip"
+
+ # ditto preserves symlinks + xattrs correctly; `zip` doesn't.
+ /usr/bin/ditto -c -k --keepParent "${APP_BUNDLE}" "${ZIP_PATH}"
+
+ echo "Submitting .app to Apple notary (this can take a few minutes)..."
+ xcrun notarytool submit "${ZIP_PATH}" \
+ --apple-id "$APPLE_ID" \
+ --team-id "$TEAM_ID" \
+ --password "$NOTARY_PASSWORD" \
+ --wait
+
+ echo "Stapling ticket to .app..."
+ xcrun stapler staple "${APP_BUNDLE}"
+ xcrun stapler validate "${APP_BUNDLE}"
+ rm -f "${ZIP_PATH}"
+
# ── Copy signed bundle to dist/ ───────────────────────────────────────
- name: Finalize dist
working-directory: fincept-qt
@@ -1001,6 +1070,42 @@ jobs:
ls -lh "build/${DMG_NAME}"
+ # ── Sign + Notarize + Staple DMG ──────────────────────────────────────
+ # Sign the DMG itself, submit to Apple's notary service, and staple
+ # the resulting ticket so Gatekeeper can verify offline. After this
+ # step the DMG opens on any Mac without "unidentified developer"
+ # warnings.
+ - name: Sign and notarize DMG
+ working-directory: fincept-qt
+ env:
+ SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
+ APPLE_ID: ${{ secrets.MACOS_NOTARY_APPLE_ID }}
+ TEAM_ID: ${{ secrets.MACOS_NOTARY_TEAM_ID }}
+ NOTARY_PASSWORD: ${{ secrets.MACOS_NOTARY_PASSWORD }}
+ run: |
+ set -euo pipefail
+ DMG=$(ls build/FinceptTerminal-*-macos-arm64-setup.dmg | head -1)
+ echo "Signing DMG: ${DMG}"
+ codesign --force --sign "$SIGNING_IDENTITY" --timestamp "$DMG"
+
+ echo "Submitting to Apple notary service (this can take a few minutes)..."
+ xcrun notarytool submit "$DMG" \
+ --apple-id "$APPLE_ID" \
+ --team-id "$TEAM_ID" \
+ --password "$NOTARY_PASSWORD" \
+ --wait
+
+ echo "Stapling ticket..."
+ xcrun stapler staple "$DMG"
+ xcrun stapler validate "$DMG"
+ spctl --assess --type open --context context:primary-signature -vv "$DMG" || true
+
+ # ── Clean up the temp keychain ────────────────────────────────────────
+ - name: Clean up keychain
+ if: always()
+ run: |
+ security delete-keychain "$RUNNER_TEMP/build.keychain-db" 2>/dev/null || true
+
# ── Upload ────────────────────────────────────────────────────────────
- name: Upload artifact
uses: actions/upload-artifact@v4
@@ -1242,7 +1347,7 @@ jobs:
run: |
set -euo pipefail
- # Strip leading 'v' so "v4.0.2" → "4.0.2" for latest-version
+ # Strip leading 'v' so "v4.0.3" → "4.0.3" for latest-version
VERSION="${TAG#v}"
WORK="$(mktemp -d)"
diff --git a/README.md b/README.md
index 26be82619..bef42c8b8 100644
--- a/README.md
+++ b/README.md
@@ -65,13 +65,13 @@ State-of-the-art financial intelligence platform with institutional-grade financ
<!-- DOWNLOAD-TABLE-START -->
### Option 1 — Download Installer (Recommended)
-Latest release: **v4.0.2** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2)
+Latest release: **v4.0.3** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3)
| Platform | Download | Run |
|----------|----------|-----|
-| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.2/FinceptTerminal-4.0.2-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
-| **Linux x64** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.2/FinceptTerminal-4.0.2-linux-x64-setup.run) | `chmod +x` → run installer |
-| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.2/FinceptTerminal-4.0.2-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
+| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
+| **Linux x64** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-linux-x64-setup.run) | `chmod +x` → run installer |
+| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
<!-- DOWNLOAD-TABLE-END -->
---
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index e24e8f444..c49850022 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -33,7 +33,7 @@ if(WIN32 AND CMAKE_HOST_WIN32)
unset(_fincept_sdk_dirs)
endif()
-project(FinceptTerminal VERSION 4.0.2 LANGUAGES C CXX)
+project(FinceptTerminal VERSION 4.0.3 LANGUAGES C CXX)
# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.
if(WIN32)
@@ -2320,6 +2320,40 @@ endif()
find_package(OpenSSL REQUIRED)
message(STATUS "OpenSSL found: ${OPENSSL_VERSION} — include: ${OPENSSL_INCLUDE_DIR}")
+# ── macOS: make Qt's openssl TLS plugin discoverable ─────────────────────────
+# Qt's libqopensslbackend.dylib only searches /usr/local/lib, /opt/local/lib,
+# /sw/lib, /usr/lib and Qt's own lib dir for libssl/libcrypto. Homebrew on
+# Apple Silicon installs to /opt/homebrew which Qt does not search, so the
+# openssl plugin fails to register and Qt falls back to the deprecated Apple
+# SecureTransport backend — which double-frees in SSLWrite during QWebSocket
+# close and crashes the crypto tab.
+#
+# Symlink the OpenSSL dylibs from OPENSSL_ROOT_DIR into Qt's lib dir at
+# configure time so the openssl plugin loads and `QT_TLS_BACKEND=openssl`
+# (set in main.cpp) actually takes effect. Runs at configure (idempotent),
+# so it survives clean checkouts and Qt updates.
+if(APPLE AND OPENSSL_ROOT_DIR)
+ cmake_path(GET Qt6_DIR PARENT_PATH _ft_qt_cmake_dir) # .../lib/cmake
+ cmake_path(GET _ft_qt_cmake_dir PARENT_PATH _ft_qt_lib_dir) # .../lib
+ set(_ft_openssl_libs
+ libcrypto.dylib libssl.dylib
+ libcrypto.3.dylib libssl.3.dylib
+ )
+ foreach(_ft_lib IN LISTS _ft_openssl_libs)
+ set(_ft_src "${OPENSSL_ROOT_DIR}/lib/${_ft_lib}")
+ set(_ft_dst "${_ft_qt_lib_dir}/${_ft_lib}")
+ if(EXISTS "${_ft_src}" AND NOT EXISTS "${_ft_dst}")
+ execute_process(
+ COMMAND "${CMAKE_COMMAND}" -E create_symlink "${_ft_src}" "${_ft_dst}"
+ RESULT_VARIABLE _ft_rc
+ )
+ if(_ft_rc EQUAL 0)
+ message(STATUS "Symlinked ${_ft_lib} into Qt lib dir for TLS plugin discovery")
+ endif()
+ endif()
+ endforeach()
+endif()
+
target_include_directories(FinceptTerminal PRIVATE
"${OPENSSL_INCLUDE_DIR}"
"${md4c_SOURCE_DIR}/src"
diff --git a/fincept-qt/packaging/linux/AppImageBuilder.yml b/fincept-qt/packaging/linux/AppImageBuilder.yml
index 5ce0da0f4..8a90ab931 100644
--- a/fincept-qt/packaging/linux/AppImageBuilder.yml
+++ b/fincept-qt/packaging/linux/AppImageBuilder.yml
@@ -16,7 +16,7 @@ AppDir:
id: com.fincept.terminal
name: Fincept Terminal
icon: fincept-terminal
- version: !ENV ${FINCEPT_VERSION:-4.0.2}
+ version: !ENV ${FINCEPT_VERSION:-4.0.3}
exec: usr/bin/FinceptTerminal
exec_args: $@
@@ -56,6 +56,6 @@ AppDir:
AppImage:
arch: x86_64
comp: xz
- file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.0.2}-x86_64.AppImage
+ file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.0.3}-x86_64.AppImage
sign-key: None
update-information: gh-releases-zsync|Fincept-Corporation|FinceptTerminal|latest|FinceptTerminal-*x86_64.AppImage.zsync
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index 392caaf69..3449d9e16 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -314,20 +314,10 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
dock_toolbar_ = new ui::DockToolBar(this);
addToolBar(Qt::TopToolBarArea, dock_toolbar_);
- // Pushpin bar lives on its own toolbar row below the main toolbar so the
- // chips are always visible and drop targets across all panels. Start a
- // new toolbar line via addToolBarBreak().
- addToolBarBreak(Qt::TopToolBarArea);
- pushpin_bar_ = new ui::PushpinBar;
- pushpin_toolbar_ = new QToolBar(this);
- pushpin_toolbar_->setObjectName("pushpinToolbar");
- pushpin_toolbar_->setMovable(false);
- pushpin_toolbar_->setFloatable(false);
- pushpin_toolbar_->setAllowedAreas(Qt::TopToolBarArea);
- pushpin_toolbar_->addWidget(pushpin_bar_);
- addToolBar(Qt::TopToolBarArea, pushpin_toolbar_);
- // Hidden until auth completes; set_shell_visible() shows it.
- pushpin_toolbar_->setVisible(false);
+ // Pushpin chips are embedded directly inside the main toolbar (see
+ // ToolBar::ToolBar). Visibility/enabled state now follows the parent
+ // toolbar — no explicit gating needed.
+ pushpin_bar_ = dock_toolbar_->inner()->pushpin_bar();
dock_status_bar_ = new ui::DockStatusBar(this);
setStatusBar(dock_status_bar_);
@@ -872,8 +862,6 @@ void WindowFrame::toggle_chat_mode() {
dock_toolbar_->setVisible(false);
if (dock_status_bar_)
dock_status_bar_->setVisible(false);
- if (pushpin_toolbar_)
- pushpin_toolbar_->setVisible(false);
if (chat_bubble_)
chat_bubble_->setVisible(false);
stack_->setCurrentIndex(2);
@@ -884,8 +872,6 @@ void WindowFrame::toggle_chat_mode() {
dock_toolbar_->setVisible(true);
if (dock_status_bar_)
dock_status_bar_->setVisible(true);
- if (pushpin_toolbar_)
- pushpin_toolbar_->setVisible(true);
// Restore chat bubble based on setting
if (chat_bubble_) {
auto r = SettingsRepository::instance().get("appearance.show_chat_bubble");
@@ -1327,7 +1313,6 @@ void WindowFrame::apply_lock_state(bool locked) {
if (dock_manager_ && dock_manager_->parentWidget())
dock_manager_->parentWidget()->setEnabled(false);
if (dock_toolbar_) dock_toolbar_->setEnabled(false);
- if (pushpin_toolbar_) pushpin_toolbar_->setEnabled(false);
if (dock_status_bar_) dock_status_bar_->setEnabled(false);
return;
}
@@ -1345,7 +1330,6 @@ void WindowFrame::apply_lock_state(bool locked) {
if (dock_manager_ && dock_manager_->parentWidget())
dock_manager_->parentWidget()->setEnabled(true);
if (dock_toolbar_) dock_toolbar_->setEnabled(true);
- if (pushpin_toolbar_) pushpin_toolbar_->setEnabled(true);
if (dock_status_bar_) dock_status_bar_->setEnabled(true);
set_shell_visible(true);
stack_->setCurrentIndex(1);
@@ -1364,7 +1348,6 @@ void WindowFrame::on_terminal_unlocked() {
if (dock_manager_ && dock_manager_->parentWidget())
dock_manager_->parentWidget()->setEnabled(true);
if (dock_toolbar_) dock_toolbar_->setEnabled(true);
- if (pushpin_toolbar_) pushpin_toolbar_->setEnabled(true);
if (dock_status_bar_) dock_status_bar_->setEnabled(true);
// Enable/restart inactivity guard. It is disabled in show_lock_screen()
@@ -1433,8 +1416,6 @@ void WindowFrame::set_shell_visible(bool visible) {
dock_toolbar_->setVisible(visible && !focus_mode_ && !chat_mode_);
if (dock_status_bar_)
dock_status_bar_->setVisible(visible && !focus_mode_ && !chat_mode_);
- if (pushpin_toolbar_)
- pushpin_toolbar_->setVisible(visible && !focus_mode_ && !chat_mode_);
if (!visible) {
// Reset title to plain app name — no screen suffix while on auth screens
const QString profile = ProfileManager::instance().active();
@@ -1767,8 +1748,6 @@ void WindowFrame::toggle_focus_mode() {
dock_toolbar_->setVisible(!focus_mode_);
if (dock_status_bar_)
dock_status_bar_->setVisible(!focus_mode_);
- if (pushpin_toolbar_)
- pushpin_toolbar_->setVisible(!focus_mode_);
}
void WindowFrame::toggle_chat_mode_action() {
diff --git a/fincept-qt/src/app/WindowFrame.h b/fincept-qt/src/app/WindowFrame.h
index bdab33512..15bb7f814 100644
--- a/fincept-qt/src/app/WindowFrame.h
+++ b/fincept-qt/src/app/WindowFrame.h
@@ -238,8 +238,7 @@ class WindowFrame : public QMainWindow {
DockScreenRouter* dock_router_ = nullptr;
ui::DockToolBar* dock_toolbar_ = nullptr;
ui::DockStatusBar* dock_status_bar_ = nullptr;
- ui::PushpinBar* pushpin_bar_ = nullptr;
- QToolBar* pushpin_toolbar_ = nullptr; // outer QToolBar that hosts pushpin_bar_
+ ui::PushpinBar* pushpin_bar_ = nullptr; // owned by ui::ToolBar (inline in main toolbar)
ui::TabBar* tab_bar_ = nullptr;
// View state
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index f04158b04..339787462 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -46,6 +46,7 @@
#include "services/prediction/fincept_internal/FinceptInternalAdapter.h"
#include "services/prediction/kalshi/KalshiAdapter.h"
#include "services/prediction/polymarket/PolymarketAdapter.h"
+#include "services/forum/ForumService.h"
#include "services/relationship_map/RelationshipMapService.h"
#include "services/report_builder/ReportBuilderService.h"
#include "datahub/DataHub.h"
@@ -72,10 +73,11 @@
#include <QCoreApplication>
#include <QDir>
#include <QFile>
-#include <QLockFile>
+#include <QLibrary>
#include <QPointer>
#include <QSqlDatabase>
#include <QSqlQuery>
+#include <QSslSocket>
#include <QStandardPaths>
#include <QTimer>
#include <QUuid>
@@ -132,6 +134,45 @@ static void wire_app_lifecycle(QApplication& app, fincept::InstanceLock& lock) {
int main(int argc, char* argv[]) {
FT_MARK(1);
+
+ // ── TLS backend selection (must happen before any Qt plugin loading) ────
+ // Force QtNetwork to use the OpenSSL TLS backend across platforms.
+ // - macOS: Apple SecureTransport (qtls_st.cpp) double-frees inside
+ // SSLWrite when QWebSocket sends a close frame after a protocol
+ // error. Reproducible by opening the crypto tab — Kraken/Polymarket
+ // WS reconnect path crashes the main thread. SecureTransport was
+ // deprecated by Apple in 10.15.
+ // - Windows: Schannel has had similar instability around WS close
+ // and certificate revocation paths in Qt 6.8. OpenSSL is the
+ // consistent backend on every platform Qt supports.
+ // QT_TLS_BACKEND is read by QTlsBackendFactory at plugin-loader time, so
+ // it has to be set BEFORE QCoreApplication/QApplication is constructed —
+ // setActiveBackend() after the fact does not always take effect because
+ // singleton factories may already be bound.
+ qputenv("QT_TLS_BACKEND", "openssl");
+
+#ifdef Q_OS_MACOS
+ // Pre-load OpenSSL from Homebrew so the openssl plugin's runtime dlopen
+ // succeeds. Qt's QLibrary search defaults don't include /opt/homebrew/...
+ // Order matters: libcrypto first (libssl depends on it).
+ {
+ const QStringList crypto_candidates = {
+ QStringLiteral("/opt/homebrew/opt/openssl@3/lib/libcrypto.3.dylib"),
+ QStringLiteral("/usr/local/opt/openssl@3/lib/libcrypto.3.dylib"),
+ };
+ const QStringList ssl_candidates = {
+ QStringLiteral("/opt/homebrew/opt/openssl@3/lib/libssl.3.dylib"),
+ QStringLiteral("/usr/local/opt/openssl@3/lib/libssl.3.dylib"),
+ };
+ for (const auto& p : crypto_candidates) {
+ if (QFile::exists(p)) { QLibrary(p).load(); break; }
+ }
+ for (const auto& p : ssl_candidates) {
+ if (QFile::exists(p)) { QLibrary(p).load(); break; }
+ }
+ }
+#endif
+
// ── Parse --profile <name> from argv before Qt initialises ───────────────
// This must happen first so that:
// 1. AppPaths returns the correct per-profile directories
@@ -189,6 +230,17 @@ int main(int argc, char* argv[]) {
// explicit one in LaunchpadScreen::closeEvent.
app.setQuitOnLastWindowClosed(false);
+ // Belt-and-braces: if QT_TLS_BACKEND wasn't honoured for some reason
+ // (e.g. plugin load order on a particular platform), retry the switch
+ // explicitly. This is a no-op if openssl is already active.
+ {
+ const auto backends = QSslSocket::availableBackends();
+ if (QSslSocket::activeBackend() != QStringLiteral("openssl")
+ && backends.contains(QStringLiteral("openssl"))) {
+ QSslSocket::setActiveBackend(QStringLiteral("openssl"));
+ }
+ }
+
// ── Single-instance lock + new-window IPC ────────────────────────────────
const QString profile_key = QString("FinceptTerminal-%1").arg(fincept::ProfileManager::instance().active());
fincept::InstanceLock instance_lock;
@@ -245,194 +297,166 @@ int main(int argc, char* argv[]) {
FT_MARK(20);
fincept::services::MarketDataService::instance().ensure_registered_with_hub();
FT_MARK(21);
- // F&O / Options chain (Phase 11 — Sensibull-style tab). Sole hub
- // producer for option:chain:*, option:tick:*, option:atm_iv:*, fno:pcr:*,
- // fno:max_pain:*. Reads instruments via InstrumentService (broker-loaded),
- // batches get_quotes via the active IBroker, and publishes assembled
- // chains. After each chain publish the service kicks off a Greeks/IV
- // batch via OptionGreeksWorker (Phase 3) and republishes the enriched
- // chain.
- fincept::services::options::OptionChainService::instance().ensure_registered_with_hub();
- // F&O OI snapshotter (Phase 3 of the F&O work) — subscribes to
- // option:chain:* and persists minute-aligned OI/LTP/Vol/IV rows to
- // SQLite. Producer for oi:history:* (window queries).
- fincept::services::options::OISnapshotter::instance().ensure_registered_with_hub();
- // F&O FII/DII flows (Phase 8) — daily NSE cash-market institutional
- // buy/sell, scraped via fii_dii_scraper.py. Producer for
- // fno:fii_dii:daily.
- fincept::services::options::FiiDiiService::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
- // prediction::* data model for the screen.
- fincept::services::polymarket::PolymarketWebSocket::instance().ensure_registered_with_hub();
- // Alpha Arena engine — singleton runtime owning TickClock, ModelDispatcher,
- // OrderRouter, PaperVenue. Not a DataHub Producer (callback-style by
- // design — see .grill-me/alpha-arena-grill.md §1). init() is idempotent;
- // calling it pre-resolves crash-recovery state from aa_competitions.
- fincept::services::alpha_arena::AlphaArenaEngine::instance().init();
- {
- auto& reg = fincept::services::prediction::PredictionExchangeRegistry::instance();
- reg.register_adapter(
- std::make_unique<fincept::services::prediction::polymarket_ns::PolymarketAdapter>());
- reg.register_adapter(
- std::make_unique<fincept::services::prediction::kalshi_ns::KalshiAdapter>());
- // Phase 4 §4.3: Fincept internal prediction-market adapter joins the
- // registry as a sibling of Polymarket / Kalshi. Ships in demo mode
- // (curated mock dataset) until `fincept.markets_endpoint` is
- // configured and the `fincept_market` Anchor program is deployed.
- reg.register_adapter(
- std::make_unique<fincept::services::prediction::fincept_internal::FinceptInternalAdapter>());
-
- // Hydrate credentials from SecureStorage if previously saved. This
- // has to happen after registration so the adapters exist.
- if (auto* pm = dynamic_cast<fincept::services::prediction::polymarket_ns::PolymarketAdapter*>(
- reg.adapter(QStringLiteral("polymarket")))) {
- pm->reload_credentials();
- }
- if (auto* ks = dynamic_cast<fincept::services::prediction::kalshi_ns::KalshiAdapter*>(
- reg.adapter(QStringLiteral("kalshi")))) {
- if (auto creds = fincept::services::prediction::PredictionCredentialStore::load_kalshi()) {
- ks->set_credentials(*creds);
- }
- }
- if (auto* fi = reg.adapter(QStringLiteral("fincept"))) {
- fi->ensure_registered_with_hub();
- }
- }
- // Phase 5: NewsService as the news:general / news:symbol:* /
- // news:category:* / news:cluster:* producer.
+
+ // ── Sync services needed by the default dashboard ─────────────────────────
+ // Anything a default dashboard widget subscribes to during its first show
+ // must be registered with the hub before the window paints. Everything
+ // else is deferred to a single QTimer::singleShot(0) below — the event
+ // loop runs that batch immediately after the first paint, so cold-start
+ // perceived latency drops without changing functional behavior.
fincept::services::NewsService::instance().ensure_registered_with_hub();
- // Phase 6: Economics + DBnomics + GovData producers.
fincept::services::EconomicsService::instance().ensure_registered_with_hub();
- fincept::services::DBnomicsService::instance().ensure_registered_with_hub();
- fincept::services::GovDataService::instance().ensure_registered_with_hub();
- // Macro calendar: HTTP-backed `econ:fincept:upcoming_events` producer
- // serving the dashboard EconomicCalendarWidget.
fincept::services::MacroCalendarService::instance().ensure_registered_with_hub();
- // Phase 7: DataStreamManager as the broker:* producer (positions,
- // orders, balance, holdings, quote, ticks). Per-account topic shape
- // `broker:<id>:<account_id>:<channel>`.
fincept::trading::DataStreamManager::instance().ensure_registered_with_hub();
- // Phase 8: Geopolitics / Maritime / RelationshipMap / MAAnalytics.
fincept::services::geo::GeopoliticsService::instance().ensure_registered_with_hub();
fincept::services::maritime::MaritimeService::instance().ensure_registered_with_hub();
fincept::services::maritime::PortsCatalog::instance().ensure_registered_with_hub();
fincept::services::RelationshipMapService::instance().ensure_registered_with_hub();
fincept::services::ma::MAAnalyticsService::instance().ensure_registered_with_hub();
- // Phase 9: AgentService as agent:* push-only producer (output/stream/status/routing/error).
- fincept::services::AgentService::instance().ensure_registered_with_hub();
- // Crypto: WalletService owns wallet:balance:* and market:price:token:*.
- // TokenMetadataService loads its symbol/name cache from SecureStorage
- // first so the very first balance publish has labels for known tokens;
- // a daily background refresh fires in the background after.
FT_MARK(30);
fincept::wallet::TokenMetadataService::instance().load_from_storage();
- FT_MARK(31);
- fincept::wallet::TokenMetadataService::instance().refresh_from_jupiter_async();
- FT_MARK(32);
- // Restore_from_storage runs after the hub is up so a soft-connected
- // wallet's balance topic resolves to a registered producer immediately.
- FT_MARK(33);
- fincept::wallet::WalletService::instance().ensure_registered_with_hub();
- FT_MARK(34);
- fincept::wallet::WalletService::instance().restore_from_storage();
FT_MARK(35);
- // Phase 2 §2C: fee-discount eligibility producer. Lives in billing/
- // because it's consumed by other paid screens later; for Phase 2 it
- // only feeds HoldingsBar's chip and TradeTab's FeeDiscountPanel.
- {
- static fincept::billing::FeeDiscountService discount_service;
- auto& hub = fincept::datahub::DataHub::instance();
- hub.register_producer(&discount_service);
- fincept::datahub::TopicPolicy p;
- // Eligibility is derived from wallet:balance — refresh cadence here
- // is just a fallback; the service also republishes whenever the
- // balance topic emits.
- p.ttl_ms = 60 * 1000;
- p.min_interval_ms = 15 * 1000;
- hub.set_policy_pattern(QStringLiteral("billing:fncpt_discount:*"), p);
- }
+ // ── Deferred service init — fires after first window paint ───────────────
+ // These services back tab-specific screens (F&O, prediction markets,
+ // alpha arena, agents, wallet/treasury/staking, etc.) — none of them is
+ // needed for the dashboard's first paint, so registering them here would
+ // only add latency to the user-visible cold start. Late registration is
+ // safe: the hub's scheduler tick picks up matching subscriptions on the
+ // next pass once the producer is registered.
+ QTimer::singleShot(0, qApp, []() {
+ // F&O / Options chain — `option:chain:*`, `option:tick:*`,
+ // `option:atm_iv:*`, `fno:pcr:*`, `fno:max_pain:*`.
+ fincept::services::options::OptionChainService::instance().ensure_registered_with_hub();
+ // F&O OI snapshotter — subscribes to option:chain:* and persists
+ // minute-aligned OI/LTP/Vol/IV rows to SQLite. Producer for
+ // oi:history:* (window queries).
+ fincept::services::options::OISnapshotter::instance().ensure_registered_with_hub();
+ // F&O FII/DII flows — daily NSE cash-market institutional buy/sell.
+ fincept::services::options::FiiDiiService::instance().ensure_registered_with_hub();
+ // Multi-broker session manager — `ws:kraken:*` / `ws:hyperliquid:*`.
+ fincept::trading::ExchangeSessionManager::instance().ensure_registered_with_hub();
+ // Prediction Markets — `prediction:polymarket:*`.
+ fincept::services::polymarket::PolymarketWebSocket::instance().ensure_registered_with_hub();
+ // Alpha Arena engine — TickClock, ModelDispatcher, OrderRouter,
+ // PaperVenue. Not a DataHub Producer (callback-style by design).
+ // init() is idempotent; pre-resolves crash-recovery state.
+ fincept::services::alpha_arena::AlphaArenaEngine::instance().init();
+ {
+ auto& reg = fincept::services::prediction::PredictionExchangeRegistry::instance();
+ reg.register_adapter(
+ std::make_unique<fincept::services::prediction::polymarket_ns::PolymarketAdapter>());
+ reg.register_adapter(
+ std::make_unique<fincept::services::prediction::kalshi_ns::KalshiAdapter>());
+ // Fincept internal prediction-market adapter (demo mode until
+ // `fincept.markets_endpoint` is configured).
+ reg.register_adapter(
+ std::make_unique<fincept::services::prediction::fincept_internal::FinceptInternalAdapter>());
+
+ // Hydrate credentials from SecureStorage if previously saved.
+ if (auto* pm = dynamic_cast<fincept::services::prediction::polymarket_ns::PolymarketAdapter*>(
+ reg.adapter(QStringLiteral("polymarket")))) {
+ pm->reload_credentials();
+ }
+ if (auto* ks = dynamic_cast<fincept::services::prediction::kalshi_ns::KalshiAdapter*>(
+ reg.adapter(QStringLiteral("kalshi")))) {
+ if (auto creds = fincept::services::prediction::PredictionCredentialStore::load_kalshi()) {
+ ks->set_credentials(*creds);
+ }
+ }
+ if (auto* fi = reg.adapter(QStringLiteral("fincept"))) {
+ fi->ensure_registered_with_hub();
+ }
+ }
+ // Specialized data sources.
+ fincept::services::DBnomicsService::instance().ensure_registered_with_hub();
+ fincept::services::GovDataService::instance().ensure_registered_with_hub();
+ // Agents — `agent:*` push-only producer.
+ fincept::services::AgentService::instance().ensure_registered_with_hub();
+ // Token metadata refresh — network call to Jupiter aggregator.
+ fincept::wallet::TokenMetadataService::instance().refresh_from_jupiter_async();
+ // Wallet — `wallet:balance:*`, `market:price:token:*`.
+ fincept::wallet::WalletService::instance().ensure_registered_with_hub();
+ fincept::wallet::WalletService::instance().restore_from_storage();
+
+ // Fee-discount eligibility producer (paid screens only).
+ {
+ static fincept::billing::FeeDiscountService discount_service;
+ auto& hub = fincept::datahub::DataHub::instance();
+ hub.register_producer(&discount_service);
+ fincept::datahub::TopicPolicy p;
+ p.ttl_ms = 60 * 1000;
+ p.min_interval_ms = 15 * 1000;
+ hub.set_policy_pattern(QStringLiteral("billing:fncpt_discount:*"), p);
+ }
- // Phase 5: buyback & burn dashboard producers (terminal-wide treasury:*
- // topics). Both producers ship in mock mode until the buyback worker
- // endpoint is configured via SecureStorage `fincept.treasury_endpoint`
- // and `fincept.treasury_pubkey`.
- {
- static fincept::wallet::BuybackBurnService buyback_burn_service;
- static fincept::wallet::TreasuryService treasury_service;
- auto& hub = fincept::datahub::DataHub::instance();
- hub.register_producer(&buyback_burn_service);
- hub.register_producer(&treasury_service);
-
- // Per-topic policies. Cadences mirror Phase 5 plan §5.3.
- fincept::datahub::TopicPolicy epoch_p;
- epoch_p.ttl_ms = 60 * 1000;
- epoch_p.min_interval_ms = 30 * 1000;
- hub.set_policy_pattern(QStringLiteral("treasury:buyback_epoch"), epoch_p);
-
- fincept::datahub::TopicPolicy burn_p;
- burn_p.ttl_ms = 5 * 60 * 1000;
- burn_p.min_interval_ms = 60 * 1000;
- hub.set_policy_pattern(QStringLiteral("treasury:burn_total"), burn_p);
-
- fincept::datahub::TopicPolicy supply_p;
- supply_p.ttl_ms = 60 * 60 * 1000;
- supply_p.min_interval_ms = 5 * 60 * 1000;
- hub.set_policy_pattern(QStringLiteral("treasury:supply_history"), supply_p);
-
- fincept::datahub::TopicPolicy reserves_p;
- reserves_p.ttl_ms = 5 * 60 * 1000;
- reserves_p.min_interval_ms = 60 * 1000;
- hub.set_policy_pattern(QStringLiteral("treasury:reserves"), reserves_p);
-
- fincept::datahub::TopicPolicy runway_p;
- runway_p.ttl_ms = 5 * 60 * 1000;
- runway_p.min_interval_ms = 60 * 1000;
- hub.set_policy_pattern(QStringLiteral("treasury:runway"), runway_p);
- }
+ // Buyback & burn / treasury producers (treasury:*).
+ {
+ static fincept::wallet::BuybackBurnService buyback_burn_service;
+ static fincept::wallet::TreasuryService treasury_service;
+ auto& hub = fincept::datahub::DataHub::instance();
+ hub.register_producer(&buyback_burn_service);
+ hub.register_producer(&treasury_service);
+
+ fincept::datahub::TopicPolicy epoch_p;
+ epoch_p.ttl_ms = 60 * 1000;
+ epoch_p.min_interval_ms = 30 * 1000;
+ hub.set_policy_pattern(QStringLiteral("treasury:buyback_epoch"), epoch_p);
+
+ fincept::datahub::TopicPolicy burn_p;
+ burn_p.ttl_ms = 5 * 60 * 1000;
+ burn_p.min_interval_ms = 60 * 1000;
+ hub.set_policy_pattern(QStringLiteral("treasury:burn_total"), burn_p);
+
+ fincept::datahub::TopicPolicy supply_p;
+ supply_p.ttl_ms = 60 * 60 * 1000;
+ supply_p.min_interval_ms = 5 * 60 * 1000;
+ hub.set_policy_pattern(QStringLiteral("treasury:supply_history"), supply_p);
+
+ fincept::datahub::TopicPolicy reserves_p;
+ reserves_p.ttl_ms = 5 * 60 * 1000;
+ reserves_p.min_interval_ms = 60 * 1000;
+ hub.set_policy_pattern(QStringLiteral("treasury:reserves"), reserves_p);
+
+ fincept::datahub::TopicPolicy runway_p;
+ runway_p.ttl_ms = 5 * 60 * 1000;
+ runway_p.min_interval_ms = 60 * 1000;
+ hub.set_policy_pattern(QStringLiteral("treasury:runway"), runway_p);
+ }
- // Phase 3: STAKE tab producers (veFNCPT lock + real-yield + tier system).
- // All three ship in mock mode until SecureStorage `fincept.lock_program_id`
- // and `fincept.yield_endpoint` are configured. The mock payloads carry
- // `is_mock=true` so panels can surface a "not yet deployed" chip.
- {
- auto& hub = fincept::datahub::DataHub::instance();
- hub.register_producer(&fincept::wallet::StakingService::instance());
- hub.register_producer(&fincept::wallet::RealYieldService::instance());
- hub.register_producer(&fincept::billing::TierService::instance());
-
- // Plan §3.4 cadences.
- fincept::datahub::TopicPolicy locks_p;
- locks_p.ttl_ms = 60 * 1000;
- locks_p.min_interval_ms = 30 * 1000;
- hub.set_policy_pattern(QStringLiteral("wallet:locks:*"), locks_p);
- hub.set_policy_pattern(QStringLiteral("wallet:vefncpt:*"), locks_p);
-
- fincept::datahub::TopicPolicy yield_p;
- yield_p.ttl_ms = 5 * 60 * 1000;
- yield_p.min_interval_ms = 60 * 1000;
- hub.set_policy_pattern(QStringLiteral("wallet:yield:*"), yield_p);
-
- fincept::datahub::TopicPolicy revenue_p;
- revenue_p.ttl_ms = 60 * 60 * 1000;
- revenue_p.min_interval_ms = 5 * 60 * 1000;
- hub.set_policy_pattern(QStringLiteral("treasury:revenue"), revenue_p);
-
- // billing:tier:* is derived from wallet:vefncpt:* — TTL is just a
- // safety net; the service republishes whenever vefncpt emits.
- fincept::datahub::TopicPolicy tier_p;
- tier_p.ttl_ms = 60 * 1000;
- tier_p.min_interval_ms = 15 * 1000;
- hub.set_policy_pattern(QStringLiteral("billing:tier:*"), tier_p);
- }
+ // STAKE tab producers (veFNCPT lock + real-yield + tier system).
+ {
+ auto& hub = fincept::datahub::DataHub::instance();
+ hub.register_producer(&fincept::wallet::StakingService::instance());
+ hub.register_producer(&fincept::wallet::RealYieldService::instance());
+ hub.register_producer(&fincept::billing::TierService::instance());
+
+ fincept::datahub::TopicPolicy locks_p;
+ locks_p.ttl_ms = 60 * 1000;
+ locks_p.min_interval_ms = 30 * 1000;
+ hub.set_policy_pattern(QStringLiteral("wallet:locks:*"), locks_p);
+ hub.set_policy_pattern(QStringLiteral("wallet:vefncpt:*"), locks_p);
+
+ fincept::datahub::TopicPolicy yield_p;
+ yield_p.ttl_ms = 5 * 60 * 1000;
+ yield_p.min_interval_ms = 60 * 1000;
+ hub.set_policy_pattern(QStringLiteral("wallet:yield:*"), yield_p);
+
+ fincept::datahub::TopicPolicy revenue_p;
+ revenue_p.ttl_ms = 60 * 60 * 1000;
+ revenue_p.min_interval_ms = 5 * 60 * 1000;
+ hub.set_policy_pattern(QStringLiteral("treasury:revenue"), revenue_p);
+
+ // billing:tier:* derived from wallet:vefncpt:* — TTL is just a
+ // safety net; the service republishes whenever vefncpt emits.
+ fincept::datahub::TopicPolicy tier_p;
+ tier_p.ttl_ms = 60 * 1000;
+ tier_p.min_interval_ms = 15 * 1000;
+ hub.set_policy_pattern(QStringLiteral("billing:tier:*"), tier_p);
+ }
+
+ LOG_INFO("App", "Deferred service init complete");
+ });
FT_MARK(40);
// Create all application directories under %LOCALAPPDATA%/com.fincept.terminal
@@ -459,21 +483,17 @@ int main(int argc, char* argv[]) {
QFile::remove(old_base + "/cache.db-shm");
}
- // ── WAL/SHM cleanup — gated behind QLockFile ────────────────────────────
- // Deleting WAL/SHM files while another process has the DB open corrupts it.
- // We only clean up orphaned files from a previous crash when we are the sole
- // running instance. The lock file is held for the entire process lifetime.
- QLockFile db_lock(fincept::AppPaths::data() + "/fincept.db.lock");
- db_lock.setStaleLockTime(0); // never auto-expire; we control the lifecycle
- const bool sole_instance = db_lock.tryLock(0);
- if (sole_instance) {
- QFile::remove(fincept::AppPaths::data() + "/fincept.db-wal");
- QFile::remove(fincept::AppPaths::data() + "/fincept.db-shm");
- QFile::remove(fincept::AppPaths::data() + "/cache.db-wal");
- QFile::remove(fincept::AppPaths::data() + "/cache.db-shm");
- }
- // db_lock remains held (stack-allocated) until main() returns.
- // Also clean legacy v3 DB location
+ // SQLite owns its own .db-wal / .db-shm files. Pre-deleting them is
+ // destructive: any committed transaction that has not yet been checkpointed
+ // back into the main .db file lives entirely in the WAL. Auto-checkpoint
+ // only fires past ~1000 pages, and the on-close checkpoint can fail
+ // silently — small writes (e.g. pin_hash on the secure_credentials table)
+ // routinely persist only in the WAL across runs. SQLite reads the WAL on
+ // open to recover any uncheckpointed or crash-truncated state, so we leave
+ // these files for SQLite to manage. Single-instance enforcement is owned
+ // by InstanceLock above.
+
+ // Clean legacy v3 DB location (these paths are no longer live DBs)
{
const QString local_dir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
const QString legacy1 = local_dir.section('/', 0, -3) + "/FinceptTerminal/fincept_settings.db";
@@ -530,7 +550,10 @@ 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.3 starting...");
+ LOG_INFO("App", QString("TLS backend: %1 (available: %2)")
+ .arg(QSslSocket::activeBackend(),
+ QSslSocket::availableBackends().join(", ")));
// Theme is applied after DB is open so saved font/theme are respected from the start.
@@ -683,6 +706,15 @@ int main(int argc, char* argv[]) {
// already exist with main-thread affinity.
(void)fincept::services::ReportBuilderService::instance();
+ // Same reason for ForumService: ForumTools (MCP) and ForumScreen (GUI)
+ // share one singleton that owns a QNetworkAccessManager. Whichever caller
+ // hits instance() first dictates thread affinity. If a worker thread
+ // touches it before the GUI does, every subsequent fetch from the Forum
+ // tab queues its reply onto a thread with no live event loop and the
+ // callback never fires — the tab spins on "loading" forever. Forcing
+ // construction here pins it to the main thread up front.
+ (void)fincept::services::ForumService::instance();
+
// Initialize MCP tool system — registers all internal tools and starts
// external MCP servers in the background (non-blocking).
fincept::mcp::initialize_all_tools();
diff --git a/fincept-qt/src/auth/UserApi.cpp b/fincept-qt/src/auth/UserApi.cpp
index 40858d951..ec072b608 100644
--- a/fincept-qt/src/auth/UserApi.cpp
+++ b/fincept-qt/src/auth/UserApi.cpp
@@ -62,8 +62,12 @@ void UserApi::request(const QString& method, const QString& endpoint, const QJso
http.post(endpoint, body, handle);
else if (method == "PUT")
http.put(endpoint, body, handle);
- else if (method == "DELETE")
- http.del(endpoint, handle);
+ else if (method == "DELETE") {
+ if (body.isEmpty())
+ http.del(endpoint, handle);
+ else
+ http.del(endpoint, body, handle);
+ }
}
// ── Profile ──────────────────────────────────────────────────────────────────
@@ -80,8 +84,12 @@ void UserApi::regenerate_api_key(Callback cb) {
void UserApi::get_user_credits(Callback cb) {
request("GET", "/user/credits", {}, cb);
}
-void UserApi::delete_user_account(Callback cb) {
- request("DELETE", "/user/account", {}, cb);
+void UserApi::delete_user_account(const QString& confirm_email, const QString& password, Callback cb) {
+ QJsonObject body;
+ body.insert("confirm", true);
+ body.insert("email", confirm_email);
+ body.insert("password", password);
+ request("DELETE", "/user/account", body, cb);
}
void UserApi::get_user_usage(int days, Callback cb) {
diff --git a/fincept-qt/src/auth/UserApi.h b/fincept-qt/src/auth/UserApi.h
index 097b84e06..e8e6f16a0 100644
--- a/fincept-qt/src/auth/UserApi.h
+++ b/fincept-qt/src/auth/UserApi.h
@@ -22,7 +22,7 @@ class UserApi : public QObject {
void regenerate_api_key(Callback cb);
void get_user_usage(int days, Callback cb);
void get_user_credits(Callback cb);
- void delete_user_account(Callback cb);
+ void delete_user_account(const QString& confirm_email, const QString& password, Callback cb);
// Session
void logout(Callback cb);
diff --git a/fincept-qt/src/mcp/McpClient.cpp b/fincept-qt/src/mcp/McpClient.cpp
index 8cbaf762c..3d7faf631 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.3";
params["clientInfo"] = client_info;
QJsonObject capabilities;
diff --git a/fincept-qt/src/network/http/HttpClient.cpp b/fincept-qt/src/network/http/HttpClient.cpp
index b9759cd01..c7026fdfc 100644
--- a/fincept-qt/src/network/http/HttpClient.cpp
+++ b/fincept-qt/src/network/http/HttpClient.cpp
@@ -109,6 +109,13 @@ void HttpClient::del(const QString& url, JsonCallback callback, const QObject* c
handle_reply(reply, std::move(callback), context);
}
+void HttpClient::del(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context) {
+ LOG_DEBUG("HTTP", "DELETE " + url);
+ QJsonDocument doc(body);
+ auto* reply = nam_->sendCustomRequest(build_request(url), "DELETE", doc.toJson(QJsonDocument::Compact));
+ handle_reply(reply, std::move(callback), context);
+}
+
void HttpClient::set_auth_header(const QString& api_key) {
api_key_ = api_key;
}
diff --git a/fincept-qt/src/network/http/HttpClient.h b/fincept-qt/src/network/http/HttpClient.h
index 84a16c7f2..ddea92661 100644
--- a/fincept-qt/src/network/http/HttpClient.h
+++ b/fincept-qt/src/network/http/HttpClient.h
@@ -26,6 +26,7 @@ class HttpClient : public QObject {
void post(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr);
void put(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr);
void del(const QString& url, JsonCallback callback, const QObject* context = nullptr);
+ void del(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr);
void set_auth_header(const QString& api_key);
void set_session_token(const QString& token);
diff --git a/fincept-qt/src/network/websocket/WebSocketClient.cpp b/fincept-qt/src/network/websocket/WebSocketClient.cpp
index 15659e1bb..a82d76d05 100644
--- a/fincept-qt/src/network/websocket/WebSocketClient.cpp
+++ b/fincept-qt/src/network/websocket/WebSocketClient.cpp
@@ -2,56 +2,139 @@
#include "core/logging/Logger.h"
+#include <QMetaObject>
+#include <QPointer>
+#include <QThread>
+#include <QTimer>
+
namespace fincept {
+namespace {
+constexpr const char* kTag = "WS";
+
+QString thread_label() {
+ auto* t = QThread::currentThread();
+ if (!t)
+ return QStringLiteral("?");
+ const QString name = t->objectName();
+ return name.isEmpty() ? QStringLiteral("0x%1").arg(reinterpret_cast<quintptr>(t), 0, 16) : name;
+}
+
+// Run `fn` on `target`'s own thread. If we're already there, runs immediately;
+// otherwise posts via QMetaObject::invokeMethod with QueuedConnection.
+//
+// Why: QWebSocket / QSslSocket internally bind QSocketNotifier and QTimer to
+// the thread that called open()/close()/sendXxx(). Calling those methods from
+// another thread corrupts the notifier table — Qt logs "QSocketNotifier:
+// Socket notifiers cannot be enabled or disabled from another thread" and then
+// the socket eventually crashes with a use-after-free in SSL_CTX_free during
+// teardown. Marshalling fixes this for every public WebSocketClient method.
+template <typename Fn>
+void run_on_owning_thread(QObject* target, Fn&& fn) {
+ if (!target)
+ return;
+ if (QThread::currentThread() == target->thread()) {
+ fn();
+ } else {
+ QMetaObject::invokeMethod(target, std::forward<Fn>(fn), Qt::QueuedConnection);
+ }
+}
+} // namespace
+
#ifdef HAS_QT_WEBSOCKETS
WebSocketClient::WebSocketClient(QObject* parent) : QObject(parent) {
- connect(&socket_, &QWebSocket::connected, this, &WebSocketClient::on_connected);
- connect(&socket_, &QWebSocket::disconnected, this, &WebSocketClient::on_disconnected);
- connect(&socket_, &QWebSocket::textMessageReceived, this, &WebSocketClient::on_text_received);
- connect(&socket_, &QWebSocket::binaryMessageReceived, this, &WebSocketClient::on_binary_received);
- connect(&socket_, &QWebSocket::errorOccurred, this, &WebSocketClient::on_error);
+ // Parent the QWebSocket to `this` so moveToThread on WebSocketClient
+ // also relocates the socket (and the QSocketNotifier / QTimer children
+ // that QWebSocket creates internally). Otherwise the socket stays on
+ // the construction thread while the wrapper has worker-thread affinity,
+ // and every connect/close/send call is a cross-thread access — Qt logs
+ // "QSocketNotifier: Socket notifiers cannot be enabled or disabled from
+ // another thread" and the SSL context eventually use-after-frees on
+ // teardown.
+ socket_ = new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this);
+ connect(socket_, &QWebSocket::connected, this, &WebSocketClient::on_connected);
+ connect(socket_, &QWebSocket::disconnected, this, &WebSocketClient::on_disconnected);
+ connect(socket_, &QWebSocket::textMessageReceived, this, &WebSocketClient::on_text_received);
+ connect(socket_, &QWebSocket::binaryMessageReceived, this, &WebSocketClient::on_binary_received);
+ connect(socket_, &QWebSocket::errorOccurred, this, &WebSocketClient::on_error);
connect(&reconnect_timer_, &QTimer::timeout, this, &WebSocketClient::attempt_reconnect);
reconnect_timer_.setSingleShot(true);
}
void WebSocketClient::connect_to(const QString& url) {
- url_ = url;
- reconnect_attempts_ = 0;
- LOG_INFO("WS", "Connecting to " + url);
- socket_.open(QUrl(url));
+ QPointer<WebSocketClient> self(this);
+ const QString u = url;
+ run_on_owning_thread(this, [self, u]() {
+ if (!self)
+ return;
+ self->url_ = u;
+ self->reconnect_attempts_ = 0;
+ LOG_INFO(kTag, QString("[%1] Connecting to %2").arg(thread_label(), u));
+ self->socket_->open(QUrl(u));
+ });
}
void WebSocketClient::disconnect() {
- reconnect_timer_.stop();
- socket_.close();
+ QPointer<WebSocketClient> self(this);
+ run_on_owning_thread(this, [self]() {
+ if (!self)
+ return;
+ LOG_INFO(kTag, QString("[%1] Disconnect requested for %2").arg(thread_label(), self->url_));
+ self->reconnect_timer_.stop();
+ self->socket_->close();
+ });
}
void WebSocketClient::send(const QString& message) {
- socket_.sendTextMessage(message);
+ QPointer<WebSocketClient> self(this);
+ const QString m = message;
+ run_on_owning_thread(this, [self, m]() {
+ if (!self)
+ return;
+ self->socket_->sendTextMessage(m);
+ });
}
void WebSocketClient::send_binary(const QByteArray& data) {
- socket_.sendBinaryMessage(data);
+ QPointer<WebSocketClient> self(this);
+ const QByteArray d = data;
+ run_on_owning_thread(this, [self, d]() {
+ if (!self)
+ return;
+ self->socket_->sendBinaryMessage(d);
+ });
}
bool WebSocketClient::is_connected() const {
- return socket_.state() == QAbstractSocket::ConnectedState;
+ // Read of QAbstractSocket::state is documented as thread-safe.
+ return socket_ && socket_->state() == QAbstractSocket::ConnectedState;
}
void WebSocketClient::on_connected() {
- LOG_INFO("WS", "Connected to " + url_);
+ LOG_INFO(kTag, QString("[%1] Connected to %2").arg(thread_label(), url_));
reconnect_attempts_ = 0;
emit connected();
}
void WebSocketClient::on_disconnected() {
- LOG_WARN("WS", "Disconnected from " + url_);
+ LOG_WARN(kTag, QString("[%1] Disconnected from %2 (state=%3)")
+ .arg(thread_label(), url_)
+ .arg(static_cast<int>(socket_ ? socket_->state() : QAbstractSocket::UnconnectedState)));
emit disconnected();
if (reconnect_attempts_ < MAX_RECONNECT_ATTEMPTS) {
- int delay = std::min(1000 * (1 << reconnect_attempts_), 30000);
+ const int delay = std::min(1000 * (1 << reconnect_attempts_), 30000);
+ LOG_INFO(kTag, QString("[%1] Scheduling reconnect attempt %2/%3 in %4ms")
+ .arg(thread_label())
+ .arg(reconnect_attempts_ + 1)
+ .arg(MAX_RECONNECT_ATTEMPTS)
+ .arg(delay));
reconnect_timer_.start(delay);
+ } else {
+ LOG_ERROR(kTag, QString("[%1] Max reconnect attempts (%2) reached for %3")
+ .arg(thread_label())
+ .arg(MAX_RECONNECT_ATTEMPTS)
+ .arg(url_));
}
}
@@ -64,22 +147,28 @@ void WebSocketClient::on_binary_received(const QByteArray& data) {
}
void WebSocketClient::on_error(QAbstractSocket::SocketError err) {
- Q_UNUSED(err);
- LOG_ERROR("WS", "Error: " + socket_.errorString());
- emit error_occurred(socket_.errorString());
+ const QString es = socket_ ? socket_->errorString() : QStringLiteral("(no socket)");
+ LOG_ERROR(kTag, QString("[%1] Error on %2: %3 (code=%4)")
+ .arg(thread_label(), url_, es)
+ .arg(static_cast<int>(err)));
+ emit error_occurred(es);
}
void WebSocketClient::attempt_reconnect() {
reconnect_attempts_++;
- LOG_INFO("WS", QString("Reconnect attempt %1/%2").arg(reconnect_attempts_).arg(MAX_RECONNECT_ATTEMPTS));
- socket_.open(QUrl(url_));
+ LOG_INFO(kTag, QString("[%1] Reconnect attempt %2/%3 to %4")
+ .arg(thread_label())
+ .arg(reconnect_attempts_)
+ .arg(MAX_RECONNECT_ATTEMPTS)
+ .arg(url_));
+ socket_->open(QUrl(url_));
}
#else // No Qt WebSockets — stub implementations
WebSocketClient::WebSocketClient(QObject* parent) : QObject(parent) {}
void WebSocketClient::connect_to(const QString& /*url*/) {
- LOG_WARN("WS", "WebSocket not available — Qt6::WebSockets not installed");
+ LOG_WARN(kTag, "WebSocket not available — Qt6::WebSockets not installed");
}
void WebSocketClient::disconnect() {}
void WebSocketClient::send(const QString& /*message*/) {}
diff --git a/fincept-qt/src/network/websocket/WebSocketClient.h b/fincept-qt/src/network/websocket/WebSocketClient.h
index 3492a4e8f..8ab7eb919 100644
--- a/fincept-qt/src/network/websocket/WebSocketClient.h
+++ b/fincept-qt/src/network/websocket/WebSocketClient.h
@@ -41,7 +41,12 @@ class WebSocketClient : public QObject {
private:
#ifdef HAS_QT_WEBSOCKETS
- QWebSocket socket_;
+ // Heap-allocated and parented to `this` so moveToThread on
+ // WebSocketClient also relocates the socket (and its internal
+ // QSocketNotifier / QTimer children). A value member would have no
+ // parent and therefore would not be carried by Qt's child-move
+ // machinery — leading to cross-thread socket access on every method.
+ QWebSocket* socket_ = nullptr;
#endif
QTimer reconnect_timer_;
QString url_;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
index 66c039a23..1405af492 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp
@@ -1,4 +1,21 @@
-// CryptoBottomPanel.cpp — tabbed panel with Time&Sales and Depth Chart
+// CryptoBottomPanel.cpp — production trading-terminal bottom panel.
+//
+// Tabs: POS · ORD · HIST · MY TRADES · FEES · T&S · DEPTH · MKT · STATS
+//
+// Design goals:
+// • Fully responsive across desktop/laptop/HiDPI: column resize modes are
+// explicit (Stretch / ResizeToContents / Interactive / Fixed) so tables
+// expand into available width without horizontal scrollbars on common
+// layouts and don't collapse below readable widths on narrow ones.
+// • Row heights derive from QFontMetrics so they scale with the user's
+// terminal font setting instead of being pinned to a hard-coded pixel.
+// • Empty states: each table-tab is wrapped in a QStackedWidget that
+// flips to a centered placeholder when the data set is empty — no more
+// "header-only" tables on relaunch before the first WS tick lands.
+// • MKT / STATS use a 3-column card grid (responsive via QGridLayout)
+// instead of a row stack of labels, so they read like a Bloomberg-style
+// dashboard rather than a ledger.
+
#include "screens/crypto_trading/CryptoBottomPanel.h"
#include "screens/crypto_trading/CryptoDepthChart.h"
@@ -6,10 +23,13 @@
#include "ui/theme/Theme.h"
#include <QDateTime>
+#include <QFontMetrics>
+#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QJsonObject>
#include <QPushButton>
+#include <QStackedWidget>
#include <QVBoxLayout>
#include <cmath>
@@ -19,27 +39,127 @@ namespace fincept::screens::crypto {
using namespace fincept::ui;
namespace {
-inline QColor kRowEven() {
- return QColor(colors::BG_BASE());
-}
-inline QColor kRowOdd() {
- return QColor(colors::ROW_ALT());
-}
-inline QColor kColorPos() {
- return QColor(colors::POSITIVE());
-}
-inline QColor kColorNeg() {
- return QColor(colors::NEGATIVE());
-}
-inline QColor kColorSec() {
- return QColor(colors::TEXT_SECONDARY());
+
+inline QColor kRowEven() { return QColor(colors::BG_BASE()); }
+inline QColor kRowOdd() { return QColor(colors::ROW_ALT()); }
+inline QColor kColorPos() { return QColor(colors::POSITIVE()); }
+inline QColor kColorNeg() { return QColor(colors::NEGATIVE()); }
+inline QColor kColorSec() { return QColor(colors::TEXT_SECONDARY()); }
+inline QColor kColorTert() { return QColor(colors::TEXT_TERTIARY()); }
+
+// Per-column resize policy.
+// Stretch: fills remaining horizontal space (use for the "primary" column
+// like Symbol — at least one per table or the last col stretches
+// by default).
+// Numeric: Interactive with a width derived from font metrics (e.g.
+// "1234567890.12" worth of digits). User-resizable.
+// Compact: ResizeToContents — best for short categorical text like
+// "BUY"/"LONG"/"FILLED".
+// Action: Fixed pixel width — for cancel/close buttons.
+enum class ColMode { Stretch, Numeric, Compact, Action };
+
+struct ColSpec {
+ QString header;
+ ColMode mode = ColMode::Stretch;
+ int width_chars = 8; // hint for Numeric mode
+ int fixed_px = 32; // for Action mode
+ Qt::Alignment align = Qt::AlignLeft | Qt::AlignVCenter;
+};
+
+QTableWidget* make_table(const QList<ColSpec>& cols) {
+ auto* t = new QTableWidget;
+ t->setObjectName("cryptoBottomTable");
+ t->setColumnCount(cols.size());
+
+ QStringList headers;
+ headers.reserve(cols.size());
+ for (const auto& c : cols) headers << c.header;
+ t->setHorizontalHeaderLabels(headers);
+
+ t->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ t->setSelectionBehavior(QAbstractItemView::SelectRows);
+ t->setSelectionMode(QAbstractItemView::SingleSelection);
+ t->setFocusPolicy(Qt::NoFocus);
+ t->setAlternatingRowColors(false); // we paint zebra stripes ourselves
+ t->setShowGrid(false);
+ t->setWordWrap(false);
+ t->setTextElideMode(Qt::ElideRight);
+ t->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
+ t->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
+
+ auto* vh = t->verticalHeader();
+ vh->hide();
+ // Row height scales with the active font — important for HiDPI and for
+ // users who bump the terminal font size in Settings → Appearance.
+ const int row_h = std::max(22, QFontMetrics(t->font()).height() + 8);
+ vh->setDefaultSectionSize(row_h);
+
+ auto* hh = t->horizontalHeader();
+ hh->setSectionsClickable(false);
+ hh->setHighlightSections(false);
+ hh->setStretchLastSection(false);
+ // Don't let any column collapse below ~48px or text becomes ellipsis-only.
+ hh->setMinimumSectionSize(48);
+ hh->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
+
+ const QFontMetrics fm(hh->font());
+ bool any_stretch = false;
+ for (int i = 0; i < cols.size(); ++i) {
+ const auto& c = cols[i];
+ switch (c.mode) {
+ case ColMode::Stretch:
+ hh->setSectionResizeMode(i, QHeaderView::Stretch);
+ any_stretch = true;
+ break;
+ case ColMode::Numeric: {
+ hh->setSectionResizeMode(i, QHeaderView::Interactive);
+ // Width: max of header text and `width_chars` worth of '0'.
+ const int header_w = fm.horizontalAdvance(c.header) + 24;
+ const int data_w = fm.horizontalAdvance(QString(c.width_chars, QLatin1Char('0'))) + 16;
+ t->setColumnWidth(i, std::max(header_w, data_w));
+ break;
+ }
+ case ColMode::Compact:
+ hh->setSectionResizeMode(i, QHeaderView::ResizeToContents);
+ break;
+ case ColMode::Action:
+ hh->setSectionResizeMode(i, QHeaderView::Fixed);
+ t->setColumnWidth(i, c.fixed_px);
+ break;
+ }
+ }
+ // Fail-safe: if the caller forgot to mark a column as Stretch, stretch
+ // the last numeric/compact column to fill remaining space.
+ if (!any_stretch) hh->setStretchLastSection(true);
+
+ return t;
}
-inline QColor kColorTert() {
- return QColor(colors::TEXT_TERTIARY());
+
+QWidget* wrap_with_empty_state(QTableWidget* table, QStackedWidget*& out_stack,
+ const QString& empty_text) {
+ out_stack = new QStackedWidget;
+ out_stack->setObjectName("cryptoBottomStack");
+ out_stack->addWidget(table);
+
+ auto* placeholder_host = new QWidget;
+ placeholder_host->setObjectName("cryptoEmptyHost");
+ auto* h_layout = new QVBoxLayout(placeholder_host);
+ h_layout->setContentsMargins(0, 0, 0, 0);
+ auto* lbl = new QLabel(empty_text);
+ lbl->setObjectName("cryptoEmptyState");
+ lbl->setAlignment(Qt::AlignCenter);
+ lbl->setWordWrap(true);
+ h_layout->addStretch();
+ h_layout->addWidget(lbl);
+ h_layout->addStretch();
+ out_stack->addWidget(placeholder_host);
+
+ out_stack->setCurrentIndex(1); // start in empty state
+ return out_stack;
}
+
} // namespace
-// Static helper: ensure QTableWidgetItem exists at (row, col)
QTableWidgetItem* CryptoBottomPanel::ensure_item(QTableWidget* table, int row, int col) {
auto* it = table->item(row, col);
if (!it) {
@@ -49,29 +169,27 @@ QTableWidgetItem* CryptoBottomPanel::ensure_item(QTableWidget* table, int row, i
return it;
}
-static QTableWidget* make_table(int cols, const QStringList& headers) {
- auto* t = new QTableWidget;
- t->setObjectName("cryptoBottomTable");
- t->setColumnCount(cols);
- t->setHorizontalHeaderLabels(headers);
- t->horizontalHeader()->setStretchLastSection(true);
- t->setEditTriggers(QAbstractItemView::NoEditTriggers);
- t->verticalHeader()->hide();
- t->setShowGrid(false);
- t->setSelectionMode(QAbstractItemView::NoSelection);
- t->setFocusPolicy(Qt::NoFocus);
- t->verticalHeader()->setDefaultSectionSize(22);
- return t;
+void CryptoBottomPanel::update_empty_state(QTableWidget* /*table*/, QStackedWidget* stack, int row_count) {
+ if (!stack) return;
+ const int target = (row_count > 0) ? 0 : 1;
+ if (stack->currentIndex() != target)
+ stack->setCurrentIndex(target);
}
CryptoBottomPanel::CryptoBottomPanel(QWidget* parent) : QWidget(parent) {
setObjectName("cryptoBottomPanel");
+ setMinimumHeight(180); // keep at least a couple of rows visible on resize
auto* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(0);
tabs_ = new QTabWidget;
tabs_->setObjectName("cryptoBottomTabs");
+ tabs_->setDocumentMode(true);
+ tabs_->tabBar()->setExpanding(false);
+ tabs_->tabBar()->setUsesScrollButtons(true);
+ tabs_->setUsesScrollButtons(true);
setup_positions_tab();
setup_orders_tab();
@@ -94,91 +212,152 @@ CryptoBottomPanel::CryptoBottomPanel(QWidget* parent) : QWidget(parent) {
}
void CryptoBottomPanel::setup_positions_tab() {
- positions_table_ = make_table(7, {"Symbol", "Side", "Qty", "Entry", "Current", "P&L", "Lev"});
- tabs_->addTab(positions_table_, "POS");
+ positions_table_ = make_table({
+ {"Symbol", ColMode::Stretch},
+ {"Side", ColMode::Compact},
+ {"Qty", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Entry", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Mark", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"P&L", ColMode::Numeric, 11, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Lev", ColMode::Compact},
+ });
+ auto* host = wrap_with_empty_state(positions_table_, positions_stack_, "No open positions.");
+ tabs_->addTab(host, "POSITIONS");
}
void CryptoBottomPanel::setup_orders_tab() {
- orders_table_ = make_table(7, {"Symbol", "Side", "Type", "Qty", "Price", "Status", ""});
- tabs_->addTab(orders_table_, "ORD");
+ orders_table_ = make_table({
+ {"Symbol", ColMode::Stretch},
+ {"Side", ColMode::Compact},
+ {"Type", ColMode::Compact},
+ {"Qty", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Price", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Status", ColMode::Compact},
+ {"", ColMode::Action, 0, 36}, // cancel button column
+ });
+ auto* host = wrap_with_empty_state(orders_table_, orders_stack_, "No active orders.");
+ tabs_->addTab(host, "ORDERS");
}
void CryptoBottomPanel::setup_trades_tab() {
- trades_table_ = make_table(7, {"Symbol", "Side", "Price", "Qty", "Fee", "P&L", "Time"});
- tabs_->addTab(trades_table_, "HIST");
+ trades_table_ = make_table({
+ {"Symbol", ColMode::Stretch},
+ {"Side", ColMode::Compact},
+ {"Price", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Qty", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Fee", ColMode::Numeric, 8, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"P&L", ColMode::Numeric, 11, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Time", ColMode::Compact},
+ });
+ auto* host = wrap_with_empty_state(trades_table_, trades_stack_, "No trade history yet.");
+ tabs_->addTab(host, "HISTORY");
}
void CryptoBottomPanel::setup_my_trades_tab() {
- my_trades_table_ = make_table(8, {"Symbol", "Side", "Price", "Amount", "Cost", "Fee", "Ccy", "Time"});
- tabs_->addTab(my_trades_table_, "MY TRADES");
+ my_trades_table_ = make_table({
+ {"Symbol", ColMode::Stretch},
+ {"Side", ColMode::Compact},
+ {"Price", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Amount", ColMode::Numeric, 10, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Cost", ColMode::Numeric, 11, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Fee", ColMode::Numeric, 9, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Ccy", ColMode::Compact},
+ {"Time", ColMode::Compact},
+ });
+ auto* host = wrap_with_empty_state(my_trades_table_, my_trades_stack_,
+ "No exchange-side fills.\nConnect an API key in LIVE mode to populate.");
+ tabs_->addTab(host, "MY TRADES");
}
void CryptoBottomPanel::setup_fees_tab() {
- fees_table_ = make_table(3, {"Symbol", "Maker %", "Taker %"});
- tabs_->addTab(fees_table_, "FEES");
+ fees_table_ = make_table({
+ {"Symbol", ColMode::Stretch},
+ {"Maker %", ColMode::Numeric, 8, 0, Qt::AlignRight | Qt::AlignVCenter},
+ {"Taker %", ColMode::Numeric, 8, 0, Qt::AlignRight | Qt::AlignVCenter},
+ });
+ auto* host = wrap_with_empty_state(fees_table_, fees_stack_, "No fee schedule loaded.");
+ tabs_->addTab(host, "FEES");
+}
+
+namespace {
+// Build a single dashboard card and return a pointer to its value-label.
+// Used by both the MARKET INFO and STATS tabs so they share visual language.
+QLabel* build_card(QGridLayout* grid, int row, int col, const QString& label_text) {
+ auto* card = new QFrame;
+ card->setObjectName("cryptoCard");
+ card->setFrameShape(QFrame::NoFrame);
+ auto* v = new QVBoxLayout(card);
+ v->setContentsMargins(12, 8, 12, 8);
+ v->setSpacing(4);
+
+ auto* lbl = new QLabel(label_text);
+ lbl->setObjectName("cryptoCardLabel");
+ auto* val = new QLabel(QStringLiteral("--"));
+ val->setObjectName("cryptoCardValue");
+ val->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
+
+ v->addWidget(lbl);
+ v->addWidget(val);
+ grid->addWidget(card, row, col);
+ return val;
}
+} // namespace
void CryptoBottomPanel::setup_market_info_tab() {
auto* widget = new QWidget(this);
- auto* grid = new QVBoxLayout(widget);
- grid->setContentsMargins(8, 4, 8, 4);
- grid->setSpacing(0);
-
- auto make_row = [&](const QString& label) -> QLabel* {
- auto* row_widget = new QWidget(this);
- row_widget->setObjectName("cryptoInfoRow");
- row_widget->setFixedHeight(24);
- auto* row = new QHBoxLayout(row_widget);
- row->setContentsMargins(0, 0, 0, 0);
-
- auto* lbl = new QLabel(label);
- lbl->setObjectName("cryptoInfoLabel");
- auto* val = new QLabel("--");
- val->setObjectName("cryptoInfoValue");
- val->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- row->addWidget(lbl);
- row->addStretch();
- row->addWidget(val);
- grid->addWidget(row_widget);
- return val;
- };
-
- funding_label_ = make_row("FUNDING RATE");
- mark_label_ = make_row("MARK PRICE");
- index_label_ = make_row("INDEX PRICE");
- oi_label_ = make_row("OPEN INTEREST");
- fees_label_ = make_row("MAKER / TAKER");
- next_funding_label_ = make_row("NEXT FUNDING");
- grid->addStretch();
-
- tabs_->addTab(widget, "MKT");
+ widget->setObjectName("cryptoCardHost");
+ auto* outer = new QVBoxLayout(widget);
+ outer->setContentsMargins(12, 12, 12, 12);
+ outer->setSpacing(0);
+
+ auto* grid = new QGridLayout;
+ grid->setHorizontalSpacing(10);
+ grid->setVerticalSpacing(10);
+ // 3 cards per row at standard width — collapses gracefully because each
+ // card's QFrame has expanding size policy.
+ for (int c = 0; c < 3; ++c) grid->setColumnStretch(c, 1);
+
+ funding_label_ = build_card(grid, 0, 0, "FUNDING RATE");
+ mark_label_ = build_card(grid, 0, 1, "MARK PRICE");
+ index_label_ = build_card(grid, 0, 2, "INDEX PRICE");
+ oi_label_ = build_card(grid, 1, 0, "OPEN INTEREST");
+ fees_label_ = build_card(grid, 1, 1, "MAKER / TAKER");
+ next_funding_label_ = build_card(grid, 1, 2, "NEXT FUNDING");
+
+ outer->addLayout(grid);
+ outer->addStretch();
+
+ tabs_->addTab(widget, "MARKET");
}
void CryptoBottomPanel::setup_stats_tab() {
auto* widget = new QWidget(this);
- auto* grid = new QVBoxLayout(widget);
- grid->setContentsMargins(8, 4, 8, 4);
- grid->setSpacing(0);
-
- const char* labels[] = {"TOTAL P&L", "WIN RATE", "TOTAL TRADES", "BEST TRADE", "WORST TRADE"};
- for (int i = 0; i < 5; ++i) {
- auto* row = new QWidget(this);
- row->setObjectName("cryptoStatRow");
- row->setFixedHeight(24);
- auto* h = new QHBoxLayout(row);
- h->setContentsMargins(0, 0, 0, 0);
-
- auto* lbl = new QLabel(labels[i]);
- lbl->setObjectName("cryptoStatLabel");
- stat_values_[i] = new QLabel("--");
- stat_values_[i]->setObjectName("cryptoStatValue");
- stat_values_[i]->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- h->addWidget(lbl);
- h->addStretch();
- h->addWidget(stat_values_[i]);
- grid->addWidget(row);
- }
- grid->addStretch();
+ widget->setObjectName("cryptoCardHost");
+ auto* outer = new QVBoxLayout(widget);
+ outer->setContentsMargins(12, 12, 12, 12);
+ outer->setSpacing(0);
+
+ auto* grid = new QGridLayout;
+ grid->setHorizontalSpacing(10);
+ grid->setVerticalSpacing(10);
+ for (int c = 0; c < 3; ++c) grid->setColumnStretch(c, 1);
+
+ static const char* labels[] = {"TOTAL P&L", "WIN RATE", "TOTAL TRADES", "BEST TRADE", "WORST TRADE"};
+ // Row 0: P&L card spans 1 col (most prominent metric), then Win Rate, Trades.
+ // Row 1: Best / Worst.
+ stat_values_[0] = build_card(grid, 0, 0, labels[0]);
+ stat_values_[1] = build_card(grid, 0, 1, labels[1]);
+ stat_values_[2] = build_card(grid, 0, 2, labels[2]);
+ stat_values_[3] = build_card(grid, 1, 0, labels[3]);
+ stat_values_[4] = build_card(grid, 1, 1, labels[4]);
+
+ // Mark P&L cards as such so the QSS can colour them via the [pnl] property.
+ stat_values_[0]->setProperty("pnl", "neutral");
+ stat_values_[3]->setProperty("pnl", "positive");
+ stat_values_[4]->setProperty("pnl", "negative");
+
+ outer->addLayout(grid);
+ outer->addStretch();
tabs_->addTab(widget, "STATS");
}
@@ -194,7 +373,7 @@ void CryptoBottomPanel::set_depth_data(const QVector<QPair<double, double>>& bid
depth_chart_->set_data(bids, asks, spread, spread_pct);
}
-// ── Data setters (with ensure_item pattern) ─────────────────────────────────
+// ── Data setters ────────────────────────────────────────────────────────────
void CryptoBottomPanel::set_positions(const QVector<trading::PtPosition>& positions) {
const int n = positions.size();
@@ -206,9 +385,6 @@ void CryptoBottomPanel::set_positions(const QVector<trading::PtPosition>& positi
const auto& pos = positions[i];
const QColor bg = (i % 2 == 0) ? kRowEven() : kRowOdd();
- // Diff every attribute — this table updates at 10 Hz on the paper
- // bookkeeping flush, and only P&L + current_price actually change per
- // tick. Skipping untouched cells cuts the repaint footprint sharply.
auto set = [&](int col, const QString& text, const QColor& fg = QColor(),
Qt::Alignment align = Qt::AlignLeft | Qt::AlignVCenter) {
auto* it = ensure_item(positions_table_, i, col);
@@ -230,16 +406,13 @@ void CryptoBottomPanel::set_positions(const QVector<trading::PtPosition>& positi
set(4, QString::number(pos.current_price, 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
set(5, QString::number(pos.unrealized_pnl, 'f', 2), pos.unrealized_pnl >= 0 ? kColorPos() : kColorNeg(),
Qt::AlignRight | Qt::AlignVCenter);
- set(6, QString::number(pos.leverage, 'f', 1), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(6, QString::number(pos.leverage, 'f', 1) + QStringLiteral("x"), QColor(), Qt::AlignRight | Qt::AlignVCenter);
}
positions_table_->setUpdatesEnabled(true);
+ update_empty_state(positions_table_, positions_stack_, n);
}
void CryptoBottomPanel::update_position_prices(const QHash<QString, double>& last_prices) {
- // Live mark-to-market patch driven directly by WS ticks. Reads symbol +
- // side + qty + entry from the existing rows (no DB round-trip), computes
- // fresh P&L from the new mark, and patches columns 4 (Current) and 5 (P&L)
- // in place. Long: pnl = (mark - entry) * qty. Short: pnl = (entry - mark) * qty.
if (last_prices.isEmpty() || !positions_table_)
return;
const int n = positions_table_->rowCount();
@@ -311,26 +484,27 @@ void CryptoBottomPanel::set_orders(const QVector<trading::PtOrder>& orders) {
set(1, o.side.toUpper(), o.side == "buy" ? kColorPos() : kColorNeg());
set(2, o.order_type.toUpper());
set(3, QString::number(o.quantity, 'f', 6), QColor(), Qt::AlignRight | Qt::AlignVCenter);
- set(4, o.price ? QString::number(*o.price, 'f', 2) : "MKT", QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(4, o.price ? QString::number(*o.price, 'f', 2) : QStringLiteral("MKT"), QColor(),
+ Qt::AlignRight | Qt::AlignVCenter);
set(5, o.status.toUpper(), kColorSec());
- // Cancel button — reuse existing widget, update its order_id property
auto* existing = qobject_cast<QPushButton*>(orders_table_->cellWidget(i, 6));
if (existing) {
- // Update the stored order ID without recreating the widget
existing->setProperty("order_id", o.id);
} else {
- auto* cancel_btn = new QPushButton("X");
+ auto* cancel_btn = new QPushButton(QStringLiteral("✕"));
cancel_btn->setObjectName("cryptoCancelBtn");
- cancel_btn->setFixedSize(20, 18);
+ cancel_btn->setToolTip("Cancel order");
cancel_btn->setCursor(Qt::PointingHandCursor);
cancel_btn->setProperty("order_id", o.id);
+ cancel_btn->setFocusPolicy(Qt::NoFocus);
connect(cancel_btn, &QPushButton::clicked, this,
[this, cancel_btn]() { emit cancel_order_requested(cancel_btn->property("order_id").toString()); });
orders_table_->setCellWidget(i, 6, cancel_btn);
}
}
orders_table_->setUpdatesEnabled(true);
+ update_empty_state(orders_table_, orders_stack_, n);
}
void CryptoBottomPanel::set_trades(const QVector<trading::PtTrade>& trades) {
@@ -363,23 +537,30 @@ void CryptoBottomPanel::set_trades(const QVector<trading::PtTrade>& trades) {
set(6, t.timestamp, kColorTert());
}
trades_table_->setUpdatesEnabled(true);
+ update_empty_state(trades_table_, trades_stack_, n);
}
void CryptoBottomPanel::set_stats(const trading::PtStats& stats) {
+ auto repolish = [](QLabel* lbl) {
+ if (!lbl || !lbl->style()) return;
+ lbl->style()->unpolish(lbl);
+ lbl->style()->polish(lbl);
+ };
+
stat_values_[0]->setText(QString("$%1").arg(stats.total_pnl, 0, 'f', 2));
stat_values_[0]->setProperty("pnl", stats.total_pnl >= 0 ? "positive" : "negative");
- stat_values_[0]->style()->unpolish(stat_values_[0]);
- stat_values_[0]->style()->polish(stat_values_[0]);
+ repolish(stat_values_[0]);
stat_values_[1]->setText(QString("%1%").arg(stats.win_rate, 0, 'f', 1));
- stat_values_[2]->setText(
- QString("%1 (W:%2 L:%3)").arg(stats.total_trades).arg(stats.winning_trades).arg(stats.losing_trades));
+ stat_values_[2]->setText(QString("%1 W:%2 / L:%3").arg(stats.total_trades).arg(stats.winning_trades).arg(stats.losing_trades));
stat_values_[3]->setText(QString("$%1").arg(stats.largest_win, 0, 'f', 2));
stat_values_[3]->setProperty("pnl", "positive");
+ repolish(stat_values_[3]);
stat_values_[4]->setText(QString("$%1").arg(stats.largest_loss, 0, 'f', 2));
stat_values_[4]->setProperty("pnl", "negative");
+ repolish(stat_values_[4]);
}
void CryptoBottomPanel::set_market_info(const MarketInfoData& info) {
@@ -427,9 +608,11 @@ void CryptoBottomPanel::set_live_positions(const QJsonArray& positions) {
set(4, QString::number(p.value("markPrice").toDouble(), 'f', 2), QColor(), Qt::AlignRight | Qt::AlignVCenter);
const double pnl = p.value("unrealizedPnl").toDouble();
set(5, QString::number(pnl, 'f', 2), pnl >= 0 ? kColorPos() : kColorNeg(), Qt::AlignRight | Qt::AlignVCenter);
- set(6, QString::number(p.value("leverage").toDouble(), 'f', 0), QColor(), Qt::AlignRight | Qt::AlignVCenter);
+ set(6, QString::number(p.value("leverage").toDouble(), 'f', 0) + QStringLiteral("x"), QColor(),
+ Qt::AlignRight | Qt::AlignVCenter);
}
positions_table_->setUpdatesEnabled(true);
+ update_empty_state(positions_table_, positions_stack_, n);
}
void CryptoBottomPanel::set_live_orders(const QJsonArray& orders) {
@@ -464,17 +647,19 @@ void CryptoBottomPanel::set_live_orders(const QJsonArray& orders) {
if (existing_btn) {
existing_btn->setProperty("order_id", o.value("id").toString());
} else {
- auto* cancel_btn = new QPushButton("X");
+ auto* cancel_btn = new QPushButton(QStringLiteral("✕"));
cancel_btn->setObjectName("cryptoCancelBtn");
- cancel_btn->setFixedSize(20, 18);
+ cancel_btn->setToolTip("Cancel order");
cancel_btn->setCursor(Qt::PointingHandCursor);
cancel_btn->setProperty("order_id", o.value("id").toString());
+ cancel_btn->setFocusPolicy(Qt::NoFocus);
connect(cancel_btn, &QPushButton::clicked, this,
[this, cancel_btn]() { emit cancel_order_requested(cancel_btn->property("order_id").toString()); });
orders_table_->setCellWidget(i, 6, cancel_btn);
}
}
orders_table_->setUpdatesEnabled(true);
+ update_empty_state(orders_table_, orders_stack_, n);
}
void CryptoBottomPanel::update_my_trades(const QJsonObject& json) {
@@ -512,32 +697,35 @@ void CryptoBottomPanel::update_my_trades(const QJsonObject& json) {
set(7, time_str, kColorTert());
}
my_trades_table_->setUpdatesEnabled(true);
+ update_empty_state(my_trades_table_, my_trades_stack_, n);
}
void CryptoBottomPanel::update_fees(const QJsonObject& json) {
- // Single-symbol response
- if (json.contains("symbol")) {
- fees_table_->setUpdatesEnabled(false);
- fees_table_->setRowCount(1);
- const QColor bg = kRowEven();
-
- auto set = [&](int col, const QString& text, const QColor& fg = QColor()) {
- auto* it = ensure_item(fees_table_, 0, col);
+ auto write_row = [&](int row, const QColor& bg, const QString& sym, double maker, double taker) {
+ auto set = [&](int col, const QString& text, const QColor& fg = QColor(),
+ Qt::Alignment align = Qt::AlignRight | Qt::AlignVCenter) {
+ auto* it = ensure_item(fees_table_, row, col);
it->setText(text);
if (fg.isValid())
it->setForeground(fg);
it->setBackground(bg);
- it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ it->setTextAlignment(align);
};
+ set(0, sym, QColor(), Qt::AlignLeft | Qt::AlignVCenter);
+ set(1, QString::number(maker * 100.0, 'f', 4) + "%", kColorSec());
+ set(2, QString::number(taker * 100.0, 'f', 4) + "%", kColorSec());
+ };
- set(0, json.value("symbol").toString());
- set(1, QString::number(json.value("maker").toDouble() * 100.0, 'f', 4) + "%", kColorSec());
- set(2, QString::number(json.value("taker").toDouble() * 100.0, 'f', 4) + "%", kColorSec());
+ if (json.contains("symbol")) {
+ fees_table_->setUpdatesEnabled(false);
+ fees_table_->setRowCount(1);
+ write_row(0, kRowEven(), json.value("symbol").toString(),
+ json.value("maker").toDouble(), json.value("taker").toDouble());
fees_table_->setUpdatesEnabled(true);
+ update_empty_state(fees_table_, fees_stack_, 1);
return;
}
- // Multi-symbol response
const QJsonArray fees = json.value("fees").toArray();
const int n = fees.size();
fees_table_->setUpdatesEnabled(false);
@@ -547,21 +735,11 @@ void CryptoBottomPanel::update_fees(const QJsonObject& json) {
for (int i = 0; i < n; ++i) {
const auto f = fees[i].toObject();
const QColor bg = (i % 2 == 0) ? kRowEven() : kRowOdd();
-
- auto set = [&](int col, const QString& text, const QColor& fg = QColor()) {
- auto* it = ensure_item(fees_table_, i, col);
- it->setText(text);
- if (fg.isValid())
- it->setForeground(fg);
- it->setBackground(bg);
- it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
- };
-
- set(0, f.value("symbol").toString());
- set(1, QString::number(f.value("maker").toDouble() * 100.0, 'f', 4) + "%", kColorSec());
- set(2, QString::number(f.value("taker").toDouble() * 100.0, 'f', 4) + "%", kColorSec());
+ write_row(i, bg, f.value("symbol").toString(),
+ f.value("maker").toDouble(), f.value("taker").toDouble());
}
fees_table_->setUpdatesEnabled(true);
+ update_empty_state(fees_table_, fees_stack_, n);
}
void CryptoBottomPanel::set_live_balance(double balance, double equity, double used_margin) {
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
index a485a002d..dd0350930 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h
@@ -6,6 +6,7 @@
#include <QJsonArray>
#include <QLabel>
+#include <QStackedWidget>
#include <QTabWidget>
#include <QTableWidget>
#include <QVector>
@@ -63,6 +64,7 @@ class CryptoBottomPanel : public QWidget {
void setup_stats_tab();
static QTableWidgetItem* ensure_item(QTableWidget* table, int row, int col);
+ void update_empty_state(QTableWidget* table, QStackedWidget* stack, int row_count);
QTabWidget* tabs_ = nullptr;
@@ -72,6 +74,15 @@ class CryptoBottomPanel : public QWidget {
QTableWidget* my_trades_table_ = nullptr;
QTableWidget* fees_table_ = nullptr;
+ // Each table is wrapped in a QStackedWidget so we can swap between the
+ // table (page 0) and an empty-state placeholder (page 1) when the data
+ // set is empty. Avoids the "blank table with header only" UX.
+ QStackedWidget* positions_stack_ = nullptr;
+ QStackedWidget* orders_stack_ = nullptr;
+ QStackedWidget* trades_stack_ = nullptr;
+ QStackedWidget* my_trades_stack_ = nullptr;
+ QStackedWidget* fees_stack_ = nullptr;
+
// Market Info
QLabel* funding_label_ = nullptr;
QLabel* mark_label_ = nullptr;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp b/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp
index 61388e864..f5dc01c33 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp
@@ -1,4 +1,30 @@
-// CryptoChart.cpp — Candlestick chart with TF toggles, vibrant colors
+// CryptoChart.cpp — production candlestick chart on top of Qt Charts.
+//
+// Why Qt Charts and not TradingView Lightweight Charts?
+// ------------------------------------------------------
+// TradingView's library is JavaScript-only. Embedding it would require
+// QtWebEngineWidgets (Chromium runtime), which is currently not in this
+// project's Qt module set and would add ~100 MB to the macOS .app and the
+// Windows installer. We can revisit if richer charting (drawing tools,
+// indicators panel, replay) becomes worth that footprint.
+//
+// What this widget does on top of stock Qt Charts:
+// • Crosshair on hover (vertical + horizontal lines through the cursor)
+// • OHLC tooltip in the top-left, updated to the candle under the cursor
+// • Right-edge price tag at the cursor's price (snaps to grid)
+// • Bottom-edge time tag at the cursor's time
+// • Always-visible "last price" tag pinned to the right axis at the
+// most recent close — colour-coded green/red by the latest direction
+// • Time-axis label format auto-scales with the timeframe
+// (HH:mm · MMM dd HH:mm · MMM dd · MMM yy)
+// • Generous bottom margin so the time-axis labels stop being clipped
+// • Mouse wheel = zoom price axis; drag = pan
+//
+// Sizing principles:
+// • No pixel-pinned heights on the header buttons — uses QSS padding so
+// the toolbar scales with the user's font size.
+// • setMinimumHeight(280) to keep the chart usable on narrow splitters.
+
#include "screens/crypto_trading/CryptoChart.h"
#include "ui/theme/Theme.h"
@@ -9,12 +35,27 @@
#include <QChartView>
#include <QDateTime>
#include <QDateTimeAxis>
+#include <QEnterEvent>
+#include <QFont>
+#include <QGraphicsLayout>
+#include <QGraphicsEllipseItem>
+#include <QGraphicsLineItem>
+#include <QGraphicsRectItem>
+#include <QGraphicsScene>
+#include <QGraphicsSimpleTextItem>
#include <QHBoxLayout>
#include <QLabel>
+#include <QLineSeries>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QPen>
#include <QStyle>
-#include <QVBoxLayout>
+#include <QToolTip>
#include <QValueAxis>
+#include <QVBoxLayout>
+#include <QWheelEvent>
+#include <algorithm>
#include <cmath>
using namespace fincept::ui;
@@ -23,6 +64,94 @@ namespace fincept::screens::crypto {
constexpr const char* CryptoChart::TF_LABELS[];
+namespace {
+
+// Maps a timeframe label to its slot duration in milliseconds. Used to
+// extend the time axis by one slot when there is only one candle (otherwise
+// QCandlestickSeries renders bars as hairlines) and to pick the time-axis
+// label format.
+qint64 tf_slot_ms(const QString& tf) {
+ if (tf == QLatin1String("1m")) return 60'000;
+ if (tf == QLatin1String("5m")) return 5 * 60'000;
+ if (tf == QLatin1String("15m")) return 15 * 60'000;
+ if (tf == QLatin1String("1h")) return 60 * 60'000;
+ if (tf == QLatin1String("4h")) return 4 * 60 * 60'000;
+ if (tf == QLatin1String("1d")) return 24 * 60 * 60'000;
+ return 60'000;
+}
+
+// Choose a time-axis label format that fits the chart's time span without
+// overlapping ticks. Driven by total span, not just the timeframe, so a
+// 120-bar 1d chart shows months/years rather than redundant day labels.
+QString time_format_for(qint64 span_ms) {
+ constexpr qint64 kHour = 60LL * 60 * 1000;
+ constexpr qint64 kDay = 24 * kHour;
+ if (span_ms <= 6 * kHour) return QStringLiteral("HH:mm");
+ if (span_ms <= 3 * kDay) return QStringLiteral("MMM dd HH:mm");
+ if (span_ms <= 90 * kDay) return QStringLiteral("MMM dd");
+ return QStringLiteral("MMM yy");
+}
+
+QFont scene_font() {
+ QFont f;
+ f.setFamily(QStringLiteral("Consolas"));
+ f.setPointSize(9);
+ f.setWeight(QFont::DemiBold);
+ return f;
+}
+
+} // namespace
+
+// ── HoverChartView ──────────────────────────────────────────────────────────
+// Custom QChartView that forwards mouse-move events to the parent CryptoChart
+// so the crosshair / OHLC tooltip can update without subclassing the chart
+// itself. Also enables wheel-zoom on the price axis and drag-pan.
+class HoverChartView : public QChartView {
+ public:
+ HoverChartView(QChart* chart, CryptoChart* host)
+ : QChartView(chart), host_(host) {
+ setMouseTracking(true);
+ setRenderHint(QPainter::Antialiasing, true);
+ setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ setRubberBand(QChartView::NoRubberBand);
+ setDragMode(QGraphicsView::NoDrag);
+ }
+
+ protected:
+ void mouseMoveEvent(QMouseEvent* e) override {
+ if (host_ && chart()) {
+ const QPointF chart_pos = chart()->mapToValue(e->pos());
+ host_->on_hover_position(chart_pos, e->pos());
+ }
+ QChartView::mouseMoveEvent(e);
+ }
+ void leaveEvent(QEvent* e) override {
+ if (host_) host_->on_hover_leave();
+ QChartView::leaveEvent(e);
+ }
+ void wheelEvent(QWheelEvent* e) override {
+ if (!chart()) {
+ QChartView::wheelEvent(e);
+ return;
+ }
+ // Zoom price axis only. Wheel-panning the time axis collides with the
+ // candle stream — users expect Time fixed and Price scaled.
+ const double factor = (e->angleDelta().y() > 0) ? 0.9 : 1.1;
+ if (auto* y = qobject_cast<QValueAxis*>(host_ ? host_->price_axis_ : nullptr)) {
+ const double mid = (y->min() + y->max()) / 2.0;
+ const double span = (y->max() - y->min()) * factor;
+ y->setRange(mid - span / 2.0, mid + span / 2.0);
+ }
+ e->accept();
+ }
+
+ private:
+ CryptoChart* host_ = nullptr;
+};
+
+// ── CryptoChart ─────────────────────────────────────────────────────────────
+
CryptoChart::CryptoChart(QWidget* parent) : QWidget(parent) {
setObjectName("cryptoChart");
@@ -30,15 +159,14 @@ CryptoChart::CryptoChart(QWidget* parent) : QWidget(parent) {
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
- // Header with TF toggle buttons
+ // ── Header with TF toggles ─────────────────────────────────────────────
auto* header = new QWidget(this);
header->setObjectName("cryptoChartHeader");
- header->setFixedHeight(28);
auto* h_layout = new QHBoxLayout(header);
- h_layout->setContentsMargins(8, 0, 8, 0);
+ h_layout->setContentsMargins(10, 4, 10, 4);
h_layout->setSpacing(2);
- auto* title = new QLabel("CHART");
+ auto* title = new QLabel(QStringLiteral("CHART"));
title->setObjectName("cryptoChartTitle");
h_layout->addWidget(title);
h_layout->addSpacing(8);
@@ -46,68 +174,137 @@ CryptoChart::CryptoChart(QWidget* parent) : QWidget(parent) {
for (int i = 0; i < 6; ++i) {
tf_buttons_[i] = new QPushButton(TF_LABELS[i]);
tf_buttons_[i]->setObjectName("cryptoTfBtn");
- tf_buttons_[i]->setFixedHeight(22);
tf_buttons_[i]->setCursor(Qt::PointingHandCursor);
- if (i == active_tf_)
- tf_buttons_[i]->setProperty("active", true);
+ tf_buttons_[i]->setFocusPolicy(Qt::NoFocus);
+ if (i == active_tf_) tf_buttons_[i]->setProperty("active", true);
connect(tf_buttons_[i], &QPushButton::clicked, this, [this, i]() { set_active_tf(i); });
h_layout->addWidget(tf_buttons_[i]);
}
h_layout->addStretch();
layout->addWidget(header);
- // Chart setup
+ // ── Chart proper ───────────────────────────────────────────────────────
chart_ = new QChart;
chart_->setBackgroundBrush(QBrush(QColor(colors::BG_SURFACE())));
+ chart_->setBackgroundPen(QPen(Qt::NoPen));
chart_->setPlotAreaBackgroundBrush(QBrush(QColor(colors::BG_BASE())));
chart_->setPlotAreaBackgroundVisible(true);
chart_->legend()->hide();
- chart_->setMargins(QMargins(4, 4, 4, 4));
+ // Generous bottom + right margins so axis labels are NEVER clipped.
+ // The previous (4,4,4,4) was the cause of the "bottom time axis isn't
+ // visible" symptom — Qt Charts renders the axis labels INSIDE the chart
+ // margin, so 4 px wasn't enough to fit a 12 px label.
+ // Right margin = 72 px gives the price-axis labels and the right-edge
+ // hover/last-price tags room for "99999.99" without bleeding into the
+ // plot. Bottom = 36 px fits "MMM dd HH:mm" comfortably.
+ chart_->setMargins(QMargins(6, 6, 72, 36));
+ if (auto* l = chart_->layout())
+ l->setContentsMargins(0, 0, 0, 0);
series_ = new QCandlestickSeries;
- // Vibrant candle colors
series_->setIncreasingColor(QColor(colors::POSITIVE()));
series_->setDecreasingColor(QColor(colors::NEGATIVE()));
- series_->setBodyWidth(0.75);
+ series_->setBodyWidth(0.78);
series_->setPen(QPen(Qt::NoPen)); // no outline on body
- series_->setCapsVisible(false); // clean look
+ series_->setCapsVisible(false);
chart_->addSeries(series_);
time_axis_ = new QDateTimeAxis;
- time_axis_->setFormat("HH:mm");
- time_axis_->setLabelsColor(QColor(colors::TEXT_DIM()));
- time_axis_->setGridLineColor(QColor(colors::BG_RAISED()));
- time_axis_->setMinorGridLineColor(QColor(colors::BG_SURFACE()));
+ time_axis_->setFormat(QStringLiteral("HH:mm"));
+ time_axis_->setLabelsColor(QColor(colors::TEXT_SECONDARY()));
+ time_axis_->setLabelsFont(scene_font());
+ time_axis_->setGridLineColor(QColor(colors::BORDER_DIM()));
+ time_axis_->setMinorGridLineColor(QColor(colors::BG_RAISED()));
time_axis_->setLinePenColor(QColor(colors::BORDER_DIM()));
+ time_axis_->setTickCount(6);
chart_->addAxis(time_axis_, Qt::AlignBottom);
series_->attachAxis(time_axis_);
price_axis_ = new QValueAxis;
- price_axis_->setLabelsColor(QColor(colors::TEXT_DIM()));
- price_axis_->setGridLineColor(QColor(colors::BG_RAISED()));
- price_axis_->setMinorGridLineColor(QColor(colors::BG_SURFACE()));
+ price_axis_->setLabelsColor(QColor(colors::TEXT_SECONDARY()));
+ price_axis_->setLabelsFont(scene_font());
+ price_axis_->setGridLineColor(QColor(colors::BORDER_DIM()));
+ price_axis_->setMinorGridLineColor(QColor(colors::BG_RAISED()));
price_axis_->setLinePenColor(QColor(colors::BORDER_DIM()));
- price_axis_->setLabelFormat("%.1f");
+ price_axis_->setLabelFormat(QStringLiteral("%.2f"));
+ price_axis_->setTickCount(6);
chart_->addAxis(price_axis_, Qt::AlignRight);
series_->attachAxis(price_axis_);
- chart_view_ = new QChartView(chart_);
- chart_view_->setRenderHint(QPainter::Antialiasing, false);
+ // ── Last-price line (horizontal) ───────────────────────────────────────
+ last_price_line_ = new QLineSeries;
+ last_price_line_->setUseOpenGL(false);
+ QPen last_pen;
+ last_pen.setColor(QColor(colors::AMBER()));
+ last_pen.setStyle(Qt::DashLine);
+ last_pen.setWidthF(1.0);
+ last_price_line_->setPen(last_pen);
+ chart_->addSeries(last_price_line_);
+ last_price_line_->attachAxis(time_axis_);
+ last_price_line_->attachAxis(price_axis_);
+
+ // ── Chart view ─────────────────────────────────────────────────────────
+ chart_view_ = new HoverChartView(chart_, this);
layout->addWidget(chart_view_, 1);
- // Minimum height so chart is never too small
- setMinimumHeight(300);
+ // ── Scene overlays (crosshair, price/time tags, last-price tag) ────────
+ auto* scene = chart_view_->scene();
+ QPen pen_grid;
+ pen_grid.setColor(QColor(colors::BORDER_BRIGHT()));
+ pen_grid.setStyle(Qt::DashLine);
+ pen_grid.setWidthF(0.8);
+
+ xhair_v_ = scene->addLine(QLineF(), pen_grid);
+ xhair_h_ = scene->addLine(QLineF(), pen_grid);
+ xhair_v_->setZValue(20);
+ xhair_h_->setZValue(20);
+ xhair_v_->setVisible(false);
+ xhair_h_->setVisible(false);
+
+ // Small dot at the crosshair intersection — gives the user a clear
+ // anchor point and disambiguates which exact price/time the tags refer
+ // to when the cursor is moving fast.
+ QPen dot_pen;
+ dot_pen.setColor(QColor(colors::AMBER()));
+ dot_pen.setWidthF(1.0);
+ xhair_dot_ = scene->addEllipse(QRectF(-3, -3, 6, 6), dot_pen,
+ QBrush(QColor(colors::BG_BASE())));
+ xhair_dot_->setZValue(23);
+ xhair_dot_->setVisible(false);
+
+ auto build_tag = [&](QGraphicsRectItem*& bg, QGraphicsSimpleTextItem*& txt,
+ const QColor& fill, const QColor& text_color) {
+ bg = scene->addRect(QRectF(), QPen(Qt::NoPen), QBrush(fill));
+ bg->setZValue(21);
+ bg->setVisible(false);
+ txt = scene->addSimpleText(QStringLiteral(""));
+ txt->setBrush(QBrush(text_color));
+ txt->setFont(scene_font());
+ txt->setZValue(22);
+ txt->setVisible(false);
+ };
+ build_tag(price_tag_bg_, price_tag_txt_, QColor(colors::BG_RAISED()), QColor(colors::TEXT_PRIMARY()));
+ build_tag(time_tag_bg_, time_tag_txt_, QColor(colors::BG_RAISED()), QColor(colors::TEXT_PRIMARY()));
+ build_tag(last_tag_bg_, last_tag_txt_, QColor(colors::AMBER()), QColor(colors::BG_BASE()));
+
+ // ── OHLC tooltip pinned to top-left of the chart widget ────────────────
+ ohlc_tooltip_ = new QLabel(chart_view_);
+ ohlc_tooltip_->setObjectName("cryptoChartOhlc");
+ ohlc_tooltip_->setVisible(false);
+ ohlc_tooltip_->setAttribute(Qt::WA_TransparentForMouseEvents);
+ ohlc_tooltip_->move(12, 12);
+
+ setMinimumHeight(280);
}
void CryptoChart::set_active_tf(int idx) {
- // Optimistically update the button highlight so the user gets immediate feedback.
for (int i = 0; i < 6; ++i) {
tf_buttons_[i]->setProperty("active", i == idx);
- tf_buttons_[i]->update();
+ if (auto* st = tf_buttons_[i]->style()) {
+ st->unpolish(tf_buttons_[i]);
+ st->polish(tf_buttons_[i]);
+ }
}
- // Store as pending — if candles_fetching_ is true in the screen, the fetch will
- // be dropped. set_candles() re-emits timeframe_changed with pending_tf_ so the
- // screen retries after the in-flight fetch completes.
pending_tf_ = TF_LABELS[idx];
active_tf_ = idx;
emit timeframe_changed(TF_LABELS[idx]);
@@ -120,10 +317,9 @@ QString CryptoChart::current_timeframe() const {
void CryptoChart::set_candles(const QVector<trading::Candle>& candles) {
candles_ = candles;
rebuild_chart();
+ apply_tf_axis_format();
+ update_last_price_marker();
- // If the user changed the timeframe while the previous fetch was in-flight,
- // the screen's candles_fetching_ guard would have dropped that request.
- // Re-emit now that we're idle so the screen retries for the correct timeframe.
if (!pending_tf_.isEmpty()) {
const QString tf = pending_tf_;
pending_tf_.clear();
@@ -132,7 +328,6 @@ void CryptoChart::set_candles(const QVector<trading::Candle>& candles) {
}
void CryptoChart::append_candle(const trading::Candle& candle) {
- // Reject malformed candles — zero/negative prices corrupt the axis range
if (candle.open <= 0.0 || candle.high <= 0.0 || candle.low <= 0.0 || candle.close <= 0.0 || candle.timestamp <= 0)
return;
if (candle.low > candle.high)
@@ -151,8 +346,6 @@ void CryptoChart::append_candle(const trading::Candle& candle) {
last_set->setLow(candle.low);
last_set->setClose(candle.close);
}
- // Intrabar update: if the replaced candle defined the current extreme,
- // bounds may shrink — mark dirty. Otherwise cheap widen-only.
if (!bounds_dirty_) {
if (prev.high >= cached_max_price_ || prev.low <= cached_min_price_) {
bounds_dirty_ = true;
@@ -166,11 +359,11 @@ void CryptoChart::append_candle(const trading::Candle& candle) {
if (candles_.size() > MAX_VISIBLE * 2) {
candles_.remove(0, candles_.size() - MAX_VISIBLE);
rebuild_chart();
+ apply_tf_axis_format();
+ update_last_price_marker();
return;
}
if (sets.size() >= MAX_VISIBLE) {
- // Evicting the oldest set may drop the current extreme — mark dirty
- // so we rescan exactly once on the next axis update.
const auto* oldest = sets.first();
if (!bounds_dirty_ &&
(oldest->low() <= cached_min_price_ || oldest->high() >= cached_max_price_)) {
@@ -180,7 +373,6 @@ void CryptoChart::append_candle(const trading::Candle& candle) {
}
series_->append(new QCandlestickSet(candle.open, candle.high, candle.low, candle.close, candle.timestamp));
- // Widen-only for new candle if bounds are clean.
if (!bounds_dirty_) {
cached_max_price_ = std::max(cached_max_price_, candle.high);
cached_min_price_ = std::min(cached_min_price_, candle.low);
@@ -194,11 +386,11 @@ void CryptoChart::append_candle(const trading::Candle& candle) {
if (bounds_dirty_)
recompute_bounds();
- // Time axis — min is O(1) from sets.first, max from last. Sets stay ordered
- // by insertion which matches timestamp order for this use case.
const qint64 min_time = static_cast<qint64>(visible_sets.first()->timestamp());
const qint64 max_time = static_cast<qint64>(visible_sets.last()->timestamp());
update_axes(cached_min_price_, cached_max_price_, min_time, max_time);
+ apply_tf_axis_format();
+ update_last_price_marker();
}
void CryptoChart::recompute_bounds() {
@@ -222,15 +414,19 @@ void CryptoChart::recompute_bounds() {
void CryptoChart::clear() {
candles_.clear();
series_->clear();
+ if (last_price_line_) last_price_line_->clear();
cached_min_price_ = cached_max_price_ = -1;
bounds_dirty_ = true;
+ if (last_tag_bg_) last_tag_bg_->setVisible(false);
+ if (last_tag_txt_) last_tag_txt_->setVisible(false);
+ on_hover_leave();
}
void CryptoChart::update_axes(double min_price, double max_price, qint64 min_time, qint64 max_time) {
if (min_price >= max_price)
- return; // invalid range
+ return;
- const double padding = (max_price - min_price) * 0.05;
+ const double padding = (max_price - min_price) * 0.06;
const double p_min = min_price - padding;
const double p_max = max_price + padding;
@@ -240,35 +436,29 @@ void CryptoChart::update_axes(double min_price, double max_price, qint64 min_tim
last_max_price_ = p_max;
}
- // QCandlestickSeries computes bar width as bodyWidth * (axis_span / bar_count).
- // If min_time == max_time (single candle or all same timestamp), bar width → 0
- // and all candles render as hairlines. Add a one-interval padding on the right
- // so the axis always spans at least 2 × the per-candle slot.
qint64 effective_max = max_time;
if (min_time >= max_time) {
- // Fallback: extend by one slot using the TF label
- const QString tf = TF_LABELS[active_tf_];
- qint64 slot_ms = 60000; // 1m default
- if (tf == "5m")
- slot_ms = 300000;
- else if (tf == "15m")
- slot_ms = 900000;
- else if (tf == "1h")
- slot_ms = 3600000;
- else if (tf == "4h")
- slot_ms = 14400000;
- else if (tf == "1d")
- slot_ms = 86400000;
- effective_max = min_time + slot_ms;
+ effective_max = min_time + tf_slot_ms(TF_LABELS[active_tf_]);
+ } else {
+ // Add half-a-slot of right padding so the latest candle isn't pinned
+ // to the right edge of the plot — looks more like a real terminal.
+ effective_max = max_time + tf_slot_ms(TF_LABELS[active_tf_]) / 2;
}
if (min_time != last_min_time_ || effective_max != last_max_time_) {
- time_axis_->setRange(QDateTime::fromMSecsSinceEpoch(min_time), QDateTime::fromMSecsSinceEpoch(effective_max));
+ time_axis_->setRange(QDateTime::fromMSecsSinceEpoch(min_time),
+ QDateTime::fromMSecsSinceEpoch(effective_max));
last_min_time_ = min_time;
last_max_time_ = effective_max;
}
}
+void CryptoChart::apply_tf_axis_format() {
+ if (!time_axis_) return;
+ const qint64 span = std::max<qint64>(0, last_max_time_ - last_min_time_);
+ time_axis_->setFormat(time_format_for(span));
+}
+
void CryptoChart::rebuild_chart() {
series_->clear();
last_min_price_ = last_max_price_ = -1;
@@ -285,7 +475,6 @@ void CryptoChart::rebuild_chart() {
for (int i = start; i < candles_.size(); ++i) {
const auto& c = candles_[i];
- // Skip malformed candles — any zero/negative OHLC corrupts the axis range
if (c.open <= 0.0 || c.high <= 0.0 || c.low <= 0.0 || c.close <= 0.0 || c.timestamp <= 0)
continue;
if (c.low > c.high || c.open > c.high || c.close > c.high)
@@ -293,13 +482,10 @@ void CryptoChart::rebuild_chart() {
series_->append(new QCandlestickSet(c.open, c.high, c.low, c.close, c.timestamp));
min_price = std::min(min_price, c.low);
max_price = std::max(max_price, c.high);
- if (c.timestamp < min_time)
- min_time = c.timestamp;
- if (c.timestamp > max_time)
- max_time = c.timestamp;
+ if (c.timestamp < min_time) min_time = c.timestamp;
+ if (c.timestamp > max_time) max_time = c.timestamp;
}
- // Seed the incremental-bounds cache from this full scan.
if (min_price < max_price) {
cached_min_price_ = min_price;
cached_max_price_ = max_price;
@@ -309,4 +495,189 @@ void CryptoChart::rebuild_chart() {
update_axes(min_price, max_price, min_time, max_time);
}
+void CryptoChart::update_last_price_marker() {
+ if (!last_price_line_ || candles_.isEmpty()) {
+ if (last_tag_bg_) last_tag_bg_->setVisible(false);
+ if (last_tag_txt_) last_tag_txt_->setVisible(false);
+ return;
+ }
+ const auto& last = candles_.last();
+ const double price = last.close;
+ const bool up = last.close >= last.open;
+ last_price_line_->clear();
+ last_price_line_->append(QDateTime::fromMSecsSinceEpoch(last_min_time_).toMSecsSinceEpoch(), price);
+ last_price_line_->append(QDateTime::fromMSecsSinceEpoch(last_max_time_).toMSecsSinceEpoch(), price);
+
+ QPen pen = last_price_line_->pen();
+ pen.setColor(QColor(up ? colors::POSITIVE() : colors::NEGATIVE()));
+ last_price_line_->setPen(pen);
+
+ // Update the always-visible "last price" tag on the right axis.
+ if (last_tag_bg_ && last_tag_txt_ && chart_) {
+ const QPointF anchor = chart_->mapToPosition(QPointF(last_max_time_, price), series_);
+ const QString text = QString::number(price, 'f', 2);
+ last_tag_txt_->setText(text);
+ const QRectF tb = last_tag_txt_->boundingRect();
+ const qreal pad_x = 6, pad_y = 2;
+ const qreal x = chart_->plotArea().right() + 2;
+ const qreal y = anchor.y() - tb.height() / 2 - pad_y;
+ last_tag_bg_->setRect(QRectF(x, y, tb.width() + 2 * pad_x, tb.height() + 2 * pad_y));
+ last_tag_bg_->setBrush(QBrush(QColor(up ? colors::POSITIVE() : colors::NEGATIVE())));
+ last_tag_txt_->setPos(x + pad_x, y + pad_y);
+ last_tag_bg_->setVisible(true);
+ last_tag_txt_->setVisible(true);
+ }
+}
+
+void CryptoChart::on_hover_position(const QPointF& chart_value_pos, const QPoint& view_pos) {
+ if (!chart_ || candles_.isEmpty()) return;
+
+ const QRectF plot = chart_->plotArea();
+ if (!plot.contains(view_pos)) {
+ on_hover_leave();
+ return;
+ }
+
+ // Crosshair lines: stop a half-pixel before the plot edge so they don't
+ // bleed into the axis labels at the bottom-right corner.
+ const qreal cx = view_pos.x();
+ const qreal cy = view_pos.y();
+ xhair_v_->setLine(cx, plot.top(), cx, plot.bottom());
+ xhair_h_->setLine(plot.left(), cy, plot.right(), cy);
+ xhair_v_->setVisible(true);
+ xhair_h_->setVisible(true);
+
+ // Intersection dot, centred on the cursor.
+ if (xhair_dot_) {
+ xhair_dot_->setRect(cx - 3, cy - 3, 6, 6);
+ xhair_dot_->setVisible(true);
+ }
+
+ // While the cursor is over the chart, hide the always-visible "last
+ // price" tag — otherwise it overlaps the live cursor price tag whenever
+ // the cursor sits at the same y-level as the last close.
+ if (last_tag_bg_) last_tag_bg_->setVisible(false);
+ if (last_tag_txt_) last_tag_txt_->setVisible(false);
+
+ constexpr qreal kPadX = 6;
+ constexpr qreal kPadY = 3;
+
+ // ── Price tag (right of plot) ──────────────────────────────────────────
+ // Clamp Y so the tag never extends past the plot edges into the time tag.
+ {
+ const double price = chart_value_pos.y();
+ price_tag_txt_->setText(QString::number(price, 'f', 2));
+ const QRectF tb = price_tag_txt_->boundingRect();
+ const qreal w = tb.width() + 2 * kPadX;
+ const qreal h = tb.height() + 2 * kPadY;
+ const qreal x = plot.right() + 4;
+ qreal y = cy - h / 2.0;
+ y = std::max(plot.top(), std::min(y, plot.bottom() - h));
+ price_tag_bg_->setRect(QRectF(x, y, w, h));
+ price_tag_txt_->setPos(x + kPadX, y + kPadY);
+ price_tag_bg_->setVisible(true);
+ price_tag_txt_->setVisible(true);
+ }
+
+ // ── Time tag (below plot) ──────────────────────────────────────────────
+ // Clamp X so it never extends into the price-axis gutter on the right or
+ // off the left edge of the chart.
+ {
+ const qint64 ms = static_cast<qint64>(chart_value_pos.x());
+ const QString fmt = time_format_for(std::max<qint64>(0, last_max_time_ - last_min_time_));
+ time_tag_txt_->setText(QDateTime::fromMSecsSinceEpoch(ms).toString(fmt));
+ const QRectF tb = time_tag_txt_->boundingRect();
+ const qreal w = tb.width() + 2 * kPadX;
+ const qreal h = tb.height() + 2 * kPadY;
+ qreal x = cx - w / 2.0;
+ x = std::max(plot.left(), std::min(x, plot.right() - w));
+ const qreal y = plot.bottom() + 4;
+ time_tag_bg_->setRect(QRectF(x, y, w, h));
+ time_tag_txt_->setPos(x + kPadX, y + kPadY);
+ time_tag_bg_->setVisible(true);
+ time_tag_txt_->setVisible(true);
+ }
+
+ // ── OHLC tooltip ───────────────────────────────────────────────────────
+ // Find the candle whose timestamp is closest to the cursor.
+ const qint64 cursor_ms = static_cast<qint64>(chart_value_pos.x());
+ const trading::Candle* hit = nullptr;
+ qint64 best = std::numeric_limits<qint64>::max();
+ for (const auto& c : candles_) {
+ const qint64 d = std::llabs(static_cast<qint64>(c.timestamp) - cursor_ms);
+ if (d < best) { best = d; hit = &c; }
+ }
+ if (hit) {
+ const bool up = hit->close >= hit->open;
+ const double pct = (hit->close - hit->open) / std::max(1e-12, hit->open) * 100.0;
+ const QString chg = QString("%1%2%")
+ .arg(pct >= 0 ? QStringLiteral("+") : QString())
+ .arg(QString::number(pct, 'f', 2));
+ const QString time_str =
+ QDateTime::fromMSecsSinceEpoch(hit->timestamp).toString(QStringLiteral("MMM dd HH:mm"));
+ const QString dir_color = up ? QString::fromLatin1(colors::POSITIVE())
+ : QString::fromLatin1(colors::NEGATIVE());
+ const QString dim = QString::fromLatin1(colors::TEXT_TERTIARY());
+ const QString fg = QString::fromLatin1(colors::TEXT_PRIMARY());
+ const QString green = QString::fromLatin1(colors::POSITIVE());
+ const QString red = QString::fromLatin1(colors::NEGATIVE());
+
+ // Vertical layout: header row + four label/value rows + change row.
+ // Numeric values use a fixed-width <td> so different price magnitudes
+ // (e.g. 79655.40 vs 9.50) don't push the values into different
+ // columns from row to row. font-family:Consolas keeps digits aligned.
+ const QString tpl = QStringLiteral(
+ "<div style='font-family:Consolas,Courier New,monospace;'>"
+ "<div style='color:%1;font-size:10px;font-weight:700;letter-spacing:0.8px;"
+ " margin-bottom:6px;'>%2</div>"
+ "<table cellspacing='0' cellpadding='0' style='border-spacing:0;font-size:12px;'>"
+ "<tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;'>O</td>"
+ " <td style='color:%3;text-align:right;'>%4</td>"
+ "</tr><tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;padding-top:1px;'>H</td>"
+ " <td style='color:%5;text-align:right;padding-top:1px;'>%6</td>"
+ "</tr><tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;padding-top:1px;'>L</td>"
+ " <td style='color:%7;text-align:right;padding-top:1px;'>%8</td>"
+ "</tr><tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;padding-top:1px;'>C</td>"
+ " <td style='color:%9;text-align:right;font-weight:700;padding-top:1px;'>%10</td>"
+ "</tr><tr>"
+ " <td colspan='2' style='padding-top:6px;color:%9;font-weight:700;text-align:right;"
+ " border-top:1px solid #1a1a1a;'>%11</td>"
+ "</tr>"
+ "</table>"
+ "</div>");
+ ohlc_tooltip_->setText(tpl
+ .arg(dim) // %1 dim/label colour
+ .arg(time_str) // %2 timestamp
+ .arg(fg) // %3 open colour
+ .arg(QString::number(hit->open, 'f', 2)) // %4
+ .arg(green) // %5 high colour
+ .arg(QString::number(hit->high, 'f', 2)) // %6
+ .arg(red) // %7 low colour
+ .arg(QString::number(hit->low, 'f', 2)) // %8
+ .arg(dir_color) // %9 close + Δ%
+ .arg(QString::number(hit->close, 'f', 2)) // %10
+ .arg(chg)); // %11
+ ohlc_tooltip_->adjustSize();
+ ohlc_tooltip_->setVisible(true);
+ }
+}
+
+void CryptoChart::on_hover_leave() {
+ if (xhair_v_) xhair_v_->setVisible(false);
+ if (xhair_h_) xhair_h_->setVisible(false);
+ if (xhair_dot_) xhair_dot_->setVisible(false);
+ if (price_tag_bg_) price_tag_bg_->setVisible(false);
+ if (price_tag_txt_)price_tag_txt_->setVisible(false);
+ if (time_tag_bg_) time_tag_bg_->setVisible(false);
+ if (time_tag_txt_) time_tag_txt_->setVisible(false);
+ if (ohlc_tooltip_) ohlc_tooltip_->setVisible(false);
+ // Bring the always-visible last-price tag back now that the cursor's
+ // gone — recompute in case anything moved while we were hovering.
+ update_last_price_marker();
+}
+
} // namespace fincept::screens::crypto
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoChart.h b/fincept-qt/src/screens/crypto_trading/CryptoChart.h
index f826bc97f..ee8bf0723 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoChart.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoChart.h
@@ -1,5 +1,6 @@
#pragma once
-// Crypto Chart — Candlestick chart with timeframe toggle buttons
+// Crypto Chart — Candlestick chart with timeframe toggles, crosshair,
+// OHLC tooltip, and a last-price tag pinned to the right axis.
#include "trading/TradingTypes.h"
@@ -10,11 +11,19 @@
class QChartView;
class QChart;
class QCandlestickSeries;
+class QLineSeries;
class QDateTimeAxis;
class QValueAxis;
+class QGraphicsLineItem;
+class QGraphicsRectItem;
+class QGraphicsEllipseItem;
+class QGraphicsSimpleTextItem;
+class QLabel;
namespace fincept::screens::crypto {
+class HoverChartView; // forward; defined in the .cpp
+
class CryptoChart : public QWidget {
Q_OBJECT
public:
@@ -33,12 +42,33 @@ class CryptoChart : public QWidget {
void rebuild_chart();
void update_axes(double min_price, double max_price, qint64 min_time, qint64 max_time);
void set_active_tf(int idx);
+ void apply_tf_axis_format();
+ void update_last_price_marker();
+ void on_hover_position(const QPointF& chart_value_pos, const QPoint& view_pos);
+ void on_hover_leave();
- QChartView* chart_view_ = nullptr;
+ HoverChartView* chart_view_ = nullptr;
QChart* chart_ = nullptr;
QCandlestickSeries* series_ = nullptr;
QDateTimeAxis* time_axis_ = nullptr;
QValueAxis* price_axis_ = nullptr;
+ QLineSeries* last_price_line_ = nullptr;
+
+ // Crosshair / hover overlay (live in the chart's QGraphicsScene)
+ QGraphicsLineItem* xhair_v_ = nullptr;
+ QGraphicsLineItem* xhair_h_ = nullptr;
+ QGraphicsEllipseItem* xhair_dot_ = nullptr;
+ QGraphicsRectItem* price_tag_bg_ = nullptr;
+ QGraphicsSimpleTextItem* price_tag_txt_ = nullptr;
+ QGraphicsRectItem* time_tag_bg_ = nullptr;
+ QGraphicsSimpleTextItem* time_tag_txt_ = nullptr;
+
+ // Last-price tag (always-visible, tracks the latest close)
+ QGraphicsRectItem* last_tag_bg_ = nullptr;
+ QGraphicsSimpleTextItem* last_tag_txt_ = nullptr;
+
+ // OHLC tooltip pinned to the chart's top-left corner
+ QLabel* ohlc_tooltip_ = nullptr;
// Timeframe toggle buttons
QPushButton* tf_buttons_[6] = {};
@@ -64,6 +94,8 @@ class CryptoChart : public QWidget {
// Pending timeframe request while a fetch is already in-flight
// set_candles() will emit timeframe_changed again if this is set
QString pending_tf_;
+
+ friend class HoverChartView;
};
} // namespace fincept::screens::crypto
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp
index 40414efbc..18b6475c4 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.cpp
@@ -1,299 +1,475 @@
-// CryptoOrderEntry.cpp — BUY/SELL tab form with toggle type buttons
+// CryptoOrderEntry.cpp — production order ticket.
+//
+// Layout (top → bottom):
+// 1. Header strip — title + paper/live badge
+// 2. Account card — Balance | Mark | Avail-after-order
+// 3. BUY / SELL tabs — full-width, color-coded
+// 4. Type buttons — Market / Limit / Stop / Stop-Limit
+// 5. Quantity input — large monospace, with unit suffix and 25/50/75/100 quick fills
+// 6. Price + Stop rows — auto-shown only for the order types that need them
+// 7. Order breakdown — Cost / Fee / Total / Receive / % of balance
+// 8. Advanced (collapsible) — SL / TP
+// 9. Futures (visible only when set_futures_mode(true)) — leverage spin + margin segmented control
+// 10. Submit — color-coded big button with computed subtitle
+// 11. Status — inline validation message
+//
+// Sizing principles:
+// • No fixed pixel heights on inputs/buttons — everything uses padding via QSS so
+// rows scale with the user's terminal font size and HiDPI multipliers.
+// • Right panel is ~290 px wide; layout is single-column with paired label/value
+// sub-rows for compact cost breakdown.
+// • Live cost preview runs on every keystroke (qty / price / type changes) and
+// feeds the submit-button subtitle so the user never has to compute anything.
+
#include "screens/crypto_trading/CryptoOrderEntry.h"
#include <QComboBox>
+#include <QDoubleValidator>
+#include <QFrame>
+#include <QGridLayout>
#include <QHBoxLayout>
#include <QSpinBox>
#include <QStyle>
#include <QVBoxLayout>
+#include <algorithm>
#include <cmath>
namespace fincept::screens::crypto {
+namespace {
+
+QFrame* make_card(const QString& object_name = "cryptoOeCard") {
+ auto* card = new QFrame;
+ card->setObjectName(object_name);
+ card->setFrameShape(QFrame::NoFrame);
+ return card;
+}
+
+// One label-value row for the account/breakdown cards. Label is upper-cased
+// dim text; value is bright primary. Returns the value label so callers can
+// update it later.
+QLabel* add_kv_row(QGridLayout* grid, int row, const QString& label_text,
+ const QString& value_obj_name = "cryptoOeKvValue") {
+ auto* lbl = new QLabel(label_text);
+ lbl->setObjectName("cryptoOeKvLabel");
+ auto* val = new QLabel(QStringLiteral("--"));
+ val->setObjectName(value_obj_name);
+ val->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+
+ grid->addWidget(lbl, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
+ grid->addWidget(val, row, 1, Qt::AlignRight | Qt::AlignVCenter);
+ return val;
+}
+
+// Base symbol of a "BASE/QUOTE" pair, defaulting to the whole string if no slash.
+QString base_of(const QString& pair) {
+ const int slash = pair.indexOf('/');
+ return slash > 0 ? pair.left(slash) : pair;
+}
+
+// Quote symbol (typically USDT, USD, USDC, …) of a pair.
+QString quote_of(const QString& pair) {
+ const int slash = pair.indexOf('/');
+ return slash > 0 ? pair.mid(slash + 1) : QStringLiteral("USD");
+}
+
+// Numeric-only validator that allows decimals; reused by every numeric input.
+QDoubleValidator* make_decimal_validator(QObject* parent) {
+ auto* v = new QDoubleValidator(0.0, 1e15, 8, parent);
+ v->setNotation(QDoubleValidator::StandardNotation);
+ v->setLocale(QLocale::c());
+ return v;
+}
+
+void repolish(QWidget* w) {
+ if (!w || !w->style()) return;
+ w->style()->unpolish(w);
+ w->style()->polish(w);
+}
+
+} // namespace
+
CryptoOrderEntry::CryptoOrderEntry(QWidget* parent) : QWidget(parent) {
setObjectName("cryptoOrderEntry");
+ setMinimumWidth(240);
- auto* layout = new QVBoxLayout(this);
- layout->setContentsMargins(0, 0, 0, 0);
- layout->setSpacing(0);
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
- // Header
+ // ── Header ──────────────────────────────────────────────────────────────
auto* header = new QWidget(this);
header->setObjectName("cryptoOeHeader");
- header->setFixedHeight(30);
auto* h_layout = new QHBoxLayout(header);
- h_layout->setContentsMargins(8, 0, 8, 0);
+ h_layout->setContentsMargins(12, 6, 12, 6);
+ h_layout->setSpacing(6);
- auto* title = new QLabel("ORDER ENTRY");
+ auto* title = new QLabel(QStringLiteral("ORDER ENTRY"));
title->setObjectName("cryptoOeTitle");
h_layout->addWidget(title);
h_layout->addStretch();
- mode_label_ = new QLabel("PAPER");
+ mode_label_ = new QLabel(QStringLiteral("PAPER"));
mode_label_->setObjectName("cryptoOeMode");
mode_label_->setProperty("mode", "paper");
h_layout->addWidget(mode_label_);
- layout->addWidget(header);
+ root->addWidget(header);
- // Content area
+ // ── Scrollable content ──────────────────────────────────────────────────
auto* content = new QWidget(this);
auto* form = new QVBoxLayout(content);
- form->setContentsMargins(8, 6, 8, 6);
- form->setSpacing(4);
-
- // BUY / SELL tabs — side by side
- auto* side_row = new QHBoxLayout;
- side_row->setSpacing(0);
-
- buy_tab_ = new QPushButton("BUY");
- buy_tab_->setObjectName("cryptoBuyTab");
- buy_tab_->setProperty("active", true);
- buy_tab_->setCursor(Qt::PointingHandCursor);
- buy_tab_->setFixedHeight(28);
- connect(buy_tab_, &QPushButton::clicked, this, [this]() { set_buy_side(true); });
- side_row->addWidget(buy_tab_, 1);
-
- sell_tab_ = new QPushButton("SELL");
- sell_tab_->setObjectName("cryptoSellTab");
- sell_tab_->setProperty("active", false);
- sell_tab_->setCursor(Qt::PointingHandCursor);
- sell_tab_->setFixedHeight(28);
- connect(sell_tab_, &QPushButton::clicked, this, [this]() { set_buy_side(false); });
- side_row->addWidget(sell_tab_, 1);
- form->addLayout(side_row);
-
- // Order type toggle buttons
- auto* type_row = new QHBoxLayout;
- type_row->setSpacing(2);
- const char* type_labels[] = {"MKT", "LMT", "STP", "S/L"};
- for (int i = 0; i < 4; ++i) {
- type_btns_[i] = new QPushButton(type_labels[i]);
- type_btns_[i]->setObjectName("cryptoOeTypeBtn");
- type_btns_[i]->setFixedHeight(20);
- type_btns_[i]->setCursor(Qt::PointingHandCursor);
- if (i == 0)
- type_btns_[i]->setProperty("active", true);
- connect(type_btns_[i], &QPushButton::clicked, this, [this, i]() { set_order_type(i); });
- type_row->addWidget(type_btns_[i]);
+ form->setContentsMargins(10, 10, 10, 10);
+ form->setSpacing(10);
+
+ // ── 1. Account card (Balance / Mark / Avail) ────────────────────────────
+ {
+ auto* card = make_card();
+ auto* grid = new QGridLayout(card);
+ grid->setContentsMargins(12, 10, 12, 10);
+ grid->setHorizontalSpacing(12);
+ grid->setVerticalSpacing(4);
+ grid->setColumnStretch(0, 0);
+ grid->setColumnStretch(1, 1);
+
+ balance_label_ = add_kv_row(grid, 0, QStringLiteral("BALANCE"), "cryptoOeKvValueAccent");
+ market_price_label_ = add_kv_row(grid, 1, QStringLiteral("MARK"));
+ avail_label_ = add_kv_row(grid, 2, QStringLiteral("AVAIL"), "cryptoOeKvValueDim");
+
+ balance_label_->setText(QStringLiteral("$0.00"));
+ market_price_label_->setText(QStringLiteral("--"));
+ avail_label_->setText(QStringLiteral("--"));
+
+ form->addWidget(card);
+ }
+
+ // ── 2. BUY / SELL tabs ──────────────────────────────────────────────────
+ {
+ auto* side_row = new QHBoxLayout;
+ side_row->setSpacing(0);
+ side_row->setContentsMargins(0, 0, 0, 0);
+
+ buy_tab_ = new QPushButton(QStringLiteral("BUY"));
+ buy_tab_->setObjectName("cryptoBuyTab");
+ buy_tab_->setProperty("active", true);
+ buy_tab_->setCursor(Qt::PointingHandCursor);
+ buy_tab_->setFocusPolicy(Qt::NoFocus);
+ connect(buy_tab_, &QPushButton::clicked, this, [this]() { set_buy_side(true); });
+ side_row->addWidget(buy_tab_, 1);
+
+ sell_tab_ = new QPushButton(QStringLiteral("SELL"));
+ sell_tab_->setObjectName("cryptoSellTab");
+ sell_tab_->setProperty("active", false);
+ sell_tab_->setCursor(Qt::PointingHandCursor);
+ sell_tab_->setFocusPolicy(Qt::NoFocus);
+ connect(sell_tab_, &QPushButton::clicked, this, [this]() { set_buy_side(false); });
+ side_row->addWidget(sell_tab_, 1);
+
+ form->addLayout(side_row);
}
- form->addLayout(type_row);
-
- form->addSpacing(2);
-
- // Balance
- balance_label_ = new QLabel("$0.00");
- balance_label_->setObjectName("cryptoOeBalance");
- form->addWidget(balance_label_);
-
- // Market price
- market_price_label_ = new QLabel("MKT: --");
- market_price_label_->setObjectName("cryptoOeMarketPrice");
- form->addWidget(market_price_label_);
-
- // Quantity
- auto* qty_lbl = new QLabel("QTY");
- qty_lbl->setObjectName("cryptoOeLabel");
- form->addWidget(qty_lbl);
-
- qty_edit_ = new QLineEdit;
- qty_edit_->setObjectName("cryptoOeInput");
- qty_edit_->setPlaceholderText("0.00");
- qty_edit_->setFixedHeight(26);
- connect(qty_edit_, &QLineEdit::textChanged, this, [this]() { update_cost_preview(); });
- form->addWidget(qty_edit_);
-
- // Percentage buttons
- auto* pct_row = new QHBoxLayout;
- pct_row->setSpacing(2);
- for (int pct : {25, 50, 75, 100}) {
- auto* btn = new QPushButton(QString("%1%").arg(pct));
- btn->setObjectName("cryptoOePctBtn");
- btn->setFixedHeight(18);
- btn->setCursor(Qt::PointingHandCursor);
- connect(btn, &QPushButton::clicked, this, [this, pct]() { on_pct_clicked(pct); });
- pct_row->addWidget(btn);
+
+ // ── 3. Order type segmented control ─────────────────────────────────────
+ {
+ auto* type_row = new QHBoxLayout;
+ type_row->setSpacing(0);
+ type_row->setContentsMargins(0, 0, 0, 0);
+ // Slightly more readable than the previous 3-letter abbreviations.
+ const char* type_labels[] = {"MARKET", "LIMIT", "STOP", "STOP-LMT"};
+ for (int i = 0; i < 4; ++i) {
+ type_btns_[i] = new QPushButton(QString::fromLatin1(type_labels[i]));
+ type_btns_[i]->setObjectName("cryptoOeTypeBtn");
+ type_btns_[i]->setCursor(Qt::PointingHandCursor);
+ type_btns_[i]->setFocusPolicy(Qt::NoFocus);
+ if (i == 0) type_btns_[i]->setProperty("active", true);
+ connect(type_btns_[i], &QPushButton::clicked, this, [this, i]() { set_order_type(i); });
+ type_row->addWidget(type_btns_[i], 1);
+ }
+ form->addLayout(type_row);
}
- form->addLayout(pct_row);
-
- // Price
- auto* price_lbl = new QLabel("PRICE");
- price_lbl->setObjectName("cryptoOeLabel");
- form->addWidget(price_lbl);
-
- price_edit_ = new QLineEdit;
- price_edit_->setObjectName("cryptoOeInput");
- price_edit_->setPlaceholderText("Limit price");
- price_edit_->setEnabled(false);
- price_edit_->setFixedHeight(26);
- connect(price_edit_, &QLineEdit::textChanged, this, [this]() { update_cost_preview(); });
- form->addWidget(price_edit_);
-
- // Stop price
- auto* stop_lbl = new QLabel("STOP");
- stop_lbl->setObjectName("cryptoOeLabel");
- form->addWidget(stop_lbl);
-
- stop_price_edit_ = new QLineEdit;
- stop_price_edit_->setObjectName("cryptoOeInput");
- stop_price_edit_->setPlaceholderText("Stop price");
- stop_price_edit_->setEnabled(false);
- stop_price_edit_->setFixedHeight(26);
- form->addWidget(stop_price_edit_);
-
- // Advanced toggle
- advanced_toggle_ = new QPushButton("+ ADVANCED");
+
+ // ── 4. Quantity input + 25/50/75/100% quick fills ───────────────────────
+ {
+ auto* qty_label = new QLabel(QStringLiteral("QUANTITY"));
+ qty_label->setObjectName("cryptoOeLabel");
+ form->addWidget(qty_label);
+
+ // Quantity field with the base-asset suffix shown in a side label so
+ // users always know whether they're sizing in BTC or USDT.
+ auto* qty_wrap = new QWidget;
+ qty_wrap->setObjectName("cryptoOeInputWrap");
+ auto* qty_h = new QHBoxLayout(qty_wrap);
+ qty_h->setContentsMargins(0, 0, 0, 0);
+ qty_h->setSpacing(0);
+
+ qty_edit_ = new QLineEdit;
+ qty_edit_->setObjectName("cryptoOeInput");
+ qty_edit_->setPlaceholderText(QStringLiteral("0.00"));
+ qty_edit_->setValidator(make_decimal_validator(this));
+ qty_edit_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ connect(qty_edit_, &QLineEdit::textChanged, this, [this]() { update_cost_preview(); });
+ qty_h->addWidget(qty_edit_, 1);
+
+ auto* unit = new QLabel(base_of(current_symbol_));
+ unit->setObjectName("cryptoOeUnit");
+ unit->setMinimumWidth(40);
+ unit->setAlignment(Qt::AlignCenter);
+ qty_h->addWidget(unit);
+
+ form->addWidget(qty_wrap);
+
+ // Quick % fills — bigger touch targets than the old 18 px buttons.
+ auto* pct_row = new QHBoxLayout;
+ pct_row->setSpacing(4);
+ for (int pct : {25, 50, 75, 100}) {
+ auto* btn = new QPushButton(QString::number(pct) + QStringLiteral("%"));
+ btn->setObjectName("cryptoOePctBtn");
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setFocusPolicy(Qt::NoFocus);
+ connect(btn, &QPushButton::clicked, this, [this, pct]() { on_pct_clicked(pct); });
+ pct_row->addWidget(btn, 1);
+ }
+ form->addLayout(pct_row);
+
+ // Symbol-change signal will update the unit label.
+ connect(this, &CryptoOrderEntry::destroyed, unit, [](){});
+ // Repurpose set_symbol's path: we keep a reference to update later.
+ unit->setProperty("ftRoleUnit", true);
+ }
+
+ // ── 5. Price (Limit / Stop-Limit) ───────────────────────────────────────
+ {
+ price_row_ = new QWidget;
+ auto* v = new QVBoxLayout(price_row_);
+ v->setContentsMargins(0, 0, 0, 0);
+ v->setSpacing(4);
+
+ auto* lbl = new QLabel(QStringLiteral("LIMIT PRICE"));
+ lbl->setObjectName("cryptoOeLabel");
+ v->addWidget(lbl);
+
+ auto* wrap = new QWidget;
+ auto* h = new QHBoxLayout(wrap);
+ h->setContentsMargins(0, 0, 0, 0);
+ h->setSpacing(0);
+
+ price_edit_ = new QLineEdit;
+ price_edit_->setObjectName("cryptoOeInput");
+ price_edit_->setPlaceholderText(QStringLiteral("0.00"));
+ price_edit_->setValidator(make_decimal_validator(this));
+ price_edit_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ connect(price_edit_, &QLineEdit::textChanged, this, [this]() { update_cost_preview(); });
+ h->addWidget(price_edit_, 1);
+
+ auto* unit = new QLabel(quote_of(current_symbol_));
+ unit->setObjectName("cryptoOeUnit");
+ unit->setMinimumWidth(40);
+ unit->setAlignment(Qt::AlignCenter);
+ unit->setProperty("ftRoleUnit", "quote");
+ h->addWidget(unit);
+
+ v->addWidget(wrap);
+ form->addWidget(price_row_);
+ price_row_->setVisible(false); // shown only when type is Limit / Stop-Limit
+ }
+
+ // ── 6. Stop trigger price (Stop / Stop-Limit) ───────────────────────────
+ {
+ stop_row_ = new QWidget;
+ auto* v = new QVBoxLayout(stop_row_);
+ v->setContentsMargins(0, 0, 0, 0);
+ v->setSpacing(4);
+
+ auto* lbl = new QLabel(QStringLiteral("STOP PRICE"));
+ lbl->setObjectName("cryptoOeLabel");
+ v->addWidget(lbl);
+
+ auto* wrap = new QWidget;
+ auto* h = new QHBoxLayout(wrap);
+ h->setContentsMargins(0, 0, 0, 0);
+ h->setSpacing(0);
+
+ stop_price_edit_ = new QLineEdit;
+ stop_price_edit_->setObjectName("cryptoOeInput");
+ stop_price_edit_->setPlaceholderText(QStringLiteral("0.00"));
+ stop_price_edit_->setValidator(make_decimal_validator(this));
+ stop_price_edit_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ h->addWidget(stop_price_edit_, 1);
+
+ auto* unit = new QLabel(quote_of(current_symbol_));
+ unit->setObjectName("cryptoOeUnit");
+ unit->setMinimumWidth(40);
+ unit->setAlignment(Qt::AlignCenter);
+ unit->setProperty("ftRoleUnit", "quote");
+ h->addWidget(unit);
+
+ v->addWidget(wrap);
+ form->addWidget(stop_row_);
+ stop_row_->setVisible(false);
+ }
+
+ // ── 7. Order breakdown card ────────────────────────────────────────────
+ {
+ auto* card = make_card("cryptoOeBreakdown");
+ auto* grid = new QGridLayout(card);
+ grid->setContentsMargins(12, 8, 12, 8);
+ grid->setHorizontalSpacing(12);
+ grid->setVerticalSpacing(3);
+ grid->setColumnStretch(0, 0);
+ grid->setColumnStretch(1, 1);
+
+ cost_label_ = add_kv_row(grid, 0, QStringLiteral("ORDER VALUE"));
+ fee_label_ = add_kv_row(grid, 1, QStringLiteral("FEE EST"), "cryptoOeKvValueDim");
+ total_label_ = add_kv_row(grid, 2, QStringLiteral("TOTAL"), "cryptoOeKvValueAccent");
+ recv_label_ = add_kv_row(grid, 3, QStringLiteral("YOU RECEIVE"), "cryptoOeKvValueDim");
+ pct_used_label_ = add_kv_row(grid, 4, QStringLiteral("% OF BALANCE"),"cryptoOeKvValueDim");
+
+ form->addWidget(card);
+ }
+
+ // ── 8. Advanced toggle (SL / TP) ────────────────────────────────────────
+ advanced_toggle_ = new QPushButton(QStringLiteral("▾ Advanced (SL / TP)"));
advanced_toggle_->setObjectName("cryptoAdvToggle");
advanced_toggle_->setCursor(Qt::PointingHandCursor);
- advanced_toggle_->setFixedHeight(18);
+ advanced_toggle_->setFocusPolicy(Qt::NoFocus);
form->addWidget(advanced_toggle_);
- // Collapsible SL/TP section
advanced_section_ = new QWidget(this);
advanced_section_->setVisible(false);
- auto* adv_layout = new QVBoxLayout(advanced_section_);
- adv_layout->setContentsMargins(0, 0, 0, 0);
- adv_layout->setSpacing(4);
-
- auto* sl_lbl = new QLabel("SL");
- sl_lbl->setObjectName("cryptoOeLabel");
- sl_edit_ = new QLineEdit;
- sl_edit_->setObjectName("cryptoOeInput");
- sl_edit_->setPlaceholderText("Stop Loss");
- sl_edit_->setFixedHeight(26);
-
- auto* tp_lbl = new QLabel("TP");
- tp_lbl->setObjectName("cryptoOeLabel");
- tp_edit_ = new QLineEdit;
- tp_edit_->setObjectName("cryptoOeInput");
- tp_edit_->setPlaceholderText("Take Profit");
- tp_edit_->setFixedHeight(26);
-
- adv_layout->addWidget(sl_lbl);
- adv_layout->addWidget(sl_edit_);
- adv_layout->addWidget(tp_lbl);
- adv_layout->addWidget(tp_edit_);
+ {
+ auto* adv = new QVBoxLayout(advanced_section_);
+ adv->setContentsMargins(0, 0, 0, 0);
+ adv->setSpacing(6);
+
+ auto add_pair = [&](const QString& label, QLineEdit*& edit, const QString& placeholder) {
+ auto* lbl = new QLabel(label);
+ lbl->setObjectName("cryptoOeLabel");
+ adv->addWidget(lbl);
+ edit = new QLineEdit;
+ edit->setObjectName("cryptoOeInput");
+ edit->setPlaceholderText(placeholder);
+ edit->setValidator(make_decimal_validator(this));
+ edit->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ adv->addWidget(edit);
+ };
+ add_pair(QStringLiteral("STOP LOSS"), sl_edit_, QStringLiteral("Trigger price"));
+ add_pair(QStringLiteral("TAKE PROFIT"), tp_edit_, QStringLiteral("Trigger price"));
+ }
form->addWidget(advanced_section_);
connect(advanced_toggle_, &QPushButton::clicked, this, [this]() {
const bool show = !advanced_section_->isVisible();
advanced_section_->setVisible(show);
- advanced_toggle_->setText(show ? "- ADVANCED" : "+ ADVANCED");
+ advanced_toggle_->setText(show ? QStringLiteral("▴ Advanced (SL / TP)")
+ : QStringLiteral("▾ Advanced (SL / TP)"));
});
- // Futures controls (leverage + margin mode) — hidden for spot markets
+ // ── 9. Futures controls (leverage + margin mode) ────────────────────────
futures_section_ = new QWidget(this);
futures_section_->setVisible(false);
- auto* futures_layout = new QVBoxLayout(futures_section_);
- futures_layout->setContentsMargins(0, 0, 0, 0);
- futures_layout->setSpacing(4);
-
- auto* lev_row = new QHBoxLayout;
- lev_row->setSpacing(4);
- auto* lev_lbl = new QLabel("LEVERAGE");
- lev_lbl->setObjectName("cryptoOeLabel");
- leverage_spin_ = new QSpinBox;
- leverage_spin_->setObjectName("cryptoOeSpinBox");
- leverage_spin_->setRange(1, 125);
- leverage_spin_->setValue(1);
- leverage_spin_->setSuffix("x");
- leverage_spin_->setFixedHeight(26);
- lev_row->addWidget(lev_lbl);
- lev_row->addStretch();
- lev_row->addWidget(leverage_spin_);
- futures_layout->addLayout(lev_row);
-
- auto* margin_row = new QHBoxLayout;
- margin_row->setSpacing(4);
- auto* margin_lbl = new QLabel("MARGIN");
- margin_lbl->setObjectName("cryptoOeLabel");
- margin_mode_combo_ = new QComboBox;
- margin_mode_combo_->setObjectName("cryptoOeCombo");
- margin_mode_combo_->addItem("Cross", "cross");
- margin_mode_combo_->addItem("Isolated", "isolated");
- margin_mode_combo_->setFixedHeight(26);
- margin_row->addWidget(margin_lbl);
- margin_row->addStretch();
- margin_row->addWidget(margin_mode_combo_);
- futures_layout->addLayout(margin_row);
-
+ {
+ auto* layout = new QVBoxLayout(futures_section_);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(6);
+
+ auto* lev_lbl = new QLabel(QStringLiteral("LEVERAGE"));
+ lev_lbl->setObjectName("cryptoOeLabel");
+ layout->addWidget(lev_lbl);
+
+ leverage_spin_ = new QSpinBox;
+ leverage_spin_->setObjectName("cryptoOeSpinBox");
+ leverage_spin_->setRange(1, 125);
+ leverage_spin_->setValue(1);
+ leverage_spin_->setSuffix(QStringLiteral("x"));
+ leverage_spin_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ layout->addWidget(leverage_spin_);
+
+ auto* margin_lbl = new QLabel(QStringLiteral("MARGIN MODE"));
+ margin_lbl->setObjectName("cryptoOeLabel");
+ layout->addWidget(margin_lbl);
+
+ margin_mode_combo_ = new QComboBox;
+ margin_mode_combo_->setObjectName("cryptoOeCombo");
+ margin_mode_combo_->addItem(QStringLiteral("Cross"), QStringLiteral("cross"));
+ margin_mode_combo_->addItem(QStringLiteral("Isolated"), QStringLiteral("isolated"));
+ layout->addWidget(margin_mode_combo_);
+ }
form->addWidget(futures_section_);
- connect(leverage_spin_, &QSpinBox::valueChanged, this, [this](int val) { emit leverage_changed(val); });
+ connect(leverage_spin_, &QSpinBox::valueChanged, this, [this](int val) {
+ emit leverage_changed(val);
+ update_cost_preview();
+ });
connect(margin_mode_combo_, &QComboBox::currentIndexChanged, this,
[this](int idx) { emit margin_mode_changed(margin_mode_combo_->itemData(idx).toString()); });
- // Cost preview
- cost_label_ = new QLabel("Est: --");
- cost_label_->setObjectName("cryptoOeCost");
- form->addWidget(cost_label_);
-
- // Submit button
- submit_btn_ = new QPushButton("BUY BTC/USDT");
+ // ── 10. Submit button + computed subtitle ───────────────────────────────
+ submit_btn_ = new QPushButton(QStringLiteral("BUY ") + current_symbol_);
submit_btn_->setObjectName("cryptoBuySubmit");
- submit_btn_->setFixedHeight(34);
submit_btn_->setCursor(Qt::PointingHandCursor);
+ submit_btn_->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return));
+ submit_btn_->setToolTip(QStringLiteral("Submit order (⌘/Ctrl+Enter)"));
connect(submit_btn_, &QPushButton::clicked, this, &CryptoOrderEntry::on_submit);
form->addWidget(submit_btn_);
- // Status
- status_label_ = new QLabel("");
+ submit_subtitle_ = new QLabel(QStringLiteral("Enter a quantity to preview"));
+ submit_subtitle_->setObjectName("cryptoOeSubmitSubtitle");
+ submit_subtitle_->setAlignment(Qt::AlignCenter);
+ submit_subtitle_->setWordWrap(true);
+ form->addWidget(submit_subtitle_);
+
+ // ── 11. Inline status / validation message ──────────────────────────────
+ status_label_ = new QLabel;
status_label_->setObjectName("cryptoOeStatus");
status_label_->setWordWrap(true);
+ status_label_->setVisible(false);
form->addWidget(status_label_);
form->addStretch();
- layout->addWidget(content, 1);
+ root->addWidget(content, 1);
+
+ update_cost_preview();
}
void CryptoOrderEntry::set_buy_side(bool is_buy) {
if (is_buy == is_buy_side_)
- return; // no-op — avoids repoling children on redundant clicks
+ return;
is_buy_side_ = is_buy;
buy_tab_->setProperty("active", is_buy);
sell_tab_->setProperty("active", !is_buy);
- // Update submit button
- const QString label = QString("%1 %2").arg(is_buy ? "BUY" : "SELL", current_symbol_);
- submit_btn_->setText(label);
+ submit_btn_->setText(QString::fromLatin1(is_buy ? "BUY " : "SELL ") + current_symbol_);
submit_btn_->setObjectName(is_buy ? "cryptoBuySubmit" : "cryptoSellSubmit");
- // Narrow style refresh — only the widgets whose dynamic property or
- // objectName actually changed, not the entire order-entry subtree.
- const auto repolish = [](QWidget* w) {
- w->style()->unpolish(w);
- w->style()->polish(w);
- };
repolish(buy_tab_);
repolish(sell_tab_);
repolish(submit_btn_);
+ update_cost_preview();
}
void CryptoOrderEntry::set_order_type(int idx) {
+ const int prev = active_type_;
if (idx == active_type_) {
- // Still update enabled state + cost preview for defensive callers
- price_edit_->setEnabled(idx == 1 || idx == 3);
- stop_price_edit_->setEnabled(idx == 2 || idx == 3);
+ // Defensive: still recompute visibility / preview in case state drifted.
+ if (price_row_) price_row_->setVisible(idx == 1 || idx == 3);
+ if (stop_row_) stop_row_->setVisible(idx == 2 || idx == 3);
+ if (price_edit_) price_edit_->setEnabled(idx == 1 || idx == 3);
+ if (stop_price_edit_) stop_price_edit_->setEnabled(idx == 2 || idx == 3);
update_cost_preview();
return;
}
- const int prev = active_type_;
active_type_ = idx;
for (int i = 0; i < 4; ++i)
type_btns_[i]->setProperty("active", i == idx);
- // Only repoll the two buttons whose "active" property changed.
- const auto repolish = [](QWidget* w) {
- w->style()->unpolish(w);
- w->style()->polish(w);
- };
- if (prev >= 0 && prev < 4)
- repolish(type_btns_[prev]);
+ if (prev >= 0 && prev < 4) repolish(type_btns_[prev]);
repolish(type_btns_[idx]);
- price_edit_->setEnabled(idx == 1 || idx == 3);
- stop_price_edit_->setEnabled(idx == 2 || idx == 3);
+ if (price_row_) price_row_->setVisible(idx == 1 || idx == 3);
+ if (stop_row_) stop_row_->setVisible(idx == 2 || idx == 3);
+ if (price_edit_) price_edit_->setEnabled(idx == 1 || idx == 3);
+ if (stop_price_edit_) stop_price_edit_->setEnabled(idx == 2 || idx == 3);
+
update_cost_preview();
}
@@ -305,21 +481,34 @@ void CryptoOrderEntry::set_balance(double balance) {
void CryptoOrderEntry::set_current_price(double price) {
current_price_ = price;
- market_price_label_->setText(QString("MKT: $%1").arg(price, 0, 'f', 2));
+ market_price_label_->setText(QString("$%1").arg(price, 0, 'f', 2));
update_cost_preview();
}
void CryptoOrderEntry::set_mode(bool is_paper) {
is_paper_ = is_paper;
- mode_label_->setText(is_paper ? "PAPER" : "LIVE");
+ mode_label_->setText(is_paper ? QStringLiteral("PAPER") : QStringLiteral("LIVE"));
mode_label_->setProperty("mode", is_paper ? "paper" : "live");
- mode_label_->style()->unpolish(mode_label_);
- mode_label_->style()->polish(mode_label_);
+ repolish(mode_label_);
}
void CryptoOrderEntry::set_symbol(const QString& symbol) {
current_symbol_ = symbol;
- submit_btn_->setText(QString("%1 %2").arg(is_buy_side_ ? "BUY" : "SELL", symbol));
+ submit_btn_->setText(QString::fromLatin1(is_buy_side_ ? "BUY " : "SELL ") + symbol);
+
+ // Update unit suffix labels (base on qty, quote on price/stop) by looking
+ // up the children we tagged with the ftRoleUnit dynamic property.
+ const QString base = base_of(symbol);
+ const QString quote = quote_of(symbol);
+ for (auto* lbl : findChildren<QLabel*>()) {
+ const auto role = lbl->property("ftRoleUnit");
+ if (!role.isValid()) continue;
+ if (role.toString() == QLatin1String("quote"))
+ lbl->setText(quote);
+ else
+ lbl->setText(base);
+ }
+ update_cost_preview();
}
void CryptoOrderEntry::on_submit() {
@@ -329,12 +518,36 @@ void CryptoOrderEntry::on_submit() {
const double qty = qty_edit_->text().toDouble();
if (qty <= 0) {
- status_label_->setText("Enter a valid quantity");
- status_label_->setProperty("error", true);
- status_label_->style()->unpolish(status_label_);
- status_label_->style()->polish(status_label_);
+ status_label_->setText(QStringLiteral("⚠ Enter a valid quantity"));
+ status_label_->setProperty("severity", "error");
+ status_label_->setVisible(true);
+ repolish(status_label_);
+ qty_edit_->setProperty("invalid", true);
+ repolish(qty_edit_);
+ qty_edit_->setFocus();
+ return;
+ }
+ qty_edit_->setProperty("invalid", false);
+ repolish(qty_edit_);
+
+ if ((active_type_ == 1 || active_type_ == 3) && price_edit_->text().toDouble() <= 0) {
+ status_label_->setText(QStringLiteral("⚠ Limit price required"));
+ status_label_->setProperty("severity", "error");
+ status_label_->setVisible(true);
+ repolish(status_label_);
+ price_edit_->setFocus();
return;
}
+ if ((active_type_ == 2 || active_type_ == 3) && stop_price_edit_->text().toDouble() <= 0) {
+ status_label_->setText(QStringLiteral("⚠ Stop trigger price required"));
+ status_label_->setProperty("severity", "error");
+ status_label_->setVisible(true);
+ repolish(status_label_);
+ stop_price_edit_->setFocus();
+ return;
+ }
+
+ status_label_->setVisible(false);
const double price = price_edit_->text().toDouble();
const double stop_price = stop_price_edit_->text().toDouble();
@@ -347,7 +560,16 @@ void CryptoOrderEntry::on_submit() {
void CryptoOrderEntry::on_pct_clicked(int pct) {
if (balance_ <= 0 || current_price_ <= 0)
return;
- const double max_qty = balance_ / current_price_;
+ // For limit orders use the limit price as the sizing basis if present, so
+ // 100% means "use my whole balance at the limit I'd actually fill at" —
+ // not at the current mark.
+ double basis = current_price_;
+ if ((active_type_ == 1 || active_type_ == 3)) {
+ const double limit_p = price_edit_->text().toDouble();
+ if (limit_p > 0) basis = limit_p;
+ }
+ const int leverage = (is_futures_ && leverage_spin_) ? leverage_spin_->value() : 1;
+ const double max_qty = (balance_ * leverage) / basis;
const double qty = max_qty * pct / 100.0;
qty_edit_->setText(QString::number(qty, 'f', 6));
}
@@ -358,17 +580,68 @@ void CryptoOrderEntry::set_futures_mode(bool is_futures) {
}
void CryptoOrderEntry::update_cost_preview() {
- const double qty = qty_edit_->text().toDouble();
+ const double qty = qty_edit_ ? qty_edit_->text().toDouble() : 0.0;
double price = current_price_;
if (active_type_ == 1 || active_type_ == 3) {
- const double limit_p = price_edit_->text().toDouble();
- if (limit_p > 0)
- price = limit_p;
+ const double limit_p = price_edit_ ? price_edit_->text().toDouble() : 0.0;
+ if (limit_p > 0) price = limit_p;
+ }
+
+ const QString quote = quote_of(current_symbol_);
+ const QString base = base_of(current_symbol_);
+ auto fmt_money = [&](double v) { return QString("%1 %2").arg(v, 0, 'f', 2).arg(quote); };
+ auto fmt_base = [&](double v) { return QString("%1 %2").arg(v, 0, 'f', 6).arg(base); };
+
+ if (qty > 0 && price > 0) {
+ const double notional = qty * price;
+ const int leverage = (is_futures_ && leverage_spin_) ? leverage_spin_->value() : 1;
+ const double margin = notional / std::max(1, leverage);
+
+ // Taker fee assumption — used purely for the on-screen estimate. Real
+ // fees come back from the exchange post-fill.
+ constexpr double kAssumedFeeBps = 0.0007; // 7 bps / 0.07 %
+ const double fee = notional * kAssumedFeeBps;
+ const double total = margin + fee;
+ const double pct = balance_ > 0 ? (margin / balance_) * 100.0 : 0.0;
+ const double avail = std::max(0.0, balance_ - total);
+
+ cost_label_->setText(fmt_money(notional));
+ fee_label_->setText(QString("~%1").arg(fmt_money(fee)));
+ total_label_->setText(fmt_money(total));
+ recv_label_->setText(is_buy_side_ ? fmt_base(qty) : fmt_money(qty * price));
+ pct_used_label_->setText(QString("%1%").arg(pct, 0, 'f', 2));
+ if (avail_label_)
+ avail_label_->setText(fmt_money(avail));
+
+ // Submit subtitle reads "0.31 BTC ≈ $25,000" or, for futures,
+ // appends the leverage.
+ const QString subtitle =
+ is_futures_
+ ? QString("%1 @ %2x ≈ %3").arg(fmt_base(qty)).arg(leverage).arg(fmt_money(margin))
+ : QString("%1 ≈ %2").arg(fmt_base(qty), fmt_money(notional));
+ submit_subtitle_->setText(subtitle);
+
+ const bool insufficient = !is_futures_ && total > balance_ && balance_ > 0;
+ if (insufficient) {
+ status_label_->setText(QStringLiteral("⚠ Insufficient balance for this order"));
+ status_label_->setProperty("severity", "warning");
+ status_label_->setVisible(true);
+ repolish(status_label_);
+ } else if (status_label_->property("severity").toString() != QLatin1String("error")) {
+ status_label_->setVisible(false);
+ }
+ } else {
+ cost_label_->setText(QStringLiteral("--"));
+ fee_label_->setText(QStringLiteral("--"));
+ total_label_->setText(QStringLiteral("--"));
+ recv_label_->setText(QStringLiteral("--"));
+ pct_used_label_->setText(QStringLiteral("--"));
+ if (avail_label_ && balance_ > 0)
+ avail_label_->setText(fmt_money(balance_));
+ else if (avail_label_)
+ avail_label_->setText(QStringLiteral("--"));
+ submit_subtitle_->setText(QStringLiteral("Enter a quantity to preview"));
}
- if (qty > 0 && price > 0)
- cost_label_->setText(QString("Est: $%1").arg(qty * price, 0, 'f', 2));
- else
- cost_label_->setText("Est: --");
}
} // namespace fincept::screens::crypto
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h
index 58df901dc..43af3d36d 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoOrderEntry.h
@@ -54,12 +54,27 @@ class CryptoOrderEntry : public QWidget {
QWidget* advanced_section_ = nullptr;
QPushButton* advanced_toggle_ = nullptr;
- // Labels
+ // Container rows so price/stop can be shown/hidden as a unit when the
+ // selected order type doesn't need them.
+ QWidget* price_row_ = nullptr;
+ QWidget* stop_row_ = nullptr;
+
+ // Header / account card labels
QLabel* balance_label_ = nullptr;
QLabel* market_price_label_ = nullptr;
+ QLabel* avail_label_ = nullptr;
+ QLabel* mode_label_ = nullptr;
+
+ // Order breakdown
QLabel* cost_label_ = nullptr;
+ QLabel* fee_label_ = nullptr;
+ QLabel* total_label_ = nullptr;
+ QLabel* recv_label_ = nullptr;
+ QLabel* pct_used_label_ = nullptr;
+
+ // Submit subtitle (rendered as a second line under the main button label)
+ QLabel* submit_subtitle_ = nullptr;
QLabel* status_label_ = nullptr;
- QLabel* mode_label_ = nullptr;
// Futures controls
QWidget* futures_section_ = nullptr;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
index 567c2b9aa..486e85636 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
@@ -1179,6 +1179,11 @@ void CryptoTradingScreen::refresh_portfolio() {
self->bottom_panel_->set_orders(s.orders);
self->bottom_panel_->set_trades(s.trades);
self->bottom_panel_->set_stats(s.stats);
+ LOG_INFO(TAG, QString("Paper portfolio refreshed: %1 positions, %2 orders, %3 trades, balance=%4")
+ .arg(s.positions.size())
+ .arg(s.orders.size())
+ .arg(s.trades.size())
+ .arg(s.portfolio.balance, 0, 'f', 2));
}, Qt::QueuedConnection);
});
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp
index 65169adfc..554c01f95 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.cpp
@@ -133,6 +133,16 @@ BaseWidget::BaseWidget(const QString& title, QWidget* parent, const QString& acc
// region (not the title bar). Sized via an event filter on `content_`.
loading_overlay_ = new LoadingOverlay(content_);
loading_overlay_->attach_to(content_);
+
+ // ── Loading watchdog ──
+ // Single-shot guard against producers that never publish. If the
+ // overlay is still active 12 s after loading started with zero items
+ // delivered, swap to a terminal "no data" overlay so the spinner can't
+ // spin forever. Per-widget refresh still works to re-arm.
+ loading_watchdog_ = new QTimer(this);
+ loading_watchdog_->setSingleShot(true);
+ loading_watchdog_->setInterval(12000);
+ connect(loading_watchdog_, &QTimer::timeout, this, &BaseWidget::on_watchdog_fired);
}
void BaseWidget::refresh_base_theme() {
@@ -167,10 +177,14 @@ void BaseWidget::set_loading(bool loading) {
loading_label_->setText(loading ? "LOADING..." : "");
if (!loading_overlay_)
return;
- if (loading)
+ if (loading) {
loading_overlay_->start_indeterminate();
- else
+ last_progress_loaded_ = 0;
+ arm_watchdog();
+ } else {
loading_overlay_->finish();
+ disarm_watchdog();
+ }
}
void BaseWidget::set_loading_progress(int loaded, int expected) {
@@ -180,6 +194,11 @@ void BaseWidget::set_loading_progress(int loaded, int expected) {
loading_label_->setVisible(active);
loading_label_->setText(active ? QStringLiteral("LOADING...") : QString());
loading_overlay_->set_progress(loaded, expected);
+ last_progress_loaded_ = loaded;
+ if (active)
+ arm_watchdog();
+ else
+ disarm_watchdog();
}
void BaseWidget::set_error(const QString& error) {
@@ -193,6 +212,7 @@ void BaseWidget::set_error(const QString& error) {
loading_label_->setVisible(false);
loading_label_->setText(QString());
}
+ disarm_watchdog();
// Clear content and show error
QLayoutItem* item;
@@ -229,4 +249,34 @@ void BaseWidget::on_config_clicked() {
dlg->exec();
}
+void BaseWidget::arm_watchdog() {
+ if (!loading_watchdog_)
+ return;
+ loading_watchdog_->start();
+}
+
+void BaseWidget::disarm_watchdog() {
+ if (!loading_watchdog_)
+ return;
+ loading_watchdog_->stop();
+}
+
+void BaseWidget::on_watchdog_fired() {
+ if (!loading_overlay_ || !loading_overlay_->is_active())
+ return;
+ if (loading_label_) {
+ loading_label_->setVisible(false);
+ loading_label_->setText(QString());
+ }
+ // If some data trickled in before the timeout, just hide the spinner so
+ // the partial content becomes visible. Otherwise surface a soft error so
+ // the user knows the widget hasn't simply hung.
+ if (last_progress_loaded_ > 0) {
+ loading_overlay_->finish();
+ } else {
+ loading_overlay_->set_error(
+ QStringLiteral("No data yet — click refresh to retry"));
+ }
+}
+
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
index 07b50c5ba..b631c0894 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
@@ -7,6 +7,7 @@
#include <QJsonObject>
#include <QLabel>
#include <QPushButton>
+#include <QTimer>
#include <QVBoxLayout>
namespace fincept::screens::widgets {
@@ -79,6 +80,9 @@ class BaseWidget : public QFrame {
private:
void refresh_base_theme();
void on_config_clicked();
+ void arm_watchdog();
+ void disarm_watchdog();
+ void on_watchdog_fired();
private:
QWidget* title_bar_ = nullptr;
@@ -90,6 +94,8 @@ class BaseWidget : public QFrame {
QPushButton* refresh_btn_ = nullptr;
QPushButton* config_btn_ = nullptr;
LoadingOverlay* loading_overlay_ = nullptr;
+ QTimer* loading_watchdog_ = nullptr;
+ int last_progress_loaded_ = 0;
QString accent_color_;
};
diff --git a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp
index 8acd2f279..79cf0058f 100644
--- a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp
@@ -7,7 +7,6 @@
#include <QEvent>
#include <QFont>
#include <QFontMetrics>
-#include <QGraphicsOpacityEffect>
#include <QLinearGradient>
#include <QPaintEvent>
#include <QPainter>
@@ -39,9 +38,12 @@ LoadingOverlay::LoadingOverlay(QWidget* parent) : QWidget(parent) {
setFocusPolicy(Qt::NoFocus);
setVisible(false);
- opacity_effect_ = new QGraphicsOpacityEffect(this);
- opacity_effect_->setOpacity(0.0);
- setGraphicsEffect(opacity_effect_);
+ // QGraphicsOpacityEffect was previously used here. Removed: on Qt6 the
+ // effect forces an offscreen render pass + composite on every paint even
+ // when opacity is 1.0, which adds ~ms per frame per overlay. With ~30
+ // dashboard widgets each owning an overlay this dominated paint time on
+ // low-end GPUs. We now apply opacity directly via QPainter::setOpacity
+ // in paintEvent and drive it through the `fadeOpacity` Q_PROPERTY.
shimmer_anim_ = new QPropertyAnimation(this, "shimmerPhase", this);
shimmer_anim_->setDuration(kShimmerPeriodMs);
@@ -53,11 +55,11 @@ LoadingOverlay::LoadingOverlay(QWidget* parent) : QWidget(parent) {
progress_anim_->setDuration(kProgressEaseMs);
progress_anim_->setEasingCurve(QEasingCurve::OutCubic);
- fade_anim_ = new QPropertyAnimation(opacity_effect_, "opacity", this);
+ fade_anim_ = new QPropertyAnimation(this, "fadeOpacity", this);
fade_anim_->setDuration(kFadeMs);
connect(fade_anim_, &QPropertyAnimation::finished, this, [this]() {
// If we faded out, actually hide so we stop drawing on top.
- if (opacity_effect_->opacity() <= 0.001) {
+ if (fade_opacity_ <= 0.001) {
setVisible(false);
stop_shimmer();
}
@@ -93,10 +95,17 @@ void LoadingOverlay::set_displayed_progress(qreal v) {
update();
}
+void LoadingOverlay::set_fade_opacity(qreal v) {
+ fade_opacity_ = v;
+ update();
+}
+
void LoadingOverlay::start_indeterminate() {
indeterminate_ = true;
loaded_ = 0;
expected_ = 0;
+ error_mode_ = false;
+ error_text_.clear();
progress_anim_->stop();
displayed_progress_ = 0.0;
@@ -118,6 +127,8 @@ void LoadingOverlay::set_progress(int loaded, int expected) {
}
indeterminate_ = false;
+ error_mode_ = false;
+ error_text_.clear();
loaded_ = std::clamp(loaded, 0, expected);
expected_ = expected;
@@ -143,12 +154,29 @@ void LoadingOverlay::set_progress(int loaded, int expected) {
}
void LoadingOverlay::finish() {
+ error_mode_ = false;
+ error_text_.clear();
if (!active_)
return;
active_ = false;
fade_out_and_hide();
}
+void LoadingOverlay::set_error(const QString& message) {
+ error_mode_ = true;
+ error_text_ = message;
+ stop_shimmer();
+ progress_anim_->stop();
+ if (!active_) {
+ active_ = true;
+ sync_geometry();
+ setVisible(true);
+ raise();
+ fade_in();
+ }
+ update();
+}
+
void LoadingOverlay::start_shimmer() {
if (shimmer_anim_->state() != QAbstractAnimation::Running)
shimmer_anim_->start();
@@ -160,18 +188,34 @@ void LoadingOverlay::stop_shimmer() {
void LoadingOverlay::fade_in() {
fade_anim_->stop();
- fade_anim_->setStartValue(opacity_effect_->opacity());
+ fade_anim_->setStartValue(fade_opacity_);
fade_anim_->setEndValue(1.0);
fade_anim_->start();
}
void LoadingOverlay::fade_out_and_hide() {
fade_anim_->stop();
- fade_anim_->setStartValue(opacity_effect_->opacity());
+ fade_anim_->setStartValue(fade_opacity_);
fade_anim_->setEndValue(0.0);
fade_anim_->start();
}
+void LoadingOverlay::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ // Resume the shimmer animation when our parent widget tree becomes
+ // visible again (e.g. user switches back to the dashboard tab). Without
+ // this the QPropertyAnimation central timer would keep ticking ~60Hz on
+ // every overlay regardless of visibility — 30+ overlays × 60Hz is
+ // measurable on weak hardware.
+ if (active_ && !error_mode_)
+ start_shimmer();
+}
+
+void LoadingOverlay::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ stop_shimmer();
+}
+
void LoadingOverlay::sync_geometry() {
if (target_)
setGeometry(target_->rect());
@@ -192,6 +236,9 @@ void LoadingOverlay::paintEvent(QPaintEvent* /*e*/) {
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::TextAntialiasing, true);
+ // Apply our fade opacity directly via the painter (was previously a
+ // QGraphicsOpacityEffect — see comment in the constructor).
+ p.setOpacity(fade_opacity_);
const QRect r = rect();
if (r.isEmpty())
@@ -203,6 +250,20 @@ void LoadingOverlay::paintEvent(QPaintEvent* /*e*/) {
// the loading state still feels like part of the widget.
p.fillRect(r, with_alpha(ui::colors::BG_SURFACE(), 235));
+ // ── Error mode ──
+ if (error_mode_) {
+ QFont err_font;
+ err_font.setFamily(ui::fonts::DATA_FAMILY);
+ err_font.setPixelSize(11);
+ err_font.setBold(true);
+ err_font.setLetterSpacing(QFont::AbsoluteSpacing, 0.6);
+ p.setFont(err_font);
+ p.setPen(QColor(ui::colors::NEGATIVE()));
+ const QRect text_rect = r.adjusted(12, 12, -12, -12);
+ p.drawText(text_rect, Qt::AlignCenter | Qt::TextWordWrap, error_text_);
+ return;
+ }
+
// ── Skeleton bars ──
// Three rows of varying widths simulate where content will appear. The
// shimmer sweeps across these, not across the full widget background.
diff --git a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h
index f50cf8930..6f0c6536e 100644
--- a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h
+++ b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h
@@ -4,8 +4,6 @@
#include <QPropertyAnimation>
#include <QWidget>
-class QGraphicsOpacityEffect;
-
namespace fincept::screens::widgets {
/// Animated loading state shown on top of a widget's content area while data
@@ -30,6 +28,7 @@ class LoadingOverlay : public QWidget {
Q_OBJECT
Q_PROPERTY(qreal shimmerPhase READ shimmer_phase WRITE set_shimmer_phase)
Q_PROPERTY(qreal displayedProgress READ displayed_progress WRITE set_displayed_progress)
+ Q_PROPERTY(qreal fadeOpacity READ fade_opacity WRITE set_fade_opacity)
public:
explicit LoadingOverlay(QWidget* parent = nullptr);
@@ -51,15 +50,26 @@ class LoadingOverlay : public QWidget {
/// Hide the overlay (with fade-out) and stop animations.
void finish();
+ /// Switch the overlay into an error state — keeps it visible, stops the
+ /// shimmer/progress animation, and renders `message` in place of the
+ /// "LOADING…" label. Use for terminal failures (network down, watchdog
+ /// fired, producer error). The next call to `start_indeterminate()` /
+ /// `set_progress()` clears error mode and resumes normal loading display.
+ void set_error(const QString& message);
+
bool is_active() const { return active_; }
qreal shimmer_phase() const { return shimmer_phase_; }
void set_shimmer_phase(qreal v);
qreal displayed_progress() const { return displayed_progress_; }
void set_displayed_progress(qreal v);
+ qreal fade_opacity() const { return fade_opacity_; }
+ void set_fade_opacity(qreal v);
protected:
void paintEvent(QPaintEvent* e) override;
+ void showEvent(QShowEvent* e) override;
+ void hideEvent(QHideEvent* e) override;
bool eventFilter(QObject* obj, QEvent* e) override;
private:
@@ -74,14 +84,16 @@ class LoadingOverlay : public QWidget {
bool indeterminate_ = true;
int loaded_ = 0;
int expected_ = 0;
+ bool error_mode_ = false;
+ QString error_text_;
qreal shimmer_phase_ = 0.0; ///< 0..1 — drives the sweeping highlight
qreal displayed_progress_ = 0.0; ///< 0..1 — eased toward loaded_/expected_
+ qreal fade_opacity_ = 0.0; ///< 0..1 — applied directly via QPainter::setOpacity
QPropertyAnimation* shimmer_anim_ = nullptr;
QPropertyAnimation* progress_anim_ = nullptr;
QPropertyAnimation* fade_anim_ = nullptr;
- QGraphicsOpacityEffect* opacity_effect_ = nullptr;
};
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 671757af5..6741285f1 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -681,18 +681,26 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
order_entry_->set_symbol(selected_symbol_);
order_entry_->set_exchange(selected_exchange_);
- // Ensure stream is running and configure it
+ // Ensure stream is running and configure it. Skip data fetches when the
+ // account has no credentials yet — every fetch_* spawns a QtConcurrent
+ // thread that bails on an empty api_key check inside the lambda. Firing
+ // ~11 of those at once trips _pthread_create on macOS and crashes the
+ // process (see crash report 2026-05-08-123609.ips). The credentials_saved
+ // handler will re-run the data-fetch path once the user connects.
+ const bool has_creds = !AccountManager::instance().load_credentials(account_id).api_key.isEmpty();
auto& dsm = DataStreamManager::instance();
- dsm.start_stream(account_id);
- auto* stream = dsm.stream_for(account_id);
- if (stream) {
- stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(watchlist_symbols_);
- stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
- stream->fetch_orderbook(selected_symbol_);
- stream->fetch_time_sales(selected_symbol_);
- stream->fetch_calendar();
- stream->fetch_clock();
+ if (has_creds) {
+ dsm.start_stream(account_id);
+ auto* stream = dsm.stream_for(account_id);
+ if (stream) {
+ stream->set_selected_symbol(selected_symbol_, selected_exchange_);
+ stream->subscribe_symbols(watchlist_symbols_);
+ stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
+ stream->fetch_orderbook(selected_symbol_);
+ stream->fetch_time_sales(selected_symbol_);
+ stream->fetch_calendar();
+ stream->fetch_clock();
+ }
}
// Load paper portfolio orders into matcher
@@ -811,10 +819,13 @@ void EquityTradingScreen::on_accounts_clicked() {
auto* dlg = new AccountManagementDialog(this);
connect(dlg, &AccountManagementDialog::account_added, this, [this](const QString& account_id) {
+ Q_UNUSED(account_id);
update_account_menu();
- // If no focused account, auto-focus the new one
- if (focused_account_id_.isEmpty())
- on_account_changed(account_id);
+ // Don't auto-focus a freshly-added account: it has no credentials yet,
+ // so on_account_changed() would spawn ~11 QtConcurrent::run fetches that
+ // all bail at the empty-api_key check. On macOS that thread-storm trips
+ // pthread_create inside QThreadPool and crashes the main thread (see
+ // crash report 2026-05-08-123609.ips). Defer focus to credentials_saved.
});
connect(dlg, &AccountManagementDialog::account_removed, this, [this](const QString& account_id) {
@@ -833,6 +844,15 @@ void EquityTradingScreen::on_accounts_clicked() {
connect(dlg, &AccountManagementDialog::credentials_saved, this, [this](const QString& account_id) {
token_expired_shown_.store(false);
+ // First account ever connected: focus it now (account_added intentionally
+ // does not auto-focus — see comment there). on_account_changed() does its
+ // own start_stream() + symbol/watchlist setup, so we're done after that.
+ if (focused_account_id_.isEmpty()) {
+ on_account_changed(account_id);
+ AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
+ update_connection_status();
+ return;
+ }
// Start/restart the stream with new credentials
DataStreamManager::instance().start_stream(account_id);
auto* stream = DataStreamManager::instance().stream_for(account_id);
diff --git a/fincept-qt/src/screens/profile/ProfileScreen.cpp b/fincept-qt/src/screens/profile/ProfileScreen.cpp
index 7f68da135..fcaf72ecb 100644
--- a/fincept-qt/src/screens/profile/ProfileScreen.cpp
+++ b/fincept-qt/src/screens/profile/ProfileScreen.cpp
@@ -784,10 +784,10 @@ void ProfileScreen::show_delete_account_dialog() {
if (first != QMessageBox::Yes)
return;
- // Second confirmation — type email to confirm
+ // Second confirmation — type email + enter password to confirm
auto* dlg = new QDialog(this);
dlg->setWindowTitle("Confirm Account Deletion");
- dlg->setFixedSize(400, 200);
+ dlg->setFixedSize(400, 260);
dlg->setStyleSheet(QString("background:%1;color:%2;font-family:'Consolas',monospace;")
.arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY()));
auto* vl = new QVBoxLayout(dlg);
@@ -807,6 +807,16 @@ void ProfileScreen::show_delete_account_dialog() {
input->setPlaceholderText(email);
vl->addWidget(input);
+ auto* pw_lbl = new QLabel("ENTER YOUR PASSWORD:");
+ pw_lbl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;background:transparent;").arg(ui::colors::NEGATIVE()));
+ vl->addWidget(pw_lbl);
+
+ auto* pw_input = new QLineEdit;
+ pw_input->setFixedHeight(28);
+ pw_input->setEchoMode(QLineEdit::Password);
+ pw_input->setPlaceholderText("Current password");
+ vl->addWidget(pw_input);
+
auto* brl = new QHBoxLayout;
brl->addStretch();
auto* cancel = new QPushButton("CANCEL");
@@ -822,16 +832,21 @@ void ProfileScreen::show_delete_account_dialog() {
"font-size:11px;font-weight:700;font-family:'Consolas',monospace;}"
"QPushButton:disabled{background:#3f1515;color:#7f3333;}")
.arg(ui::colors::NEGATIVE(), ui::colors::TEXT_PRIMARY()));
- connect(input, &QLineEdit::textChanged, this, [confirm, email](const QString& text) {
- confirm->setEnabled(text.trimmed() == email);
- });
+ auto reeval = [confirm, input, pw_input, email]() {
+ const bool email_ok = input->text().trimmed() == email;
+ const bool pw_ok = !pw_input->text().isEmpty();
+ confirm->setEnabled(email_ok && pw_ok);
+ };
+ connect(input, &QLineEdit::textChanged, this, [reeval](const QString&) { reeval(); });
+ connect(pw_input, &QLineEdit::textChanged, this, [reeval](const QString&) { reeval(); });
QPointer<ProfileScreen> self = this;
QPointer<QDialog> dlg_ptr = dlg;
- connect(confirm, &QPushButton::clicked, this, [self, dlg_ptr]() {
+ connect(confirm, &QPushButton::clicked, this, [self, dlg_ptr, email, pw_input]() {
if (!self) return;
+ const QString password = pw_input->text();
if (dlg_ptr) dlg_ptr->accept();
- auth::UserApi::instance().delete_user_account([self](auth::ApiResponse r) {
+ auth::UserApi::instance().delete_user_account(email, password, [self](auth::ApiResponse r) {
if (!self) return;
if (r.success) {
LOG_INFO("Profile", "Account deleted successfully");
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
index b8731930d..27005925c 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
@@ -462,6 +462,10 @@ void WatchlistScreen::fetch_quotes() {
}
hub_resubscribe_stocks();
+ // Render placeholder rows synchronously so a newly-added symbol appears
+ // in the table immediately. Real prices fill in as the hub delivers
+ // quotes via the subscription callbacks.
+ rebuild_from_cache();
}
@@ -501,12 +505,16 @@ void WatchlistScreen::hub_resubscribe_stocks() {
const QString topic = QStringLiteral("market:quote:") + sym;
topics.append(topic);
hub.subscribe(this, topic, [this, sym](const QVariant& v) {
+ LOG_INFO("Watchlist", QString("hub callback fired for %1 (canConvert=%2)")
+ .arg(sym).arg(v.canConvert<services::QuoteData>()));
if (!v.canConvert<services::QuoteData>())
return;
row_cache_.insert(sym, v.value<services::QuoteData>());
rebuild_from_cache();
});
}
+ LOG_INFO("Watchlist", QString("subscribed + requesting %1 topics: %2")
+ .arg(topics.size()).arg(topics.join(", ")));
// force=true: watchlist symbols change on user edit; bypass min_interval
// so newly-added tickers resolve immediately instead of waiting for the
// scheduler tick.
diff --git a/fincept-qt/src/services/markets/MarketDataService.cpp b/fincept-qt/src/services/markets/MarketDataService.cpp
index 1caa8a514..a666707aa 100644
--- a/fincept-qt/src/services/markets/MarketDataService.cpp
+++ b/fincept-qt/src/services/markets/MarketDataService.cpp
@@ -122,6 +122,20 @@ void MarketDataService::refresh(const QStringList& topics) {
if (!ok) {
LOG_WARN("MarketData",
QString("batch_all failed in %1ms: %2").arg(elapsed).arg(err.left(200)));
+ // Notify hub so subscribers can react (clear spinner / show
+ // error) and so the scheduler clears the in_flight flag for
+ // retry on the next pass. Without this widgets that depend
+ // on these topics would spin forever on producer failure.
+ auto& hub = datahub::DataHub::instance();
+ const QString msg = err.isEmpty()
+ ? QStringLiteral("Market data refresh failed")
+ : err.left(200);
+ for (const auto& s : quote_syms)
+ hub.publish_error(QStringLiteral("market:quote:") + s, msg);
+ for (const auto& s : spark_syms)
+ hub.publish_error(QStringLiteral("market:sparkline:") + s, msg);
+ for (const auto& h : hist_reqs)
+ hub.publish_error(h.topic, msg);
return;
}
diff --git a/fincept-qt/src/services/news/NewsService.cpp b/fincept-qt/src/services/news/NewsService.cpp
index 582740cbd..4267d473e 100644
--- a/fincept-qt/src/services/news/NewsService.cpp
+++ b/fincept-qt/src/services/news/NewsService.cpp
@@ -26,7 +26,7 @@
namespace fincept::services {
-static constexpr int kFeedTransferTimeoutMs = 8000; // 8s per RSS feed request
+static constexpr int kFeedTransferTimeoutMs = 4000; // 4s per RSS feed request — was 8s; many tail feeds time out anyway so we'd rather show the fast majority within 1-2s than wait on the slow 5%
static constexpr int kWsReconnectDelayMs = 10000; // 10s before WebSocket reconnect
static constexpr int kSummaryMaxChars = 300; // max chars for article summary
@@ -1294,6 +1294,41 @@ void NewsService::refresh(const QStringList& topics) {
}
if (!needs_general) return;
+ // Cache-first: prime the hub with last-known-good articles from disk so
+ // subscribers (NewsWidget etc.) render in ~50 ms on cold start instead
+ // of waiting for RSS feeds to resolve. The network refresh below then
+ // overwrites with fresh data when it lands.
+ const QVariant cached = fincept::CacheManager::instance().get("news:articles");
+ if (!cached.isNull()) {
+ const QJsonArray arr = QJsonDocument::fromJson(cached.toString().toUtf8()).array();
+ if (!arr.isEmpty()) {
+ QVector<NewsArticle> articles;
+ articles.reserve(arr.size());
+ for (const auto& v : arr) {
+ const QJsonObject o = v.toObject();
+ NewsArticle a;
+ a.id = o["id"].toString();
+ a.time = o["time"].toString();
+ a.headline = o["headline"].toString();
+ a.summary = o["summary"].toString();
+ a.source = o["source"].toString();
+ a.region = o["region"].toString();
+ a.category = o["category"].toString();
+ a.link = o["link"].toString();
+ a.sort_ts = o["sort_ts"].toVariant().toLongLong();
+ a.tier = o["tier"].toInt(4);
+ a.priority = priority_from_string(o["priority"].toString());
+ a.sentiment = sentiment_from_string(o["sentiment"].toString());
+ a.impact = impact_from_string(o["impact"].toString());
+ a.lang = o["lang"].toString();
+ for (const auto& t : o["tickers"].toArray())
+ a.tickers << t.toString();
+ articles.append(a);
+ }
+ publish_articles_to_hub(articles);
+ }
+ }
+
// All non-cluster topics derive from the general feed; one fetch
// fans out via publish_articles_to_hub.
fetch_all_news_progressive(/*force=*/true, [](bool, QVector<NewsArticle>) {});
diff --git a/fincept-qt/src/services/updater/UpdateService.h b/fincept-qt/src/services/updater/UpdateService.h
index bea79acf5..ae888bb8c 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.3", "download-url": "...", "sha256": "...", "open-url": "...", "changelog": "..." },
/// "windows-arm64":{ ... },
/// "linux-x64": { ... },
/// "macos-arm64": { ... },
diff --git a/fincept-qt/src/storage/sqlite/Database.cpp b/fincept-qt/src/storage/sqlite/Database.cpp
index b5765f786..f53186515 100644
--- a/fincept-qt/src/storage/sqlite/Database.cpp
+++ b/fincept-qt/src/storage/sqlite/Database.cpp
@@ -3,26 +3,46 @@
#include "core/logging/Logger.h"
#include "storage/sqlite/migrations/MigrationRunner.h"
+#include <QSqlError>
+#include <QThread>
+
namespace fincept {
+namespace {
+constexpr const char* kMainConnectionName = "fincept_main";
+constexpr const char* kDbTag = "DB";
+
+QString thread_label(QThread* t) {
+ if (!t)
+ return QStringLiteral("?");
+ const QString name = t->objectName();
+ return name.isEmpty()
+ ? QStringLiteral("0x%1").arg(reinterpret_cast<quintptr>(t), 0, 16)
+ : name;
+}
+} // namespace
+
Database& Database::instance() {
static Database s;
return s;
}
Result<void> Database::open(const QString& path) {
- db_ = QSqlDatabase::addDatabase("QSQLITE", "fincept_main");
+ main_thread_ = QThread::currentThread();
+ db_path_ = path;
+
+ db_ = QSqlDatabase::addDatabase("QSQLITE", kMainConnectionName);
db_.setDatabaseName(path);
if (!db_.open()) {
return Result<void>::err(db_.lastError().text().toStdString());
}
- LOG_INFO("DB", "Opened database: " + path);
+ LOG_INFO(kDbTag, "Opened database: " + path);
- auto pr = apply_pragmas();
+ auto pr = apply_pragmas(db_, /*include_database_wide=*/true);
if (pr.is_err())
return pr;
- // Run versioned migrations
+ // Run versioned migrations on the main connection.
MigrationRunner runner(db_);
return runner.run();
}
@@ -36,8 +56,69 @@ bool Database::is_open() const {
return db_.isOpen();
}
+QSqlDatabase Database::connection() {
+ QThread* t = QThread::currentThread();
+
+ // Main-thread fast path — the connection opened by `open()`.
+ if (t == main_thread_)
+ return db_;
+
+ // Per-thread cloned connection. The thread_local Guard owns the
+ // connection-name lifetime so the registry entry is removed when the
+ // thread exits. This handles QtConcurrent thread-pool workers correctly:
+ // they keep their connection across tasks and clean up at pool shutdown.
+ struct Guard {
+ QString name;
+ ~Guard() {
+ if (!name.isEmpty()) {
+ // Remove from Qt's connection registry so file descriptors
+ // and the QSqlDriver are released. Logs an inert warning if
+ // any QSqlDatabase handle is still alive — harmless.
+ QSqlDatabase::removeDatabase(name);
+ }
+ }
+ };
+ thread_local Guard guard;
+
+ if (guard.name.isEmpty()) {
+ if (db_path_.isEmpty()) {
+ LOG_ERROR(kDbTag, "connection() called before open() — refusing to clone");
+ return {};
+ }
+
+ // Unique connection name per thread. Encode pointer + objectName so
+ // log messages are debuggable.
+ guard.name = QStringLiteral("fincept_thread_%1_%2")
+ .arg(thread_label(t))
+ .arg(reinterpret_cast<quintptr>(t), 0, 16);
+
+ QSqlDatabase clone = QSqlDatabase::cloneDatabase(db_, guard.name);
+ if (!clone.open()) {
+ const QString err = clone.lastError().text();
+ LOG_ERROR(kDbTag, QString("Failed to open per-thread connection on [%1]: %2")
+ .arg(thread_label(t), err));
+ // Clean up the registry entry we created via cloneDatabase.
+ QSqlDatabase::removeDatabase(guard.name);
+ guard.name.clear();
+ return {};
+ }
+ // Database-wide PRAGMAs (journal_mode) are already set by the main
+ // connection — only re-apply per-connection ones.
+ apply_pragmas(clone, /*include_database_wide=*/false);
+ const int n = ++per_thread_connections_;
+ LOG_INFO(kDbTag, QString("Opened per-thread connection on [%1] (total=%2)")
+ .arg(thread_label(t))
+ .arg(n));
+ }
+ return QSqlDatabase::database(guard.name, /*open=*/false);
+}
+
Result<QSqlQuery> Database::execute(const QString& sql, const QVariantList& params) {
- QSqlQuery query(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen()) {
+ return Result<QSqlQuery>::err("DB connection unavailable on this thread");
+ }
+ QSqlQuery query(conn);
query.prepare(sql);
for (int i = 0; i < params.size(); ++i) {
query.bindValue(i, params[i]);
@@ -49,7 +130,11 @@ Result<QSqlQuery> Database::execute(const QString& sql, const QVariantList& para
}
Result<void> Database::exec(const QString& sql) {
- QSqlQuery query(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen()) {
+ return Result<void>::err("DB connection unavailable on this thread");
+ }
+ QSqlQuery query(conn);
if (!query.exec(sql)) {
return Result<void>::err(query.lastError().text().toStdString());
}
@@ -57,7 +142,10 @@ Result<void> Database::exec(const QString& sql) {
}
Result<void> Database::begin_transaction() {
- QSqlQuery q(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen())
+ return Result<void>::err("DB connection unavailable on this thread");
+ QSqlQuery q(conn);
if (!q.exec("BEGIN IMMEDIATE")) {
return Result<void>::err(q.lastError().text().toStdString());
}
@@ -65,7 +153,10 @@ Result<void> Database::begin_transaction() {
}
Result<void> Database::commit() {
- QSqlQuery q(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen())
+ return Result<void>::err("DB connection unavailable on this thread");
+ QSqlQuery q(conn);
if (!q.exec("COMMIT")) {
return Result<void>::err(q.lastError().text().toStdString());
}
@@ -73,26 +164,49 @@ Result<void> Database::commit() {
}
Result<void> Database::rollback() {
- QSqlQuery q(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen())
+ return Result<void>::err("DB connection unavailable on this thread");
+ QSqlQuery q(conn);
if (!q.exec("ROLLBACK")) {
return Result<void>::err(q.lastError().text().toStdString());
}
return Result<void>::ok();
}
-Result<void> Database::apply_pragmas() {
- const char* pragmas[] = {
- "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -20000",
- "PRAGMA temp_store = MEMORY", "PRAGMA mmap_size = 268435456", "PRAGMA foreign_keys = ON",
+Result<void> Database::apply_pragmas(QSqlDatabase& conn, bool include_database_wide) {
+ // Database-wide PRAGMAs only need to be set once (any connection sets them
+ // for the file). Per-connection PRAGMAs (foreign_keys, busy_timeout, …)
+ // have to be re-applied for every cloned connection or cascade deletes
+ // and contention behaviour will silently regress.
+ static const char* kDatabaseWide[] = {
+ "PRAGMA journal_mode = WAL",
+ };
+ static const char* kPerConnection[] = {
+ "PRAGMA synchronous = NORMAL",
+ "PRAGMA cache_size = -20000",
+ "PRAGMA temp_store = MEMORY",
+ "PRAGMA mmap_size = 268435456",
+ "PRAGMA foreign_keys = ON",
"PRAGMA busy_timeout = 5000",
};
- for (auto* p : pragmas) {
- auto r = exec(p);
- if (r.is_err()) {
- LOG_WARN("DB", QString("PRAGMA failed: %1 — %2").arg(p, QString::fromStdString(r.error())));
+
+ auto run = [&conn](const char* sql) {
+ QSqlQuery q(conn);
+ if (!q.exec(QLatin1String(sql))) {
+ LOG_WARN(kDbTag, QString("PRAGMA failed: %1 — %2").arg(sql, q.lastError().text()));
}
+ };
+
+ if (include_database_wide) {
+ for (auto* p : kDatabaseWide)
+ run(p);
}
- LOG_INFO("DB", "PRAGMAs applied (WAL, foreign_keys, cache_size=20MB)");
+ for (auto* p : kPerConnection)
+ run(p);
+
+ if (include_database_wide)
+ LOG_INFO(kDbTag, "PRAGMAs applied (WAL, foreign_keys, cache_size=20MB)");
return Result<void>::ok();
}
diff --git a/fincept-qt/src/storage/sqlite/Database.h b/fincept-qt/src/storage/sqlite/Database.h
index 2fd81e152..374221576 100644
--- a/fincept-qt/src/storage/sqlite/Database.h
+++ b/fincept-qt/src/storage/sqlite/Database.h
@@ -7,9 +7,20 @@
#include <QString>
#include <QVariantList>
+#include <atomic>
+
+class QThread;
+
namespace fincept {
/// SQLite database wrapper with WAL mode, prepared statements, and transaction support.
+///
+/// Thread-safety: QSqlDatabase is single-threaded by design — a connection can
+/// only be used on the thread that created it (Qt docs). To support background
+/// queries (QtConcurrent::run lambdas in repositories) without silent query
+/// failures, this class hands out a CLONED per-thread connection on demand via
+/// `connection()`. The clone is registered with `QSqlDatabase` under a unique
+/// name and torn down automatically when the thread terminates.
class Database {
public:
static Database& instance();
@@ -18,10 +29,17 @@ class Database {
void close();
bool is_open() const;
+ /// Returns a `QSqlDatabase` handle valid for the current thread.
+ /// On the main thread, returns the primary connection opened by `open()`.
+ /// On any other thread, lazy-creates a thread-local cloned connection on
+ /// first call and reuses it for subsequent calls. The thread_local guard
+ /// removes the cloned connection from the registry on thread exit.
+ QSqlDatabase connection();
+
Result<QSqlQuery> execute(const QString& sql, const QVariantList& params = {});
Result<void> exec(const QString& sql);
- // Transaction support
+ // Transaction support (per-thread — operates on the calling thread's connection).
Result<void> begin_transaction();
Result<void> commit();
Result<void> rollback();
@@ -29,13 +47,16 @@ class Database {
QSqlDatabase& raw_db() { return db_; }
/// Returns the file path of the open database (empty if not open).
- QString path() const { return db_.databaseName(); }
+ QString path() const { return db_path_; }
private:
Database() = default;
- Result<void> apply_pragmas();
+ Result<void> apply_pragmas(QSqlDatabase& conn, bool include_database_wide);
- QSqlDatabase db_;
+ QSqlDatabase db_; // main-thread (owning) connection
+ QThread* main_thread_ = nullptr; // captured at open()
+ QString db_path_; // for cloning per-thread connections
+ std::atomic<int> per_thread_connections_{0}; // diagnostic counter
};
} // namespace fincept
diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
index b57f09bd3..f38bad376 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.3"},
{"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.3"},
{"browsername", "Chrome"},
{"browserversion", "120.0"},
};
diff --git a/fincept-qt/src/ui/navigation/StatusBar.cpp b/fincept-qt/src/ui/navigation/StatusBar.cpp
index 32b729a76..522fd4098 100644
--- a/fincept-qt/src/ui/navigation/StatusBar.cpp
+++ b/fincept-qt/src/ui/navigation/StatusBar.cpp
@@ -23,7 +23,7 @@ StatusBar::StatusBar(QWidget* parent) : QWidget(parent) {
return l;
};
- hl->addWidget(mk("v4.0.2", "sbVersion"));
+ hl->addWidget(mk("v4.0.3", "sbVersion"));
hl->addWidget(mk(" | ", "sbSep"));
const char* feeds[] = {"EQ", "FX", "CM", "FI", "CR"};
for (auto& f : feeds) {
diff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cpp
index c3ae0b8fe..0b2080a07 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.cpp
+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp
@@ -1,6 +1,7 @@
#include "ui/navigation/ToolBar.h"
#include "auth/AuthManager.h"
+#include "ui/pushpins/PushpinBar.h"
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
@@ -44,6 +45,10 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
hl->setSpacing(0);
menu_bar_ = new QMenuBar(this);
+ // Keep the menu inline in the toolbar on macOS. Without this, Qt migrates
+ // the QMenuBar into the native screen-top application menu, leaving
+ // File/Navigate/View/Help missing from the toolbar row on Mac builds.
+ menu_bar_->setNativeMenuBar(false);
menu_bar_->setStyleSheet(menu_ss());
menu_bar_->addMenu(build_file_menu());
menu_bar_->addMenu(build_navigate_menu());
@@ -86,13 +91,21 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
live_label_ = mk(" LIVE");
hl->addWidget(live_label_);
- hl->addStretch(1);
+ sep();
+
+ // Inline pushpin chips — used to live in a separate toolbar row, now
+ // embedded directly so symbol pins share the row with menus and clock.
+ pushpin_bar_ = new PushpinBar(this);
+ pushpin_bar_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ hl->addWidget(pushpin_bar_, 1);
+
+ sep();
clock_label_ = mk("");
clock_label_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
hl->addWidget(clock_label_);
- hl->addStretch(1);
+ hl->addStretch(0);
user_label_ = mk("---");
user_label_->setMaximumWidth(120);
@@ -210,9 +223,11 @@ void ToolBar::apply_responsive_layout(int w) {
if (chat_mode_btn_)
chat_mode_btn_->setVisible(show_chat);
- if (separators_.size() >= 5) {
- separators_[2]->setVisible(show_credits);
- separators_[3]->setVisible(show_chat);
+ // Two extra separators were added to bracket the inline pushpin bar at
+ // the start of the layout, so the credits/chat separator indices shift by 2.
+ if (separators_.size() >= 7) {
+ separators_[4]->setVisible(show_credits);
+ separators_[5]->setVisible(show_chat);
}
}
diff --git a/fincept-qt/src/ui/navigation/ToolBar.h b/fincept-qt/src/ui/navigation/ToolBar.h
index e02800473..e45dfbe58 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.h
+++ b/fincept-qt/src/ui/navigation/ToolBar.h
@@ -10,6 +10,8 @@
namespace fincept::ui {
+class PushpinBar;
+
/// Combined toolbar: File/Navigate/View/Help menus + branding + clock + user info + logout.
/// Replaces both ToolBar and NavigationBar in a single row.
class ToolBar : public QWidget {
@@ -19,6 +21,8 @@ class ToolBar : public QWidget {
void refresh_user_display();
+ PushpinBar* pushpin_bar() const { return pushpin_bar_; }
+
signals:
void navigate_to(const QString& tab_id);
void dock_command(const QString& action, const QString& primary, const QString& secondary);
@@ -50,6 +54,7 @@ class ToolBar : public QWidget {
QLabel* fincept_label_ = nullptr;
CommandBar* command_bar_ = nullptr;
+ PushpinBar* pushpin_bar_ = nullptr;
void refresh_theme();
void apply_responsive_layout(int width);
diff --git a/fincept-qt/src/ui/theme/StyleSheets.cpp b/fincept-qt/src/ui/theme/StyleSheets.cpp
index 0b8dcfa5a..a2d5fdcbc 100644
--- a/fincept-qt/src/ui/theme/StyleSheets.cpp
+++ b/fincept-qt/src/ui/theme/StyleSheets.cpp
@@ -316,12 +316,17 @@ QString crypto_trading_styles() {
"#cryptoChart { background: %2; border: 1px solid %3; }"
"#cryptoChartHeader { background: %8; border-bottom: 1px solid %3; }"
"#cryptoChartTitle { color: %12; font-weight: 700; font-size: 11px; "
- " letter-spacing: 0.5px; background: transparent; border: none; }"
- "#cryptoTfBtn { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 2px 8px; "
- " font-size: 11px; font-weight: 700; }"
- "#cryptoTfBtn:hover { color: %7; }"
- "#cryptoTfBtn[active=\"true\"] { color: %12; border-bottom-color: %12; }"
+ " letter-spacing: 0.8px; background: transparent; border: none; }"
+ "#cryptoTfBtn { background: transparent; color: %7; border: none; "
+ " border-bottom: 2px solid transparent; padding: 4px 10px; "
+ " font-size: 11px; font-weight: 700; letter-spacing: 0.5px; }"
+ "#cryptoTfBtn:hover { color: %4; background: %13; }"
+ "#cryptoTfBtn[active=\"true\"] { color: %12; border-bottom-color: %12; "
+ " background: %16; }"
+ "#cryptoChartOhlc { background: rgba(8,8,8,220); color: %4; "
+ " border: 1px solid %10; border-radius: 4px; "
+ " padding: 8px 12px; font-family: 'Consolas','Courier New',monospace; "
+ " min-width: 130px; }"
/* ── Order book ── */
"#cryptoOrderBook { background: %2; border: 1px solid %3; }"
@@ -340,85 +345,182 @@ QString crypto_trading_styles() {
"#cryptoOrderEntry { background: %2; border: 1px solid %3; }"
"#cryptoOeHeader { background: %8; border-bottom: 1px solid %3; }"
"#cryptoOeTitle { color: %12; font-weight: 700; font-size: 11px; "
- " letter-spacing: 0.5px; background: transparent; border: none; }"
- "#cryptoOeMode { font-weight: 700; font-size: 11px; letter-spacing: 0.5px; "
+ " letter-spacing: 0.8px; background: transparent; border: none; }"
+ "#cryptoOeMode { font-weight: 700; font-size: 10px; letter-spacing: 0.8px; "
+ " padding: 2px 8px; border-radius: 8px; }"
+ "#cryptoOeMode[mode=\"paper\"] { color: %15; background: %17; border: 1px solid %19; }"
+ "#cryptoOeMode[mode=\"live\"] { color: %11; background: %18; border: 1px solid %20; }"
+
+ /* Account / breakdown card */
+ "#cryptoOeCard, #cryptoOeBreakdown { background: %1; border: 1px solid %3; "
+ " border-radius: 4px; }"
+ "#cryptoOeKvLabel { color: %9; font-size: 10px; font-weight: 700; "
+ " letter-spacing: 0.7px; background: transparent; border: none; }"
+ "#cryptoOeKvValue { color: %4; font-size: 12px; font-weight: 700; "
+ " background: transparent; border: none; }"
+ "#cryptoOeKvValueAccent { color: %14; font-size: 13px; font-weight: 700; "
+ " background: transparent; border: none; }"
+ "#cryptoOeKvValueDim { color: %7; font-size: 12px; font-weight: 600; "
" background: transparent; border: none; }"
- "#cryptoOeMode[mode=\"paper\"] { color: %15; }"
- "#cryptoOeMode[mode=\"live\"] { color: %11; }"
-
- "#cryptoBuyTab { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 4px 0; "
- " font-size: 12px; font-weight: 700; }"
- "#cryptoBuyTab:hover { color: %15; }"
- "#cryptoBuyTab[active=\"true\"] { color: %15; border-bottom-color: %15; }"
- "#cryptoSellTab { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 4px 0; "
- " font-size: 12px; font-weight: 700; }"
- "#cryptoSellTab:hover { color: %11; }"
- "#cryptoSellTab[active=\"true\"] { color: %11; border-bottom-color: %11; }"
-
- "#cryptoOeTypeBtn { background: transparent; color: %6; border: none; "
- " border-bottom: 2px solid transparent; padding: 1px 6px; "
- " font-size: 10px; font-weight: 700; }"
- "#cryptoOeTypeBtn:hover { color: %7; }"
- "#cryptoOeTypeBtn[active=\"true\"] { color: %4; border-bottom-color: %12; }"
- "#cryptoOeLabel { color: %7; font-size: 11px; font-weight: 700; "
- " letter-spacing: 0.5px; background: transparent; border: none; }"
+ /* BUY / SELL side tabs — full pill buttons rather than the old underline. */
+ "#cryptoBuyTab { background: %2; color: %7; border: 1px solid %3; "
+ " padding: 8px 0; font-size: 12px; font-weight: 700; letter-spacing: 1px; "
+ " border-top-left-radius: 4px; border-bottom-left-radius: 4px; "
+ " border-right: none; }"
+ "#cryptoBuyTab:hover { color: %15; background: %17; }"
+ "#cryptoBuyTab[active=\"true\"] { color: %1; background: %15; "
+ " border-color: %15; }"
+ "#cryptoSellTab { background: %2; color: %7; border: 1px solid %3; "
+ " padding: 8px 0; font-size: 12px; font-weight: 700; letter-spacing: 1px; "
+ " border-top-right-radius: 4px; border-bottom-right-radius: 4px; }"
+ "#cryptoSellTab:hover { color: %11; background: %18; }"
+ "#cryptoSellTab[active=\"true\"] { color: %1; background: %11; "
+ " border-color: %11; }"
+
+ "#cryptoOeTypeBtn { background: %1; color: %7; border: 1px solid %3; "
+ " border-right: none; padding: 6px 0; "
+ " font-size: 10px; font-weight: 700; letter-spacing: 0.5px; }"
+ "#cryptoOeTypeBtn:hover { color: %4; background: %13; }"
+ "#cryptoOeTypeBtn[active=\"true\"] { color: %12; background: %16; "
+ " border-color: %10; }"
+
+ "#cryptoOeLabel { color: %9; font-size: 10px; font-weight: 700; "
+ " letter-spacing: 0.8px; background: transparent; border: none; "
+ " padding-bottom: 2px; }"
"#cryptoOeInput { background: %1; border: 1px solid %3; color: %4; "
- " padding: 3px 6px; font-size: 12px; }"
- "#cryptoOeInput:focus { border-color: %5; }"
- "#cryptoOeInput:disabled { color: %9; }"
- "#cryptoOePctBtn { background: %8; color: %7; border: 1px solid %3; "
- " font-size: 10px; font-weight: 700; padding: 0 4px; }"
- "#cryptoOePctBtn:hover { color: %4; background: %13; }"
-
+ " padding: 7px 10px; font-size: 13px; font-weight: 600; "
+ " selection-background-color: %13; }"
+ "#cryptoOeInput:focus { border-color: %12; }"
+ "#cryptoOeInput:disabled { color: %9; background: %2; }"
+ "#cryptoOeInput[invalid=\"true\"] { border-color: %11; }"
+ "#cryptoOeInputWrap { background: transparent; border: none; }"
+ "#cryptoOeUnit { background: %2; color: %9; border: 1px solid %3; "
+ " border-left: none; font-size: 11px; font-weight: 700; "
+ " letter-spacing: 0.5px; padding: 0 6px; }"
+
+ "#cryptoOePctBtn { background: %1; color: %7; border: 1px solid %3; "
+ " font-size: 11px; font-weight: 700; padding: 5px 0; }"
+ "#cryptoOePctBtn:hover { color: %12; background: %13; border-color: %10; }"
+ "#cryptoOePctBtn:pressed { background: %16; color: %12; }"
+
+ "#cryptoOeSpinBox, #cryptoOeCombo { background: %1; border: 1px solid %3; "
+ " color: %4; padding: 6px 10px; font-size: 12px; font-weight: 700; "
+ " selection-background-color: %13; }"
+ "#cryptoOeSpinBox:focus, #cryptoOeCombo:focus { border-color: %12; }"
+ "#cryptoOeCombo::drop-down { border: none; width: 18px; }"
+ "#cryptoOeCombo QAbstractItemView { background: %2; color: %4; "
+ " border: 1px solid %3; selection-background-color: %13; }"
+
+ "#cryptoOeStatus { font-size: 11px; font-weight: 600; "
+ " background: transparent; border: 1px solid %3; "
+ " border-radius: 3px; padding: 6px 8px; }"
+ "#cryptoOeStatus[severity=\"error\"] { color: %11; background: %18; "
+ " border-color: %20; }"
+ "#cryptoOeStatus[severity=\"warning\"] { color: %12; background: %16; "
+ " border-color: %10; }"
+ "#cryptoOeStatus[severity=\"info\"] { color: %4; background: %13; }"
+ /* Back-compat for old [error=true] callers */
+ "#cryptoOeStatus[error=\"true\"] { color: %11; background: %18; border-color: %20; }"
+
+ "#cryptoBuySubmit { background: %15; color: %1; "
+ " border: 1px solid %15; padding: 12px 8px; "
+ " font-weight: 800; font-size: 14px; letter-spacing: 1px; "
+ " border-radius: 4px; }"
+ "#cryptoBuySubmit:hover { background: %19; color: %15; border-color: %19; }"
+ "#cryptoBuySubmit:pressed { background: %15; color: %1; }"
+ "#cryptoSellSubmit { background: %11; color: %1; "
+ " border: 1px solid %11; padding: 12px 8px; "
+ " font-weight: 800; font-size: 14px; letter-spacing: 1px; "
+ " border-radius: 4px; }"
+ "#cryptoSellSubmit:hover { background: %20; color: %11; border-color: %20; }"
+ "#cryptoSellSubmit:pressed { background: %11; color: %1; }"
+
+ "#cryptoOeSubmitSubtitle { color: %9; font-size: 10px; font-weight: 600; "
+ " letter-spacing: 0.4px; background: transparent; border: none; "
+ " padding: 2px 4px 0 4px; }"
+
+ "#cryptoAdvToggle { background: transparent; color: %7; border: none; "
+ " font-size: 10px; font-weight: 700; letter-spacing: 0.6px; "
+ " padding: 4px 0; text-align: left; }"
+ "#cryptoAdvToggle:hover { color: %12; }"
+
+ /* Legacy aliases — kept so any other code referencing the old
+ IDs continues to render. */
"#cryptoOeBalance { color: %14; font-size: 12px; font-weight: 700; "
" background: transparent; border: none; }"
"#cryptoOeMarketPrice { color: %6; font-size: 11px; background: transparent; border: none; }"
"#cryptoOeCost { color: %6; font-size: 11px; background: transparent; border: none; }"
- "#cryptoOeStatus { font-size: 11px; background: transparent; border: none; }"
- "#cryptoOeStatus[error=\"true\"] { color: %11; }"
-
- "#cryptoBuySubmit { background: %17; color: %15; "
- " border: 1px solid %19; padding: 8px; font-weight: 700; font-size: 13px; }"
- "#cryptoBuySubmit:hover { background: %15; color: %1; }"
- "#cryptoSellSubmit { background: %18; color: %11; "
- " border: 1px solid %20; padding: 8px; font-weight: 700; font-size: 13px; }"
- "#cryptoSellSubmit:hover { background: %11; color: %4; }"
-
- "#cryptoAdvToggle { background: transparent; color: %6; border: none; "
- " font-size: 10px; font-weight: 700; letter-spacing: 0.5px; padding: 2px 0; }"
- "#cryptoAdvToggle:hover { color: %7; }"
/* ── Bottom panel ── */
"#cryptoBottomPanel { background: %2; border: 1px solid %3; }"
"#cryptoBottomTabs::pane { border: none; background: %2; }"
- "#cryptoBottomTabs QTabBar::tab { background: transparent; color: %6; "
- " padding: 3px 10px; border: none; border-bottom: 2px solid transparent; "
- " font-size: 11px; font-weight: 700; letter-spacing: 0.5px; }"
- "#cryptoBottomTabs QTabBar::tab:selected { color: %12; border-bottom-color: %12; }"
- "#cryptoBottomTabs QTabBar::tab:hover:!selected { color: %7; }"
-
- "#cryptoBottomTable { background: %1; border: none; color: %4; font-size: 12px; }"
- "#cryptoBottomTable::item { padding: 0 4px; border-bottom: 1px solid %3; }"
+ "#cryptoBottomTabs QTabBar { background: %8; border-bottom: 1px solid %3; }"
+ "#cryptoBottomTabs QTabBar::tab { background: transparent; color: %7; "
+ " padding: 7px 14px; border: none; border-bottom: 2px solid transparent; "
+ " font-size: 11px; font-weight: 700; letter-spacing: 0.6px; "
+ " min-width: 60px; }"
+ "#cryptoBottomTabs QTabBar::tab:selected { color: %12; "
+ " border-bottom-color: %12; background: %2; }"
+ "#cryptoBottomTabs QTabBar::tab:hover:!selected { color: %4; background: %13; }"
+ "#cryptoBottomStack { background: %1; border: none; }"
+
+ "#cryptoBottomTable { background: %1; border: none; color: %4; "
+ " font-size: 12px; gridline-color: transparent; "
+ " selection-background-color: %13; selection-color: %4; }"
+ "#cryptoBottomTable::item { padding: 0 8px; border: none; }"
+ "#cryptoBottomTable::item:hover { background: %13; }"
+ "#cryptoBottomTable::item:selected { background: %13; color: %4; }"
+ "#cryptoBottomTable QHeaderView { background: %2; }"
"#cryptoBottomTable QHeaderView::section { background: %2; color: %9; "
- " font-size: 11px; font-weight: 700; border: none; border-bottom: 1px solid %3; padding: 0 4px; }"
+ " font-size: 10px; font-weight: 700; letter-spacing: 0.5px; "
+ " border: none; border-bottom: 1px solid %3; padding: 6px 8px; }"
+ "#cryptoBottomTable QHeaderView::section:first { padding-left: 12px; }"
+ "#cryptoBottomTable QScrollBar:vertical { background: %2; width: 8px; margin: 0; }"
+ "#cryptoBottomTable QScrollBar::handle:vertical { background: %3; min-height: 24px; "
+ " border-radius: 3px; }"
+ "#cryptoBottomTable QScrollBar::handle:vertical:hover { background: %10; }"
+ "#cryptoBottomTable QScrollBar::add-line:vertical, "
+ "#cryptoBottomTable QScrollBar::sub-line:vertical { height: 0; }"
+ "#cryptoBottomTable QScrollBar:horizontal { background: %2; height: 8px; margin: 0; }"
+ "#cryptoBottomTable QScrollBar::handle:horizontal { background: %3; min-width: 24px; "
+ " border-radius: 3px; }"
+ "#cryptoBottomTable QScrollBar::handle:horizontal:hover { background: %10; }"
+ "#cryptoBottomTable QScrollBar::add-line:horizontal, "
+ "#cryptoBottomTable QScrollBar::sub-line:horizontal { width: 0; }"
"#cryptoCancelBtn { background: %18; color: %11; "
- " border: 1px solid %20; padding: 1px 6px; font-size: 10px; font-weight: 700; }"
- "#cryptoCancelBtn:hover { background: %11; color: %4; }"
-
- "#cryptoInfoRow { border-bottom: 1px solid %3; }"
- "#cryptoInfoLabel { color: %7; font-size: 11px; font-weight: 700; "
- " letter-spacing: 0.5px; background: transparent; border: none; }"
- "#cryptoInfoValue { color: %4; font-size: 12px; font-weight: 700; "
+ " border: 1px solid %20; border-radius: 3px; padding: 0; "
+ " min-width: 22px; min-height: 22px; max-width: 22px; max-height: 22px; "
+ " font-size: 12px; font-weight: 700; }"
+ "#cryptoCancelBtn:hover { background: %11; color: %1; border-color: %11; }"
+ "#cryptoCancelBtn:pressed { background: %20; color: %4; }"
+
+ "#cryptoEmptyHost { background: %1; }"
+ "#cryptoEmptyState { color: %9; font-size: 12px; font-weight: 600; "
+ " letter-spacing: 0.4px; background: transparent; border: none; "
+ " padding: 24px; }"
+
+ /* Card-grid layout used by MARKET and STATS tabs. */
+ "#cryptoCardHost { background: %1; }"
+ "#cryptoCard { background: %2; border: 1px solid %3; border-radius: 4px; }"
+ "#cryptoCard:hover { border-color: %10; }"
+ "#cryptoCardLabel { color: %9; font-size: 10px; font-weight: 700; "
+ " letter-spacing: 0.8px; background: transparent; border: none; }"
+ "#cryptoCardValue { color: %4; font-size: 16px; font-weight: 700; "
" background: transparent; border: none; }"
-
- "#cryptoStatRow { border-bottom: 1px solid %3; }"
- "#cryptoStatLabel { color: %7; font-size: 11px; font-weight: 700; "
- " letter-spacing: 0.5px; background: transparent; border: none; }"
- "#cryptoStatValue { color: %4; font-size: 13px; font-weight: 700; "
+ "#cryptoCardValue[pnl=\"positive\"] { color: %15; }"
+ "#cryptoCardValue[pnl=\"negative\"] { color: %11; }"
+ "#cryptoCardValue[pnl=\"neutral\"] { color: %4; }"
+
+ /* Legacy aliases — kept so older callers still match. */
+ "#cryptoInfoLabel { color: %9; font-size: 10px; font-weight: 700; "
+ " letter-spacing: 0.8px; background: transparent; border: none; }"
+ "#cryptoInfoValue { color: %4; font-size: 16px; font-weight: 700; "
+ " background: transparent; border: none; }"
+ "#cryptoStatLabel { color: %9; font-size: 10px; font-weight: 700; "
+ " letter-spacing: 0.8px; background: transparent; border: none; }"
+ "#cryptoStatValue { color: %4; font-size: 16px; font-weight: 700; "
" background: transparent; border: none; }"
"#cryptoStatValue[pnl=\"positive\"] { color: %15; }"
"#cryptoStatValue[pnl=\"negative\"] { color: %11; }"
diff --git a/updates.json b/updates.json
index 46d02cff0..18249170c 100644
--- a/updates.json
+++ b/updates.json
@@ -3,25 +3,25 @@
"schema-version": 2,
"updates": {
"windows-x64": {
- "latest-version": "4.0.2",
- "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.2/FinceptTerminal-4.0.2-windows-x64-setup.exe",
+ "latest-version": "4.0.3",
+ "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-windows-x64-setup.exe",
"sha256": "30fb95ca95d06e5813585d87cf010bddf2f81f10240e1d17b629bb042100314c",
- "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2",
- "changelog": "Fincept Terminal v4.0.2 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2"
+ "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3",
+ "changelog": "Fincept Terminal v4.0.3 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3"
},
"linux-x64": {
- "latest-version": "4.0.2",
- "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.2/FinceptTerminal-4.0.2-linux-x64-setup.run",
+ "latest-version": "4.0.3",
+ "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-linux-x64-setup.run",
"sha256": "4c88df8f008700cc595f5adb2a0b019ea03b5998eded27f6239b018ac05c2338",
- "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2",
- "changelog": "Fincept Terminal v4.0.2 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2"
+ "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3",
+ "changelog": "Fincept Terminal v4.0.3 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3"
},
"macos-arm64": {
- "latest-version": "4.0.2",
- "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.2/FinceptTerminal-4.0.2-macos-arm64-setup.dmg",
+ "latest-version": "4.0.3",
+ "download-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-macos-arm64-setup.dmg",
"sha256": "65e24154ee6558b182257c7f6004a3f00f0db9605daa33dbc07bf7122cf9a046",
- "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2",
- "changelog": "Fincept Terminal v4.0.2 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.2"
+ "open-url": "https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3",
+ "changelog": "Fincept Terminal v4.0.3 \u2014 see release notes at https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3"
}
}
}