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.

version 4.4.0 update

tilakpatel22931494a8e4fc
diff --git a/.gitattributes b/.gitattributes
index 486a23256..2800e7343 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1,17 @@
*.zip filter=lfs diff=lfs merge=lfs -text
+
+# ── Auto-update manifest: byte-exact, never line-ending normalised ───────────
+# The updater verifies an Ed25519 detached signature (updates.json.sig) over
+# the bytes of updates.json AS SERVED. Any CRLF↔LF translation by Git — on
+# checkout, on a Windows clone, or via a core.autocrlf setting — changes those
+# bytes and the signature check fails, which the client treats as a tampered
+# manifest and refuses to update. -text pins both files to their committed
+# bytes on every platform. Do not remove.
+updates.json -text
+updates.json.sig -text
+
+# ── Shell scripts must stay LF ───────────────────────────────────────────────
+# .github/scripts/*.sh run on Linux/macOS runners. A CRLF copy committed from
+# a Windows checkout (core.autocrlf=false) fails there with
+# "/usr/bin/env: 'bash\r': No such file or directory".
+*.sh text eol=lf
diff --git a/.github/scripts/check_version_drift.sh b/.github/scripts/check_version_drift.sh
new file mode 100644
index 000000000..2f0c17e01
--- /dev/null
+++ b/.github/scripts/check_version_drift.sh
@@ -0,0 +1,65 @@
+#!/usr/bin/env bash
+# ─────────────────────────────────────────────────────────────────────────────
+# check_version_drift.sh — assert the packaging metadata agrees with CMake.
+#
+# The single source of truth is fincept-qt/CMakeLists.txt:
+# project(FinceptTerminal VERSION X.Y.Z ...)
+# The release workflows parse it correctly, but every file under
+# fincept-qt/packaging/ carries an independent hand-written copy (flatpak
+# manifest + metainfo, AppImageBuilder, appdata, installer licence). A stale
+# copy ships a bundle whose advertised version disagrees with the binary, which
+# breaks the auto-updater's version comparison.
+#
+# RULE: a packaging file that mentions any X.Y.Z version at all must mention
+# the CURRENT one somewhere. Files legitimately list *historical* releases
+# (<release version="4.1.0"> …), so "contains no other version" would be wrong;
+# "contains the current version" catches the file-stuck-on-the-old-release case
+# without false-positiving on changelog history.
+#
+# Usage: check_version_drift.sh [repo-root] (default: cwd)
+# ─────────────────────────────────────────────────────────────────────────────
+set -uo pipefail
+
+ROOT="${1:-.}"
+CMAKELISTS="${ROOT}/fincept-qt/CMakeLists.txt"
+PKG_DIR="${ROOT}/fincept-qt/packaging"
+
+if [ ! -f "$CMAKELISTS" ]; then
+ echo "::error::${CMAKELISTS} not found"
+ exit 1
+fi
+
+VERSION=$(grep -Eo 'project\(FinceptTerminal VERSION [0-9]+\.[0-9]+\.[0-9]+' "$CMAKELISTS" | awk '{print $3}')
+if [ -z "$VERSION" ]; then
+ echo "::error::could not parse project(FinceptTerminal VERSION ...) from ${CMAKELISTS}"
+ exit 1
+fi
+echo "CMake project version: ${VERSION}"
+
+if [ ! -d "$PKG_DIR" ]; then
+ echo "::warning::${PKG_DIR} not found — nothing to check"
+ exit 0
+fi
+
+# Shipped metadata only. Prose docs (*.md, licence text) are excluded: they
+# quote unrelated versions (e.g. the bundled Python 3.11.9) and would
+# false-positive without adding any signal the metadata files don't already
+# carry.
+DRIFT=0
+while IFS= read -r f; do
+ grep -Iq . "$f" 2>/dev/null || continue # skip binaries
+ versions=$(grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' "$f" 2>/dev/null | sort -u)
+ [ -n "$versions" ] || continue # no version at all
+ if ! printf '%s\n' "$versions" | grep -qx "$VERSION"; then
+ echo "::error::version drift in ${f#"$ROOT"/}: mentions $(printf '%s' "$versions" | tr '\n' ' ') but never ${VERSION}"
+ DRIFT=1
+ fi
+done < <(find "$PKG_DIR" -type f \
+ \( -name '*.xml' -o -name '*.yml' -o -name '*.yaml' -o -name '*.json' \
+ -o -name '*.desktop' -o -name '*.spec' -o -name '*.plist' \))
+
+if [ "$DRIFT" -ne 0 ]; then
+ echo "::error::packaging metadata is out of sync with CMakeLists.txt (${VERSION}). Update the files listed above."
+ exit 1
+fi
+echo "Packaging metadata is consistent with ${VERSION}."
diff --git a/.github/scripts/ci_app_checks.sh b/.github/scripts/ci_app_checks.sh
new file mode 100644
index 000000000..00673375d
--- /dev/null
+++ b/.github/scripts/ci_app_checks.sh
@@ -0,0 +1,170 @@
+#!/usr/bin/env bash
+# ─────────────────────────────────────────────────────────────────────────────
+# ci_app_checks.sh — run the terminal's headless checks against a built binary.
+#
+# ci_app_checks.sh selftests <binary> [profile] [per-test-timeout-seconds]
+# ci_app_checks.sh smoke <binary> [profile] [timeout-seconds]
+#
+# WHY THIS IS A SCRIPT AND NOT INLINE YAML
+# The self-test flag list used to be hand-copied into build-cpp.yml. It
+# drifted: main.cpp dispatched 10 --selftest-* flags while CI ran 9, so
+# --selftest-live-table was never executed anywhere. One implementation,
+# called from every workflow, cannot drift between workflows — and the list
+# itself is *discovered from the binary* (see below) rather than typed here.
+#
+# FLAG DISCOVERY
+# Preferred: `<binary> --selftest-list` prints one flag per line. That flag
+# does not exist yet (see the CROSS-FILE note in the CI report / the header
+# comment in main.cpp's self-test dispatch loop) so this script probes for it
+# safely and falls back to the hard-coded list below. The probe first greps
+# the binary image for the literal string: if main.cpp has no --selftest-list
+# handler, an unknown flag would make the app boot the *full GUI* instead of
+# printing a list, so we must never run the probe blind.
+#
+# PROFILE ISOLATION
+# Every run passes --profile <name> (default "ci"). --selftest-paper and
+# --selftest-fno-algo drive the paper-trading and F&O engines against
+# whatever profile they are given; without this they would mutate a real
+# user profile's database. Never remove it.
+# ─────────────────────────────────────────────────────────────────────────────
+set -uo pipefail
+
+# Self-tests registered in src/app/main.cpp's dispatch loop. FALLBACK ONLY —
+# used when the binary does not support --selftest-list. --dump-tools is
+# deliberately absent: it is a catalog dump, not a pass/fail check.
+FALLBACK_SELFTESTS="
+--selftest-tools
+--selftest-feeds
+--selftest-dock-layout
+--selftest-live-table
+--selftest-fno-algo
+--selftest-universe-scan
+--selftest-paper
+--selftest-portfolio-monitor
+--selftest-portfolio-replication
+--selftest-arena
+"
+
+usage() {
+ echo "usage: $0 selftests|smoke <binary> [profile] [timeout-seconds]" >&2
+ exit 2
+}
+
+# Portable timeout: GNU `timeout` is absent on macOS runners and unreliable in
+# git-bash. Run in the background, poll, SIGKILL on overrun. Returns 124 on
+# timeout, otherwise the child's exit status.
+run_with_timeout() {
+ local secs="$1"; shift
+ # </dev/null: the self-test loop feeds the flag list on stdin via a
+ # heredoc — a child that reads stdin would swallow the remaining flags.
+ "$@" </dev/null &
+ local pid=$! waited=0
+ while kill -0 "$pid" 2>/dev/null; do
+ if [ "$waited" -ge "$secs" ]; then
+ echo "::error::timed out after ${secs}s: $*" >&2
+ kill -9 "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ return 124
+ fi
+ sleep 1
+ waited=$((waited + 1))
+ done
+ wait "$pid"
+}
+
+# Echo the discovered self-test flags, one per line. Falls back silently.
+discover_selftests() {
+ local bin="$1" listing rc=1
+ if grep -aq -- '--selftest-list' "$bin" 2>/dev/null; then
+ listing="$(mktemp)"
+ if run_with_timeout 60 "$bin" --selftest-list >"$listing" 2>/dev/null; then
+ rc=0
+ fi
+ if [ "$rc" -eq 0 ] && [ -s "$listing" ]; then
+ # Accept only if EVERY non-empty line is a --selftest-* flag; any
+ # other output means we caught log noise, not a flag listing.
+ local cleaned
+ cleaned="$(tr -d '\r' <"$listing" | sed '/^[[:space:]]*$/d')"
+ if [ -n "$cleaned" ] && ! printf '%s\n' "$cleaned" | grep -qvE '^--selftest-[a-z0-9-]+$'; then
+ echo "discovered $(printf '%s\n' "$cleaned" | wc -l) self-test(s) via --selftest-list" >&2
+ printf '%s\n' "$cleaned"
+ rm -f "$listing"
+ return 0
+ fi
+ fi
+ rm -f "$listing"
+ fi
+ echo "::warning::${bin##*/} has no usable --selftest-list — using this script's fallback list (it can drift from main.cpp; see CROSS-FILE note)" >&2
+ printf '%s\n' "$FALLBACK_SELFTESTS" | sed '/^[[:space:]]*$/d'
+}
+
+MODE="${1:-}"; BINARY="${2:-}"
+[ -n "$MODE" ] && [ -n "$BINARY" ] || usage
+if [ ! -f "$BINARY" ]; then
+ echo "::error::binary not found: $BINARY" >&2
+ exit 1
+fi
+[ -x "$BINARY" ] || chmod +x "$BINARY" 2>/dev/null || true
+
+# Headless defaults. Windows keeps its native 'windows' platform plugin: the
+# staged tree's qt.conf pins Prefix=. so only bundled plugins resolve, and the
+# release smoke gate already proves that path works.
+case "$(uname -s 2>/dev/null || echo unknown)" in
+ MINGW*|MSYS*|CYGWIN*) : ;;
+ *) export QT_QPA_PLATFORM="${QT_QPA_PLATFORM:-offscreen}" ;;
+esac
+export QT_OPENGL="${QT_OPENGL:-software}"
+export QTWEBENGINE_DISABLE_SANDBOX="${QTWEBENGINE_DISABLE_SANDBOX:-1}"
+export QTWEBENGINE_CHROMIUM_FLAGS="${QTWEBENGINE_CHROMIUM_FLAGS:---disable-gpu --no-sandbox --disable-gpu-compositing}"
+
+case "$MODE" in
+ selftests)
+ PROFILE="${3:-ci}"
+ PER_TEST_TIMEOUT="${4:-300}"
+ echo "Self-tests: binary=$BINARY profile=$PROFILE platform=${QT_QPA_PLATFORM:-<native>}"
+ FAILED=""
+ PASSED=0
+ while IFS= read -r flag; do
+ [ -n "$flag" ] || continue
+ echo "::group::self-test $flag"
+ echo "Running: $BINARY --profile $PROFILE $flag"
+ if run_with_timeout "$PER_TEST_TIMEOUT" "$BINARY" --profile "$PROFILE" "$flag"; then
+ PASSED=$((PASSED + 1))
+ echo "PASS $flag"
+ else
+ status=$?
+ echo "::error::self-test $flag failed (exit $status)"
+ FAILED="${FAILED} ${flag}"
+ fi
+ echo "::endgroup::"
+ done <<EOF
+$(discover_selftests "$BINARY")
+EOF
+ if [ -n "$FAILED" ]; then
+ echo "::error::self-tests failed:${FAILED}"
+ exit 1
+ fi
+ echo "All ${PASSED} self-test(s) passed."
+ ;;
+
+ smoke)
+ PROFILE="${3:-ci-smoke}"
+ TIMEOUT="${4:-600}"
+ echo "Smoke test: binary=$BINARY profile=$PROFILE platform=${QT_QPA_PLATFORM:-<native>}"
+ echo "Walks every registered screen; the last '[Smoke] >>> constructing <id>'"
+ echo "line names the screen if the process dies."
+ if run_with_timeout "$TIMEOUT" "$BINARY" --smoke-test --profile "$PROFILE"; then
+ echo "Smoke test passed — every screen constructed on this runtime."
+ else
+ status=$?
+ if [ "$status" -eq 124 ]; then
+ echo "::error::Smoke test hung (>${TIMEOUT}s) — likely a blocking dialog or a stalled screen"
+ else
+ echo "::error::Smoke test failed (exit $status) — see the last '[Smoke] >>> constructing <id>' line above"
+ fi
+ exit 1
+ fi
+ ;;
+
+ *) usage ;;
+esac
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index 9f1ebd29a..8c7012ee6 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -38,12 +38,18 @@ jobs:
cmake_extra: "-A ARM64"
# ---- Linux x64 ----
+ # qt_arch is NOT empty: this leg used to skip install-qt-action and
+ # apt-install qt6-base-dev, which is Qt 6.2.4 on ubuntu-22.04 while
+ # CMakeLists.txt pins Qt 6.8 (FINCEPT_QT_PIN_MODE defaults to MINOR
+ # → find_package(Qt6 6.8 REQUIRED)). The job could never configure.
+ # release.yml:588-595 documents that exact trap and installs Qt via
+ # aqt; the fix had simply never been mirrored here.
- os: ubuntu-22.04
arch: x64
platform: Linux
artifact: FinceptTerminal-Linux-x64
exe: FinceptTerminal
- qt_arch: ""
+ qt_arch: linux_gcc_64
cmake_extra: ""
# ---- macOS ARM64 (Apple Silicon) ----
@@ -88,6 +94,13 @@ jobs:
# Ubuntu 22.04's default g++ is 11.4, but CMakeLists.txt requires GCC 12.3+.
# Install gcc-12/g++-12 from the Ubuntu Toolchain PPA (pre-enabled on
# ubuntu-22.04 runners) and pin it via CC/CXX for the rest of the job.
+ #
+ # NO apt Qt packages here — ubuntu-22.04 ships Qt 6.2 and CMakeLists.txt
+ # pins Qt 6.8, so `qt6-base-dev` & friends made find_package(Qt6 6.8)
+ # fail outright. Qt comes from install-qt-action below (as it already
+ # did on Windows/macOS, and as release.yml does on all three platforms).
+ # The XCB / GL / fontconfig system libs stay: Qt's xcb platform plugin
+ # links against them at build time and loads them at runtime.
- name: Install system dependencies (Linux)
if: runner.os == 'Linux'
run: |
@@ -97,16 +110,17 @@ jobs:
cmake ninja-build gcc-12 g++-12 \
libssl-dev \
libsecret-1-dev \
- qt6-base-dev qt6-base-private-dev \
- qt6-tools-dev qt6-tools-dev-tools \
- libqt6charts6-dev libqt6websockets6-dev \
- qt6-multimedia-dev libqt6multimediawidgets6 \
- libqt6svg6-dev libqt6concurrent6 \
libgl1-mesa-dev libglu1-mesa-dev \
- libxkbcommon-dev libxkbcommon-x11-0 \
- libxcb-cursor0 libxcb-icccm4 libxcb-image0 \
- libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 \
- libxcb-xinerama0 libxcb-xkb1 \
+ libxkbcommon-dev libxkbcommon-x11-0 libxkbcommon-x11-dev \
+ libxcb-cursor0 libxcb-cursor-dev \
+ libxcb-icccm4 libxcb-icccm4-dev \
+ libxcb-image0 libxcb-image0-dev \
+ libxcb-keysyms1 libxcb-keysyms1-dev \
+ libxcb-randr0 \
+ libxcb-render-util0 libxcb-render-util0-dev \
+ libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev \
+ libxcb-xinerama0 libxcb-xinerama0-dev libxcb-xkb1 \
+ libdbus-1-dev libfontconfig1-dev libfreetype6-dev \
pkg-config zip
echo "CC=gcc-12" >> "$GITHUB_ENV"
echo "CXX=g++-12" >> "$GITHUB_ENV"
@@ -151,9 +165,10 @@ jobs:
fi
echo "static zlib confirmed: $ZLIB_DIR/lib/zlib.lib"
- # ---- Qt6 target (Windows/macOS) ----
+ # ---- Qt6 target (all platforms) ----
+ # Linux is no longer excluded — see the matrix comment on the Linux
+ # entry: apt Qt 6.2 can never satisfy CMakeLists' 6.8 pin.
- name: Install Qt6
- if: runner.os != 'Linux'
uses: jurplel/install-qt-action@v4
with:
version: ${{ env.QT_VERSION }}
@@ -180,13 +195,37 @@ jobs:
shell: bash
run: pip install yt-dlp
+ # ---- Strip dangling Qt SQL driver plugin CMake configs (aqt workaround) ----
+ # aqtinstall ships Qt6Sql's MySQL/PSQL/ODBC/Mimer *DriverPlugin CMake
+ # target files but NOT the plugin binaries they reference, so
+ # find_package(Qt6 ... Sql) aborts at CONFIGURE time ("references the
+ # file .../libqsqlmysql.so but this file does not exist"). We only use
+ # SQLite. Mirrors release.yml's identically-named step in all three of
+ # its build jobs. MUST run before "Configure CMake".
+ - name: Remove dangling Qt SQL driver plugin CMake configs
+ shell: bash
+ run: |
+ set -euo pipefail
+ SQL_CMAKE="${QT_ROOT_DIR}/lib/cmake/Qt6Sql"
+ if [ -d "${SQL_CMAKE}" ]; then
+ for drv in QMYSQLDriverPlugin QPSQLDriverPlugin QODBCDriverPlugin QMimerSQLDriverPlugin; do
+ rm -fv "${SQL_CMAKE}/Qt6${drv}"*.cmake || true
+ done
+ else
+ echo "::warning::${SQL_CMAKE} not found — skipping SQL plugin config cleanup"
+ fi
+
# ---- Configure CMake ----
+ # CMAKE_PREFIX_PATH is required now that Qt comes from install-qt-action
+ # instead of apt (it was absent while this leg relied on system Qt).
- name: Configure CMake (Linux)
if: runner.os == 'Linux'
working-directory: fincept-qt
run: |
cmake -B build -G Ninja \
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
+ -DOPENSSL_ROOT_DIR=/usr \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
-DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON \
@@ -281,47 +320,28 @@ jobs:
# needs no FUSE mount or codesigning. Skipped on cross-compiled targets
# (Windows arm64, macOS x64) whose binaries can't execute on the host
# runner's architecture. timeout-minutes bounds any unexpected hang.
+ #
+ # The flag list used to be spelled out here and DRIFTED: main.cpp
+ # dispatches 10 --selftest-* flags, this loop listed 9, so
+ # --selftest-live-table ran nowhere. It now lives in
+ # .github/scripts/ci_app_checks.sh, which prefers `--selftest-list` from
+ # the binary itself and is shared with release.yml and build-pr.yml.
- name: Run self-tests (headless)
if: "!(matrix.platform == 'Windows' && matrix.arch == 'arm64') && !(matrix.platform == 'macOS' && matrix.arch == 'x64')"
shell: bash
working-directory: fincept-qt
- timeout-minutes: 10
- env:
- QT_QPA_PLATFORM: offscreen
+ timeout-minutes: 25
run: |
set -euo pipefail
if [ "${{ runner.os }}" == "Windows" ]; then
BINARY="build/Release/${{ matrix.exe }}"
- elif [ "${{ runner.os }}" == "macOS" ]; then
- if [ -f "build/${{ matrix.exe }}" ]; then
- BINARY="build/${{ matrix.exe }}"
- elif [ -f "build/${{ matrix.exe }}.app/Contents/MacOS/${{ matrix.exe }}" ]; then
- BINARY="build/${{ matrix.exe }}.app/Contents/MacOS/${{ matrix.exe }}"
- else
- BINARY="build/${{ matrix.exe }}"
- fi
+ elif [ "${{ runner.os }}" == "macOS" ] && [ ! -f "build/${{ matrix.exe }}" ]; then
+ BINARY="build/${{ matrix.exe }}.app/Contents/MacOS/${{ matrix.exe }}"
else
BINARY="build/${{ matrix.exe }}"
fi
- # No umbrella --selftest exists; run each registered self-test in its
- # own process (shared DB/state would cross-contaminate one process).
- for f in \
- --selftest-tools \
- --selftest-feeds \
- --selftest-dock-layout \
- --selftest-fno-algo \
- --selftest-universe-scan \
- --selftest-paper \
- --selftest-portfolio-monitor \
- --selftest-portfolio-replication \
- --selftest-arena; do
- echo "::group::self-test $f"
- # --profile ci isolates each run in a fresh, migrated DB so a
- # cached/drifted default profile can't cause false failures.
- echo "Running: $BINARY --profile ci $f (QT_QPA_PLATFORM=$QT_QPA_PLATFORM)"
- "$BINARY" --profile ci "$f"
- echo "::endgroup::"
- done
+ export LD_LIBRARY_PATH="${QT_ROOT_DIR}/lib:${LD_LIBRARY_PATH:-}"
+ bash ../.github/scripts/ci_app_checks.sh selftests "$BINARY" ci
# ---- Package: Windows (windeployqt + manual DLL sweep) ----
- name: Package (Windows)
@@ -646,7 +666,14 @@ jobs:
mkdir -p "${APP_BUNDLE}/Contents/MacOS"
cp "build/${{ matrix.exe }}" "${APP_BUNDLE}/Contents/MacOS/${{ matrix.exe }}"
chmod +x "${APP_BUNDLE}/Contents/MacOS/${{ matrix.exe }}"
- cat > "${APP_BUNDLE}/Contents/Info.plist" <<'PLIST'
+ # Version comes from CMakeLists.txt, never a literal — a hardcoded
+ # 4.3.0 here shipped a bundle whose CFBundleVersion disagreed with
+ # the binary the moment the project version moved, which breaks the
+ # auto-updater's version comparison. Heredoc delimiter is unquoted
+ # (<<PLIST, not <<'PLIST') so ${VERSION} interpolates.
+ VERSION=$(grep -Eo 'project\(FinceptTerminal VERSION [0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt | awk '{print $3}')
+ [ -n "${VERSION}" ] || { echo "::error::Could not parse VERSION from CMakeLists.txt"; exit 1; }
+ cat > "${APP_BUNDLE}/Contents/Info.plist" <<PLIST
<?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>
@@ -654,8 +681,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.3.0</string>
- <key>CFBundleVersion</key><string>4.3.0</string>
+ <key>CFBundleShortVersionString</key><string>${VERSION}</string>
+ <key>CFBundleVersion</key><string>${VERSION}</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
diff --git a/.github/workflows/build-pr.yml b/.github/workflows/build-pr.yml
new file mode 100644
index 000000000..353e36ed0
--- /dev/null
+++ b/.github/workflows/build-pr.yml
@@ -0,0 +1,282 @@
+name: PR Build (compile + self-test gate)
+
+# ─────────────────────────────────────────────────────────────────────────────
+# WHY THIS WORKFLOW EXISTS
+# Until this file was added, NOTHING compiled the C++ on a pull request or on
+# a push to main: build-cpp.yml and lint.yml are workflow_dispatch-only, and
+# the only pull_request workflows were arch-ratchet.yml (a Python string
+# counter) and pr-gate.yml (label policy). That meant /WX and -Werror — which
+# CMakeLists.txt enables whenever $CI is set — were first enforced on the
+# `v*` tag push, on three platforms at once, in release.yml. Every release
+# was a blind roll.
+#
+# This job builds the same configuration release.yml builds, on the same
+# three platforms, and runs the headless self-tests. It is the gate that
+# makes a tag push boring.
+# ─────────────────────────────────────────────────────────────────────────────
+
+on:
+ pull_request:
+ paths:
+ - 'fincept-qt/**'
+ - '.github/workflows/build-pr.yml'
+ - '.github/scripts/ci_app_checks.sh'
+ - '.github/scripts/check_version_drift.sh'
+ push:
+ branches: [main]
+ paths:
+ - 'fincept-qt/**'
+ - '.github/workflows/build-pr.yml'
+ - '.github/scripts/ci_app_checks.sh'
+ - '.github/scripts/check_version_drift.sh'
+ workflow_dispatch:
+
+# One build per PR (or per main push). A new push cancels the in-flight run —
+# these are 30–60 minute jobs and superseded runs are wasted runner time.
+concurrency:
+ group: build-pr-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+env:
+ BUILD_TYPE: Release
+ QT_VERSION: "6.8.3"
+ # Mirrors release.yml — qtserialport is required because the qtpositioning
+ # NMEA plugin links Qt6SerialPort.
+ QT_MODULES: "qtcharts qtwebsockets qtmultimedia qtwebengine qtwebchannel qtpositioning qtserialport"
+ APP_NAME: FinceptTerminal
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
+
+jobs:
+ # ── Cheap gates first — these finish in seconds and fail fast ──────────────
+ version-consistency:
+ name: Version consistency
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ # CMakeLists.txt project(... VERSION x.y.z) is the source of truth; the
+ # flatpak / AppImage / appdata manifests each carry a hand-written copy.
+ # A stale copy ships a bundle whose CFBundleVersion / appdata version
+ # disagrees with the binary and breaks the updater's version compare.
+ - name: Check packaging metadata matches CMakeLists.txt
+ run: bash .github/scripts/check_version_drift.sh .
+
+ build:
+ name: ${{ matrix.platform }} build + self-tests
+ needs: version-consistency
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: windows-2022
+ platform: Windows
+ qt_arch: win64_msvc2022_64
+ - os: ubuntu-22.04
+ platform: Linux
+ qt_arch: linux_gcc_64
+ - os: macos-15
+ platform: macOS
+ qt_arch: clang_64
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 120
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ submodules: recursive
+ fetch-depth: 1
+
+ # ccache for the two platforms release.yml caches. Same action, same key
+ # shape, so a cache warmed by a main-branch run is restored by PR runs.
+ # Windows has no compiler cache here for the same reason release.yml has
+ # none: that job uses the Visual Studio generator, and CMake's
+ # CMAKE_<LANG>_COMPILER_LAUNCHER (how ccache/sccache is injected) is
+ # honoured only by the Makefile and Ninja generators.
+ - name: Set up ccache
+ if: runner.os != 'Windows'
+ uses: hendrikmuhs/ccache-action@v1
+ with:
+ key: ${{ runner.os == 'Linux' && 'linux-x64-release' || 'macos-arm64-release' }}-${{ env.QT_VERSION }}
+ max-size: 500M
+
+ # ── Windows: OpenSSL (dynamic) + zlib (STATIC) via vcpkg ──────────────
+ # Copied from release.yml. The forward-slash normalisation and the
+ # zs.lib → zlib.lib alias are load-bearing: without them FindZLIB falls
+ # through to a stray system zlib and the exe imports an unbundled z.dll
+ # (the v4.1.0 launch failure).
+ - name: Install OpenSSL + zlib (Windows)
+ if: runner.os == 'Windows'
+ shell: bash
+ run: |
+ set -euo pipefail
+ VCPKG_ROOT="${VCPKG_INSTALLATION_ROOT:-C:/vcpkg}"
+ VCPKG_ROOT="${VCPKG_ROOT//\\//}"
+ "$VCPKG_ROOT/vcpkg" install openssl:x64-windows zlib:x64-windows-static-md --no-print-usage
+ OPENSSL_DIR="$VCPKG_ROOT/installed/x64-windows"
+ ZLIB_DIR="$VCPKG_ROOT/installed/x64-windows-static-md"
+ echo "OPENSSL_ROOT_DIR=$OPENSSL_DIR" >> "$GITHUB_ENV"
+ echo "ZLIB_ROOT=$ZLIB_DIR" >> "$GITHUB_ENV"
+ if [ ! -f "$ZLIB_DIR/lib/zlib.lib" ]; then
+ ALT="$(ls "$ZLIB_DIR"/lib/z*.lib 2>/dev/null | head -1 || true)"
+ [ -n "$ALT" ] && cp "$ALT" "$ZLIB_DIR/lib/zlib.lib"
+ fi
+ [ -f "$ZLIB_DIR/lib/zlib.lib" ] || { echo "::error::static zlib archive not found"; exit 1; }
+
+ # ── Linux: toolchain + XCB/GL system libs ─────────────────────────────
+ # ubuntu-22.04 ships g++ 11.4; CMakeLists.txt requires GCC 12.3+.
+ # Deliberately NO apt Qt packages — ubuntu-22.04 has Qt 6.2 and
+ # CMakeLists pins Qt 6.8 (FINCEPT_QT_PIN_MODE defaults to MINOR).
+ - name: Install system dependencies (Linux)
+ if: runner.os == 'Linux'
+ run: |
+ sudo add-apt-repository universe -y
+ sudo apt-get update -qq
+ sudo apt-get install -y \
+ cmake ninja-build gcc-12 g++-12 \
+ libssl-dev \
+ libgl1-mesa-dev libglu1-mesa-dev \
+ libxkbcommon-dev libxkbcommon-x11-0 libxkbcommon-x11-dev \
+ libxcb-cursor0 libxcb-cursor-dev \
+ libxcb-icccm4 libxcb-icccm4-dev \
+ libxcb-image0 libxcb-image0-dev \
+ libxcb-keysyms1 libxcb-keysyms1-dev \
+ libxcb-randr0 \
+ libxcb-render-util0 libxcb-render-util0-dev \
+ libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev \
+ libxcb-xinerama0 libxcb-xinerama0-dev libxcb-xkb1 \
+ libdbus-1-dev libfontconfig1-dev libfreetype6-dev \
+ pkg-config
+ echo "CC=gcc-12" >> "$GITHUB_ENV"
+ echo "CXX=g++-12" >> "$GITHUB_ENV"
+
+ - name: Install build tools (macOS)
+ if: runner.os == 'macOS'
+ run: brew install ninja cmake || brew upgrade ninja cmake || true
+
+ - name: Install Qt ${{ env.QT_VERSION }}
+ uses: jurplel/install-qt-action@v4
+ with:
+ version: ${{ env.QT_VERSION }}
+ arch: ${{ matrix.qt_arch }}
+ modules: ${{ env.QT_MODULES }}
+ cache: true
+ cache-key-prefix: qt-${{ matrix.platform }}-pr
+
+ # aqtinstall ships Qt6Sql's MySQL/PSQL/ODBC/Mimer *DriverPlugin CMake
+ # target files but not the plugin binaries, so find_package(Qt6 ... Sql)
+ # aborts at configure time. We only use SQLite. (release.yml does the
+ # same in all three of its build jobs.)
+ - name: Remove dangling Qt SQL driver plugin CMake configs
+ shell: bash
+ run: |
+ set -euo pipefail
+ SQL_CMAKE="${QT_ROOT_DIR}/lib/cmake/Qt6Sql"
+ if [ -d "${SQL_CMAKE}" ]; then
+ for drv in QMYSQLDriverPlugin QPSQLDriverPlugin QODBCDriverPlugin QMimerSQLDriverPlugin; do
+ rm -fv "${SQL_CMAKE}/Qt6${drv}"*.cmake || true
+ done
+ else
+ echo "::warning::${SQL_CMAKE} not found — skipping SQL plugin config cleanup"
+ fi
+
+ # ── Configure ─────────────────────────────────────────────────────────
+ # CRITICAL: this must be the RELEASE-STYLE configuration, i.e. unity
+ # build ON (FINCEPT_DEV_BUILD=OFF, the default). The local `win-dev`
+ # preset turns unity OFF, so a win-dev-shaped PR build would silently
+ # miss the exact class of error this gate exists to catch: unity
+ # concatenates ~20 .cpp files into one TU, so two file-scope symbols
+ # with the same name in the same batch become a hard redefinition error
+ # that appears ONLY on a unity build — and adding or removing a source
+ # file re-batches everything after it. GitHub Actions always sets
+ # CI=true, so CMakeLists.txt also turns on /WX (MSVC) and -Werror
+ # (GCC/Clang) here, exactly as it does on the release path.
+ - name: Configure (Windows)
+ if: runner.os == 'Windows'
+ shell: bash
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ cmake -B build \
+ -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
+ -DOPENSSL_ROOT_DIR="${OPENSSL_ROOT_DIR}" \
+ -DZLIB_ROOT="${ZLIB_ROOT}" \
+ -DZLIB_USE_STATIC_LIBS=ON \
+ -DFINCEPT_DEV_BUILD=OFF \
+ -DFINCEPT_BUILD_INSTALLER=OFF
+
+ - name: Configure (Linux)
+ if: runner.os == 'Linux'
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ cmake -B build -G Ninja \
+ -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
+ -DOPENSSL_ROOT_DIR=/usr \
+ -DCMAKE_C_COMPILER_LAUNCHER=ccache \
+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DFINCEPT_DEV_BUILD=OFF \
+ -DFINCEPT_BUILD_INSTALLER=OFF
+
+ - name: Configure (macOS)
+ if: runner.os == 'macOS'
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ cmake -B build -G Ninja \
+ -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
+ -DCMAKE_OSX_ARCHITECTURES=arm64 \
+ -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \
+ -DCMAKE_C_COMPILER_LAUNCHER=ccache \
+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DFINCEPT_DEV_BUILD=OFF \
+ -DFINCEPT_BUILD_INSTALLER=OFF
+
+ # Guard against someone "fixing" a slow PR build by flipping the preset
+ # to the dev configuration — that would quietly delete the unity-batch
+ # coverage this workflow exists to provide. The build dir is always
+ # fresh on a runner, so the generated unity sources are proof.
+ - name: Assert unity build is ON
+ shell: bash
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ if ! find build -name 'unity_*_cxx.cxx' -print -quit | grep -q .; then
+ echo "::error::No unity sources generated — this build is NOT the release-style configuration."
+ echo "::error::CI must build with CMAKE_UNITY_BUILD=ON (FINCEPT_DEV_BUILD=OFF) or it cannot catch unity-batch symbol collisions."
+ exit 1
+ fi
+ echo "Unity build confirmed (batch size 20, matching the release path)."
+
+ - name: Build
+ shell: bash
+ working-directory: fincept-qt
+ run: |
+ cmake --build build --config ${{ env.BUILD_TYPE }} \
+ --parallel $(nproc 2>/dev/null || sysctl -n hw.logicalcpu 2>/dev/null || echo 4)
+
+ # ── Headless self-tests ───────────────────────────────────────────────
+ # The flag list is discovered from the binary (--selftest-list) with a
+ # hard-coded fallback — see .github/scripts/ci_app_checks.sh. Never
+ # hand-maintain the list in YAML: it drifted once already and
+ # --selftest-live-table ran nowhere for months.
+ - name: Run self-tests (headless)
+ shell: bash
+ working-directory: fincept-qt
+ timeout-minutes: 25
+ run: |
+ set -euo pipefail
+ if [ "${{ runner.os }}" = "Windows" ]; then
+ BINARY="build/Release/${{ env.APP_NAME }}.exe"
+ elif [ -f "build/${{ env.APP_NAME }}.app/Contents/MacOS/${{ env.APP_NAME }}" ]; then
+ BINARY="build/${{ env.APP_NAME }}.app/Contents/MacOS/${{ env.APP_NAME }}"
+ else
+ BINARY="build/${{ env.APP_NAME }}"
+ fi
+ export LD_LIBRARY_PATH="${QT_ROOT_DIR}/lib:${LD_LIBRARY_PATH:-}"
+ bash ../.github/scripts/ci_app_checks.sh selftests "$BINARY" ci
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 0ae4cbb32..f4c08dc82 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -1,12 +1,38 @@
name: Lint
+# ─────────────────────────────────────────────────────────────────────────────
+# Runs on pull requests (incremental, gating) and on demand (full tree).
+#
+# It used to be workflow_dispatch-only, and even when run by hand the
+# clang-tidy job could not fail: .clang-tidy sets `WarningsAsErrors: ''` and
+# the invocation passed no --warnings-as-errors, so it exited 0 no matter what
+# it printed — while xargs-ing 1,032 files through a single-threaded process
+# (hours). The PR path below is therefore INCREMENTAL: only the .cpp files the
+# PR actually changed, in parallel, with a narrow high-signal check set that is
+# adoptable today. The full-tree sweep stays available via "Run workflow".
+# ─────────────────────────────────────────────────────────────────────────────
on:
- # Manual-only — lint never runs automatically on push/tag/PR.
- # Trigger from the Actions tab via "Run workflow".
+ pull_request:
+ paths:
+ - 'fincept-qt/src/**'
+ - 'fincept-qt/CMakeLists.txt'
+ - 'fincept-qt/.clang-tidy'
+ - 'fincept-qt/.clang-format'
+ - 'fincept-qt/.cppcheck-suppressions'
+ - '.github/workflows/lint.yml'
workflow_dispatch:
+concurrency:
+ group: lint-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
+ QT_VERSION: "6.8.3"
+ QT_MODULES: "qtcharts qtwebsockets qtmultimedia qtwebengine qtwebchannel qtpositioning qtserialport"
jobs:
# ── clang-format ─────────────────────────────────────────────────────────────
@@ -15,6 +41,8 @@ jobs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
- name: Install clang-format
run: |
@@ -22,7 +50,31 @@ jobs:
sudo apt-get install -y clang-format-18
sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-18 100
- - name: Check formatting
+ # PR path: only the lines this PR touched. A whole-file --dry-run would
+ # flag pre-existing formatting in untouched lines and fail PRs for code
+ # their author never wrote — the fastest way to get a check deleted.
+ - name: Check formatting of changed lines
+ if: github.event_name == 'pull_request'
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ GCF="$(command -v git-clang-format-18 || command -v git-clang-format || true)"
+ if [ -z "${GCF}" ]; then
+ echo "::warning::git-clang-format not available — skipping the diff-scoped format check"
+ exit 0
+ fi
+ BASE="${{ github.event.pull_request.base.sha }}"
+ DIFF=$("${GCF}" --binary clang-format --diff --commit "${BASE}" -- 'src/*.cpp' 'src/*.h' || true)
+ case "${DIFF}" in
+ *"no modified files"*|*"did not modify"*|"") echo "Changed lines are correctly formatted."; exit 0 ;;
+ esac
+ echo "${DIFF}"
+ echo "::error::Formatting differs from .clang-format on lines this PR touched. Run: git-clang-format --commit ${BASE}"
+ exit 1
+
+ # Full-tree sweep — manual runs only.
+ - name: Check formatting (full tree)
+ if: github.event_name == 'workflow_dispatch'
working-directory: fincept-qt
run: |
# Parentheses required: without them -o has lower precedence than the
@@ -37,6 +89,8 @@ jobs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
- name: Install dependencies
run: |
@@ -44,18 +98,41 @@ jobs:
sudo apt-get install -y \
clang-18 clang-tidy-18 \
cmake ninja-build \
- qt6-base-dev qt6-base-private-dev \
- qt6-tools-dev qt6-tools-dev-tools \
- qt6-charts-dev \
- qt6-multimedia-dev libqt6multimediawidgets6 \
- libqt6svg6-dev \
- libqt6sql6-dev libqt6websockets6-dev \
- libqt6concurrent6-dev libqt6printsupport6-dev \
- libgl1-mesa-dev
+ libgl1-mesa-dev libglu1-mesa-dev \
+ libxkbcommon-dev libxkbcommon-x11-dev \
+ libxcb-cursor-dev libxcb-icccm4-dev libxcb-image0-dev \
+ libxcb-keysyms1-dev libxcb-render-util0-dev libxcb-shape0-dev \
+ libxcb-sync-dev libxcb-xfixes0-dev libxcb-xinerama0-dev \
+ libdbus-1-dev libfontconfig1-dev libfreetype6-dev libssl-dev
sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-18 100
sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-18 100
sudo update-alternatives --install /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-18 100
+ # Qt 6.8.3 from aqt, NOT apt: ubuntu-24.04 ships Qt 6.4 and CMakeLists.txt
+ # pins Qt 6.8 (FINCEPT_QT_PIN_MODE=MINOR), so the previous apt-based
+ # configure could never produce a compile database.
+ - name: Install Qt ${{ env.QT_VERSION }}
+ uses: jurplel/install-qt-action@v4
+ with:
+ version: ${{ env.QT_VERSION }}
+ arch: linux_gcc_64
+ modules: ${{ env.QT_MODULES }}
+ cache: true
+ cache-key-prefix: qt-linux-x64-lint
+
+ - name: Remove dangling Qt SQL driver plugin CMake configs
+ run: |
+ set -euo pipefail
+ SQL_CMAKE="${QT_ROOT_DIR}/lib/cmake/Qt6Sql"
+ if [ -d "${SQL_CMAKE}" ]; then
+ for drv in QMYSQLDriverPlugin QPSQLDriverPlugin QODBCDriverPlugin QMimerSQLDriverPlugin; do
+ rm -fv "${SQL_CMAKE}/Qt6${drv}"*.cmake || true
+ done
+ fi
+
+ # FINCEPT_DEV_BUILD=ON turns the unity build OFF. That is REQUIRED here:
+ # with unity ON the compile database contains only unity_*.cxx entries,
+ # so clang-tidy cannot find a compile command for an individual .cpp.
- name: Configure (generate compile_commands.json)
working-directory: fincept-qt
run: |
@@ -63,20 +140,67 @@ jobs:
-G Ninja \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_COMPILER=clang++ \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
+ -DFINCEPT_DEV_BUILD=ON \
-DFINCEPT_BUILD_INSTALLER=OFF \
-DDEPLOY_QT=OFF
- - name: Run clang-tidy
+ # moc/uic output must exist before clang-tidy parses anything that
+ # includes it, otherwise every hit is a bogus "file not found".
+ - name: Generate moc/uic sources
+ working-directory: fincept-qt
+ run: cmake --build build --target FinceptTerminal_autogen -j "$(nproc)" || echo "::warning::autogen target unavailable — clang-tidy may report missing generated headers"
+
+ # ── PR path: incremental + GATING ───────────────────────────────────────
+ # Narrow, high-signal checks only. bugprone-easily-swappable-parameters,
+ # -narrowing-conversions and -branch-clone are excluded: thousands of
+ # pre-existing hits, near-zero defect yield.
+ - name: clang-tidy (changed files, gating)
+ if: github.event_name == 'pull_request'
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ BASE="${{ github.event.pull_request.base.sha }}"
+ CHECKS='-*,bugprone-*,concurrency-*,performance-move-const-arg,-bugprone-easily-swappable-parameters,-bugprone-narrowing-conversions,-bugprone-branch-clone'
+ git diff --name-only --diff-filter=ACMR "${BASE}" HEAD -- 'fincept-qt/src/**/*.cpp' \
+ | sed 's|^fincept-qt/||' > /tmp/changed.txt || true
+ # Keep only files the compile database actually knows about (a brand
+ # new .cpp not yet added to CMakeLists.txt has no compile command).
+ : > /tmp/tidy_files.txt
+ while IFS= read -r f; do
+ [ -n "$f" ] || continue
+ [ -f "$f" ] || continue
+ grep -q "\"$(basename "$f")\"\|/$f\"" build/compile_commands.json 2>/dev/null && echo "$f" >> /tmp/tidy_files.txt || \
+ echo "::warning::$f not in compile_commands.json — skipped by clang-tidy"
+ done < /tmp/changed.txt
+ COUNT=$(wc -l < /tmp/tidy_files.txt | tr -d ' ')
+ if [ "${COUNT}" = "0" ]; then
+ echo "No changed .cpp files with compile commands — nothing to analyse."
+ exit 0
+ fi
+ echo "Analysing ${COUNT} changed file(s) with: ${CHECKS}"
+ xargs -a /tmp/tidy_files.txt -P "$(nproc)" -n 1 \
+ clang-tidy -p build \
+ --checks="${CHECKS}" \
+ --warnings-as-errors="${CHECKS}" \
+ --quiet \
+ --extra-arg=-std=c++20
+ echo "clang-tidy clean on changed files."
+
+ # ── Manual path: full tree, advisory ────────────────────────────────────
+ - name: clang-tidy (full tree, advisory)
+ if: github.event_name == 'workflow_dispatch'
working-directory: fincept-qt
run: |
find src -name "*.cpp" | grep -v "/moc_" | grep -v "/qrc_" | sort | \
- xargs clang-tidy \
+ xargs -P "$(nproc)" -n 1 clang-tidy \
--config-file=.clang-tidy \
-p build \
+ --quiet \
--extra-arg=-std=c++20 \
- 2>&1
- echo "clang-tidy complete."
+ 2>&1 || true
+ echo "clang-tidy sweep complete (advisory — .clang-tidy sets WarningsAsErrors: '')."
# ── datahub-discipline ───────────────────────────────────────────────────────
# Enforces DataHub rules D1 and D4 (see fincept-qt/CLAUDE.md §D):
@@ -94,15 +218,22 @@ jobs:
- name: Check screens/ does not call PythonRunner directly
working-directory: fincept-qt
run: |
- if grep -rn --include='*.cpp' --include='*.h' \
- 'PythonRunner::instance()\.run(' src/screens/; then
+ # GRANDFATHER LIST — two pre-existing D1 violations, present when this
+ # check first became a PR gate. New violations anywhere else fail the
+ # build; editing one of these files for an unrelated reason does not.
+ # Delete an entry here the moment its file is migrated to a Producer.
+ ALLOW='src/screens/equity_research/EquityResearchScreen.cpp|src/screens/portfolio/views/EconomicsView.cpp'
+ violations=$(grep -rn --include='*.cpp' --include='*.h' \
+ 'PythonRunner::instance()\.run(' src/screens/ | grep -vE "^(${ALLOW})" || true)
+ if [ -n "$violations" ]; then
+ echo "$violations"
echo ""
echo "::error::D1 violation — screens must not call PythonRunner directly."
echo "Route through a Producer registered with DataHub."
echo "See fincept-qt/DATAHUB_ARCHITECTURE.md §4."
exit 1
fi
- echo "D1 — screens are clean."
+ echo "D1 — screens are clean (excluding the 2 grandfathered files)."
- name: Check screens/ does not call deprecated service fetch_* APIs
working-directory: fincept-qt
@@ -129,6 +260,8 @@ jobs:
echo "D4 — screens are clean."
# ── cppcheck ─────────────────────────────────────────────────────────────────
+ # Unchanged from its manual-only form — it already gates via
+ # --error-exitcode=1 and runs the whole tree in a couple of minutes.
cppcheck:
name: cppcheck
runs-on: ubuntu-24.04
diff --git a/.github/workflows/nightly-sanitizers.yml b/.github/workflows/nightly-sanitizers.yml
new file mode 100644
index 000000000..7e8a97e9e
--- /dev/null
+++ b/.github/workflows/nightly-sanitizers.yml
@@ -0,0 +1,155 @@
+name: Nightly Sanitizers (ASan + UBSan)
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Nightly AddressSanitizer + UndefinedBehaviorSanitizer build of the Linux
+# target, exercised by the headless self-tests and the all-screens smoke walk.
+#
+# WHY THOSE TWO AS THE PAYLOAD
+# They are deterministic, headless, need no display / GPU / network / API
+# key, and between them they construct every screen and drive the tool
+# registry, feed parsing, dock layout, the F&O + paper engines, the
+# portfolio monitor/replication paths and the arena. That is the largest
+# slice of real execution CI can reach without a human — exactly what a
+# sanitizer wants. A use-after-free or a signed-overflow that only bites a
+# user at runtime shows up here with a full stack trace.
+#
+# WHY NIGHTLY AND NOT PER-PR
+# The instrumented build is ~2x slower to compile and the tests run 2-5x
+# slower; putting it on every PR would make the gate unaffordable and it
+# would get disabled. Nightly catches regressions within a day.
+# ─────────────────────────────────────────────────────────────────────────────
+on:
+ schedule:
+ - cron: '17 3 * * *' # 03:17 UTC daily
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: nightly-sanitizers
+ cancel-in-progress: true
+
+env:
+ QT_VERSION: "6.8.3"
+ QT_MODULES: "qtcharts qtwebsockets qtmultimedia qtwebengine qtwebchannel qtpositioning qtserialport"
+ APP_NAME: FinceptTerminal
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
+
+jobs:
+ asan-ubsan:
+ name: Linux ASan + UBSan
+ runs-on: ubuntu-22.04
+ timeout-minutes: 240
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ submodules: recursive
+ fetch-depth: 1
+
+ - name: Set up ccache
+ uses: hendrikmuhs/ccache-action@v1
+ with:
+ key: linux-x64-asan-${{ env.QT_VERSION }}
+ max-size: 800M
+
+ # Same toolchain as the release Linux job (GCC 12.3+ is a CMakeLists
+ # requirement); libasan6/libubsan1 ship with gcc-12.
+ - name: Install system dependencies
+ run: |
+ sudo add-apt-repository universe -y
+ sudo apt-get update -qq
+ sudo apt-get install -y \
+ cmake ninja-build gcc-12 g++-12 \
+ libssl-dev \
+ libgl1-mesa-dev libglu1-mesa-dev \
+ libxkbcommon-dev libxkbcommon-x11-0 libxkbcommon-x11-dev \
+ libxcb-cursor0 libxcb-cursor-dev \
+ libxcb-icccm4 libxcb-icccm4-dev \
+ libxcb-image0 libxcb-image0-dev \
+ libxcb-keysyms1 libxcb-keysyms1-dev \
+ libxcb-randr0 \
+ libxcb-render-util0 libxcb-render-util0-dev \
+ libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev \
+ libxcb-xinerama0 libxcb-xinerama0-dev libxcb-xkb1 \
+ libdbus-1-dev libfontconfig1-dev libfreetype6-dev \
+ pkg-config
+ echo "CC=gcc-12" >> "$GITHUB_ENV"
+ echo "CXX=g++-12" >> "$GITHUB_ENV"
+
+ - name: Install Qt ${{ env.QT_VERSION }}
+ uses: jurplel/install-qt-action@v4
+ with:
+ version: ${{ env.QT_VERSION }}
+ arch: linux_gcc_64
+ modules: ${{ env.QT_MODULES }}
+ cache: true
+ cache-key-prefix: qt-linux-x64-asan
+
+ - name: Remove dangling Qt SQL driver plugin CMake configs
+ run: |
+ set -euo pipefail
+ SQL_CMAKE="${QT_ROOT_DIR}/lib/cmake/Qt6Sql"
+ if [ -d "${SQL_CMAKE}" ]; then
+ for drv in QMYSQLDriverPlugin QPSQLDriverPlugin QODBCDriverPlugin QMimerSQLDriverPlugin; do
+ rm -fv "${SQL_CMAKE}/Qt6${drv}"*.cmake || true
+ done
+ fi
+
+ # RelWithDebInfo keeps -O2 (the tests would crawl at -O0) and -g so the
+ # sanitizer reports carry file:line. -fno-sanitize-recover=undefined
+ # makes UBSan ABORT instead of printing and continuing — otherwise a
+ # nightly "failure" is a log nobody reads.
+ - name: Configure (ASan + UBSan)
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ SAN_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=undefined -g"
+ cmake -B build-asan -G Ninja \
+ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
+ -DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
+ -DOPENSSL_ROOT_DIR=/usr \
+ -DCMAKE_C_COMPILER_LAUNCHER=ccache \
+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DCMAKE_C_FLAGS="${SAN_FLAGS}" \
+ -DCMAKE_CXX_FLAGS="${SAN_FLAGS}" \
+ -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \
+ -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" \
+ -DFINCEPT_DEV_BUILD=OFF \
+ -DFINCEPT_BUILD_INSTALLER=OFF
+
+ - name: Build
+ working-directory: fincept-qt
+ run: cmake --build build-asan --parallel "$(nproc)"
+
+ # detect_leaks=0: LeakSanitizer would report thousands of intentional
+ # one-shot Qt/singleton allocations and bury real findings. ASan's
+ # use-after-free / heap-overflow / stack-overflow detection — the classes
+ # that actually crash users — is unaffected.
+ - name: Self-tests under ASan + UBSan
+ working-directory: fincept-qt
+ timeout-minutes: 90
+ env:
+ QT_QPA_PLATFORM: offscreen
+ ASAN_OPTIONS: detect_leaks=0:abort_on_error=1:print_stacktrace=1:strict_string_checks=1
+ UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1
+ run: |
+ set -euo pipefail
+ export LD_LIBRARY_PATH="${QT_ROOT_DIR}/lib:${LD_LIBRARY_PATH:-}"
+ bash ../.github/scripts/ci_app_checks.sh selftests "build-asan/${{ env.APP_NAME }}" ci-asan 900
+
+ - name: All-screens smoke walk under ASan + UBSan
+ working-directory: fincept-qt
+ timeout-minutes: 60
+ env:
+ QT_QPA_PLATFORM: offscreen
+ QTWEBENGINE_DISABLE_SANDBOX: '1'
+ # Chromium ships its own allocator and trips ASan's intercepts; the
+ # smoke walk still constructs every screen, WebEngine included.
+ ASAN_OPTIONS: detect_leaks=0:abort_on_error=1:print_stacktrace=1
+ UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1
+ run: |
+ set -euo pipefail
+ export LD_LIBRARY_PATH="${QT_ROOT_DIR}/lib:${LD_LIBRARY_PATH:-}"
+ bash ../.github/scripts/ci_app_checks.sh smoke "build-asan/${{ env.APP_NAME }}" ci-asan-smoke 1800
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 254577e52..44e41b726 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -464,6 +464,86 @@ jobs:
}
Write-Host "Smoke test passed — every screen constructed on the bundled runtime."
+ # ── Headless self-tests ───────────────────────────────────────────────
+ # These never ran on the release path before: the self-test loop lived
+ # only in build-cpp.yml, which is workflow_dispatch-only. They are
+ # deterministic, headless, and exercise the tool registry, feed parsing,
+ # dock layout, F&O + paper engines, portfolio monitor/replication and
+ # the arena — i.e. logic the screen-construction smoke test never
+ # reaches. The flag list is discovered from the binary rather than
+ # hand-copied here (it drifted once: main.cpp dispatched 10 flags while
+ # CI listed 9, so --selftest-live-table ran nowhere). --profile ci keeps
+ # the paper/F&O engines off any real user profile.
+ - name: Run self-tests (headless)
+ shell: bash
+ working-directory: fincept-qt
+ timeout-minutes: 25
+ run: bash ../.github/scripts/ci_app_checks.sh selftests "build/Release/${{ env.APP_NAME }}.exe" ci
+
+ # ── Authenticode sign the application binary ──────────────────────────
+ # Runs BEFORE cpack so the signed exe is what lands in the installer
+ # payload. Without this, every Windows user hits a SmartScreen "unknown
+ # publisher" block on the primary platform — and for an app that stores
+ # broker credentials, an unsigned installer is also trivially
+ # substitutable by a phishing build.
+ #
+ # Credentials come from an Azure Key Vault code-signing certificate
+ # (AzureSignTool). Set these five repo secrets to enable signing:
+ # AZ_KV_URL vault URI, e.g. https://myvault.vault.azure.net
+ # AZ_KV_CLIENT_ID service-principal / app registration client id
+ # AZ_KV_SECRET service-principal client secret
+ # AZ_KV_CERT certificate name inside the vault
+ # AZ_TENANT Entra tenant id
+ # Optional: AZ_TIMESTAMP_URL (defaults to DigiCert's RFC-3161 server;
+ # use http://timestamp.acs.microsoft.com for Azure Trusted Signing).
+ #
+ # Absent secrets → skip with a loud warning so forks and dry runs still
+ # build. Present secrets → any failure fails the job.
+ - name: Code-sign application binary
+ shell: pwsh
+ working-directory: fincept-qt
+ env:
+ AZ_KV_URL: ${{ secrets.AZ_KV_URL }}
+ AZ_KV_CLIENT_ID: ${{ secrets.AZ_KV_CLIENT_ID }}
+ AZ_KV_SECRET: ${{ secrets.AZ_KV_SECRET }}
+ AZ_KV_CERT: ${{ secrets.AZ_KV_CERT }}
+ AZ_TENANT: ${{ secrets.AZ_TENANT }}
+ AZ_TIMESTAMP_URL: ${{ secrets.AZ_TIMESTAMP_URL }}
+ run: |
+ $ErrorActionPreference = 'Stop'
+ $secrets = @($env:AZ_KV_URL, $env:AZ_KV_CLIENT_ID, $env:AZ_KV_SECRET, $env:AZ_KV_CERT, $env:AZ_TENANT)
+ if ($secrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) {
+ Write-Host "::warning::==================== WINDOWS BUILD IS UNSIGNED ===================="
+ Write-Host "::warning::Code-signing secrets (AZ_KV_URL / AZ_KV_CLIENT_ID / AZ_KV_SECRET /"
+ Write-Host "::warning::AZ_KV_CERT / AZ_TENANT) are not set, so FinceptTerminal.exe and the"
+ Write-Host "::warning::installer will NOT be signed. Every user will hit a SmartScreen"
+ Write-Host "::warning::'unknown publisher' warning. Do not publish this as a real release."
+ Write-Host "::warning::=================================================================="
+ "FINCEPT_SIGNED=0" | Out-File -FilePath $env:GITHUB_ENV -Append
+ exit 0
+ }
+ $ts = if ([string]::IsNullOrWhiteSpace($env:AZ_TIMESTAMP_URL)) { 'http://timestamp.digicert.com' } else { $env:AZ_TIMESTAMP_URL }
+
+ dotnet tool install --global AzureSignTool
+ if ($LASTEXITCODE -ne 0) { Write-Host "::error::AzureSignTool install failed"; exit 1 }
+ $env:PATH = "$env:USERPROFILE\.dotnet\tools;$env:PATH"
+
+ # Our own build outputs. Qt's DLLs keep their upstream signatures (or
+ # lack thereof); re-signing third-party binaries buys nothing and
+ # would slow the job by minutes.
+ $targets = @('build/Release/FinceptTerminal.exe')
+ if (Test-Path 'build/Release/qgeoview.dll') { $targets += 'build/Release/qgeoview.dll' }
+
+ foreach ($t in $targets) {
+ Write-Host "Signing $t"
+ azuresigntool sign `
+ -kvu $env:AZ_KV_URL -kvi $env:AZ_KV_CLIENT_ID -kvs $env:AZ_KV_SECRET `
+ -kvc $env:AZ_KV_CERT -kvt $env:AZ_TENANT `
+ -tr $ts -td sha256 -fd sha256 -v $t
+ if ($LASTEXITCODE -ne 0) { Write-Host "::error::Signing failed for $t"; exit 1 }
+ }
+ "FINCEPT_SIGNED=1" | Out-File -FilePath $env:GITHUB_ENV -Append
+
# ── Generate Installer ────────────────────────────────────────────────
- name: Generate Installer (CPack IFW)
shell: bash
@@ -475,6 +555,59 @@ jobs:
cpack -G IFW -C ${{ env.BUILD_TYPE }} --verbose
ls -lh ${{ env.APP_NAME }}-*-setup* 2>/dev/null || ls -lh *.exe 2>/dev/null || true
+ # ── Authenticode sign the installer + verify the signature ────────────
+ # The installer is the file users actually download, so it needs its own
+ # signature (the signed payload inside is invisible to SmartScreen until
+ # after extraction). `signtool verify /pa` is the gate: when signing was
+ # supposed to happen it must succeed, and when it was skipped the run
+ # says so loudly in the job summary so an unsigned build can't ship
+ # unnoticed.
+ - name: Code-sign installer + verify
+ shell: pwsh
+ working-directory: fincept-qt/build
+ env:
+ AZ_KV_URL: ${{ secrets.AZ_KV_URL }}
+ AZ_KV_CLIENT_ID: ${{ secrets.AZ_KV_CLIENT_ID }}
+ AZ_KV_SECRET: ${{ secrets.AZ_KV_SECRET }}
+ AZ_KV_CERT: ${{ secrets.AZ_KV_CERT }}
+ AZ_TENANT: ${{ secrets.AZ_TENANT }}
+ AZ_TIMESTAMP_URL: ${{ secrets.AZ_TIMESTAMP_URL }}
+ run: |
+ $ErrorActionPreference = 'Stop'
+ $setup = Get-ChildItem -Filter "${{ env.APP_NAME }}-*-windows-x64-setup.exe" | Select-Object -First 1
+ if (-not $setup) { Write-Host "::error::installer not found for signing"; exit 1 }
+
+ # signtool ships with the Windows SDK; pick the newest x64 build.
+ $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" -ErrorAction SilentlyContinue |
+ Sort-Object FullName -Descending | Select-Object -First 1
+
+ if ($env:FINCEPT_SIGNED -ne '1') {
+ Write-Host "::warning::Installer $($setup.Name) is UNSIGNED (no code-signing secrets configured)."
+ "### :warning: Windows installer is UNSIGNED" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append
+ "``$($setup.Name)`` was built without Authenticode signing — users will see a SmartScreen 'unknown publisher' block. Configure the AZ_KV_* / AZ_TENANT secrets before publishing." | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append
+ exit 0
+ }
+
+ $ts = if ([string]::IsNullOrWhiteSpace($env:AZ_TIMESTAMP_URL)) { 'http://timestamp.digicert.com' } else { $env:AZ_TIMESTAMP_URL }
+ $env:PATH = "$env:USERPROFILE\.dotnet\tools;$env:PATH"
+ Write-Host "Signing installer: $($setup.Name)"
+ azuresigntool sign `
+ -kvu $env:AZ_KV_URL -kvi $env:AZ_KV_CLIENT_ID -kvs $env:AZ_KV_SECRET `
+ -kvc $env:AZ_KV_CERT -kvt $env:AZ_TENANT `
+ -tr $ts -td sha256 -fd sha256 -v $setup.FullName
+ if ($LASTEXITCODE -ne 0) { Write-Host "::error::Installer signing failed"; exit 1 }
+
+ if (-not $signtool) { Write-Host "::error::signtool.exe not found — cannot verify the signature"; exit 1 }
+ Write-Host "Verifying with: $($signtool.FullName) verify /pa /v"
+ & $signtool.FullName verify /pa /v $setup.FullName
+ if ($LASTEXITCODE -ne 0) { Write-Host "::error::signtool verify /pa FAILED — the installer is not trusted by the Authenticode policy"; exit 1 }
+
+ # The exe inside the payload was signed before cpack — prove it, so a
+ # signed installer can never ship an unsigned application binary.
+ & $signtool.FullName verify /pa /v (Join-Path (Get-Location) 'Release\FinceptTerminal.exe')
+ if ($LASTEXITCODE -ne 0) { Write-Host "::error::signtool verify /pa FAILED for the packaged FinceptTerminal.exe"; exit 1 }
+ Write-Host "Installer + application signatures verified."
+
# ── Validate installer PAYLOAD (not just the stage dir) ───────────────
# The smoke test above runs against build/Release — the *staged* dir,
# where every file exists. But CPack's install() rules decide what
@@ -717,6 +850,19 @@ jobs:
echo "Binary: $BINARY ($(du -sh "$BINARY" | cut -f1))"
file "$BINARY"
+ # ── Headless self-tests (build-tree binary) ───────────────────────────
+ # Run before packaging so a logic regression fails the release in ~2
+ # minutes instead of after the 15-minute AppImage/deb/rpm/IFW sequence.
+ # Flags are discovered from the binary; --profile ci keeps the paper and
+ # F&O engines off any real profile. See .github/scripts/ci_app_checks.sh.
+ - name: Run self-tests (headless)
+ working-directory: fincept-qt
+ timeout-minutes: 25
+ run: |
+ set -euo pipefail
+ export LD_LIBRARY_PATH="${QT_ROOT_DIR}/lib:${LD_LIBRARY_PATH:-}"
+ bash ../.github/scripts/ci_app_checks.sh selftests "build/${{ env.APP_NAME }}" ci
+
# ── Build self-contained AppImage ─────────────────────────────────────
# The previous release workflow ran CPack IFW on Linux but didn't bundle
# Qt at all — the installer produced a "binary + desktop file" payload
@@ -947,6 +1093,30 @@ jobs:
zsyncmake "build/${OUTPUT}" -o "build/${OUTPUT}.zsync" || true
fi
+ # ── Smoke-test the AppImage (the artifact users actually download) ────
+ # Until this step existed, the Linux artifact got ZERO runtime
+ # verification — "Verify binary" above only checks the file exists and
+ # runs `file` on it. The bug class the Windows job's closure walk and
+ # clean-PATH smoke test were built for (v4.1.0's unbundled z.dll, the
+ # WebEngine crash on first screen open) was completely uncaught here.
+ # The AppImage is self-mounting (libfuse2 is installed above), so
+ # executing it exercises the bundled Qt/OpenSSL/plugin payload exactly
+ # as an end user's machine would — including the #352 OpenSSL pairing.
+ # --smoke-test walks every screen; the '[Smoke] >>> constructing <id>'
+ # breadcrumb names the screen if it dies.
+ - name: Smoke-test AppImage
+ working-directory: fincept-qt
+ timeout-minutes: 15
+ env:
+ QT_QPA_PLATFORM: offscreen
+ QTWEBENGINE_DISABLE_SANDBOX: '1'
+ run: |
+ set -euo pipefail
+ APPIMAGE=$(ls build/${{ env.APP_NAME }}-*-linux-x64-setup.run 2>/dev/null | head -1 || true)
+ [ -n "${APPIMAGE}" ] || { echo "::error::AppImage not found for smoke test"; exit 1; }
+ chmod +x "${APPIMAGE}"
+ bash ../.github/scripts/ci_app_checks.sh smoke "${APPIMAGE}" ci-smoke 600
+
# ── Build .deb package ────────────────────────────────────────────────
- name: Build .deb package
working-directory: fincept-qt
@@ -1253,6 +1423,22 @@ jobs:
echo "Binary: $BINARY ($(du -sh "$BINARY" | cut -f1))"
lipo -info "$BINARY"
+ # ── Headless self-tests (build-tree binary) ───────────────────────────
+ # Runs before staging/macdeployqt/codesign so a logic regression fails
+ # in ~2 minutes rather than after the notarization round-trip. The
+ # signed-bundle launch check is a separate step after stapling.
+ - name: Run self-tests (headless)
+ working-directory: fincept-qt
+ timeout-minutes: 25
+ run: |
+ set -euo pipefail
+ if [ -f "build/${{ env.APP_NAME }}.app/Contents/MacOS/${{ env.APP_NAME }}" ]; then
+ BINARY="build/${{ env.APP_NAME }}.app/Contents/MacOS/${{ env.APP_NAME }}"
+ else
+ BINARY="build/${{ env.APP_NAME }}"
+ fi
+ bash ../.github/scripts/ci_app_checks.sh selftests "$BINARY" ci
+
# ── Stage .app bundle contents (Python + resources FIRST) ─────────────
# Order is critical: Python.framework and resources must be in the bundle
# BEFORE macdeployqt / codesign run. If we embed after signing, dyld on
@@ -1271,7 +1457,15 @@ jobs:
mkdir -p "${APP_BUNDLE}/Contents/MacOS"
cp "${BUILD_DIR}/${{ env.APP_NAME }}" "${APP_BUNDLE}/Contents/MacOS/${{ env.APP_NAME }}"
chmod +x "${APP_BUNDLE}/Contents/MacOS/${{ env.APP_NAME }}"
- cat > "${APP_BUNDLE}/Contents/Info.plist" <<'PLIST'
+ # Version MUST come from CMakeLists.txt, not a literal: this
+ # fallback plist used to hardcode 4.3.0, so on the fallback path
+ # the bundle advertised a CFBundleVersion that disagreed with the
+ # binary as soon as the project version moved — which breaks the
+ # auto-updater's version comparison. Note the heredoc delimiter is
+ # unquoted (<<PLIST, not <<'PLIST') so ${VERSION} interpolates.
+ VERSION=$(grep -Eo 'project\(FinceptTerminal VERSION [0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt | awk '{print $3}')
+ [ -n "${VERSION}" ] || { echo "::error::Could not parse VERSION from CMakeLists.txt"; exit 1; }
+ cat > "${APP_BUNDLE}/Contents/Info.plist" <<PLIST
<?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>
@@ -1279,8 +1473,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.3.0</string>
- <key>CFBundleVersion</key><string>4.3.0</string>
+ <key>CFBundleShortVersionString</key><string>${VERSION}</string>
+ <key>CFBundleVersion</key><string>${VERSION}</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
@@ -1994,6 +2188,32 @@ jobs:
xcrun stapler validate "${APP_BUNDLE}"
rm -f "${ZIP_PATH}" "${SUBMIT_JSON}" "${INFO_JSON}"
+ # ── Smoke-test the SIGNED bundle ──────────────────────────────────────
+ # Until this step existed, the macOS artifact got ZERO runtime
+ # verification — "Verify binary" is only `[ -f ]` plus `lipo -info`. It
+ # runs AFTER codesign + notarize + staple deliberately: launching the
+ # binary from inside the sealed bundle is the only check that proves the
+ # signature is actually loadable. That is exactly the failure mode of
+ # issue #139 (dyld SIGKILL "Code Signature Invalid" from a framework
+ # embedded after signing) — a broken seal aborts the process here
+ # instead of on a user's Mac. It also walks every screen against the
+ # macdeployqt-bundled Qt, the counterpart of the Windows clean-PATH
+ # gate. codesign --verify is re-run first so a seal break is reported as
+ # a signature error rather than an opaque crash.
+ - name: Smoke-test signed .app bundle
+ working-directory: fincept-qt
+ timeout-minutes: 15
+ env:
+ QT_QPA_PLATFORM: offscreen
+ QTWEBENGINE_DISABLE_SANDBOX: '1'
+ run: |
+ set -euo pipefail
+ APP_BUNDLE="build/${{ env.APP_NAME }}.app"
+ BINARY="${APP_BUNDLE}/Contents/MacOS/${{ env.APP_NAME }}"
+ [ -f "${BINARY}" ] || { echo "::error::signed bundle binary not found at ${BINARY}"; exit 1; }
+ codesign --verify --deep --strict --verbose=2 "${APP_BUNDLE}"
+ bash ../.github/scripts/ci_app_checks.sh smoke "${BINARY}" ci-smoke 600
+
# ── Copy signed bundle to dist/ ───────────────────────────────────────
- name: Finalize dist
working-directory: fincept-qt
@@ -2445,8 +2665,6 @@ jobs:
END_MARKER="<!-- DOWNLOAD-TABLE-END -->"
NEW_BLOCK="${START_MARKER}
- ### Option 1 — Download Installer (Recommended)
-
Latest release: **${TAG}** — [View all releases](${RELEASE_URL})
| Platform | Download | Run |
diff --git a/.gitignore b/.gitignore
index 2b4b08fb1..31f578675 100644
--- a/.gitignore
+++ b/.gitignore
@@ -83,17 +83,28 @@ logs/
.env.*.local
*.key
*.pub
+# NOTE: *.pub is repo-wide and matches PUBLIC keys too. If the auto-updater
+# ever ships its Ed25519 verification key as a file (rather than embedded in
+# C++), it will be invisible to `git add` and absent from a fresh clone —
+# add a `!` negation for that exact path at that time.
# ── Large data / ML model files ──────────────────────────────
-*.csv
-*.bin
-*.pt
-*.onnx
-*.h5
-*.pkl
-*.pickle
-*.model
-*.weights
+# SCOPED to the Python analytics tree, which is where scripts write their
+# outputs. These globs used to be repo-wide with no negations, which silently
+# dropped any committed fixture: a .csv test input a script needs, a small
+# .bin resource — invisible to `git add`, absent from a fresh clone and from
+# CI, and impossible to notice until something fails at runtime. Build trees
+# (fincept-qt/build*/) are already ignored above, so nothing generated there
+# needs a second rule.
+fincept-qt/scripts/**/*.csv
+fincept-qt/scripts/**/*.bin
+fincept-qt/scripts/**/*.pt
+fincept-qt/scripts/**/*.onnx
+fincept-qt/scripts/**/*.h5
+fincept-qt/scripts/**/*.pkl
+fincept-qt/scripts/**/*.pickle
+fincept-qt/scripts/**/*.model
+fincept-qt/scripts/**/*.weights
# ── Archives ─────────────────────────────────────────────────
*.zip
@@ -123,7 +134,12 @@ fincept-qt/uitest/build/
# ── ML training artifacts ─────────────────────────────────────
lightning_logs/
*.ckpt
-*.yaml
+# `*.yaml` was here and is DELETED: it was repo-wide with no negations, so a
+# workflow added as .github/workflows/foo.yaml, a flatpak/AppImage manifest,
+# or any other YAML config would be silently untrackable — invisible to
+# `git add` and simply missing from a fresh clone and from CI. Nothing in the
+# repo was ever tracked as .yaml (verified), and the only .yaml on disk is
+# CMakeConfigureLog.yaml inside an already-ignored build tree.
# ── Shell tree output files ───────────────────────────────────
**/tree
diff --git a/LICENSE b/LICENSE
index 67ee7d7ff..2755a3752 100644
--- a/LICENSE
+++ b/LICENSE
@@ -67,10 +67,14 @@ The Fincept Terminal software is offered under AGPL-3.0 for non-commercial
use as described above.
Fincept Data Sources and APIs are separate services subject to:
-- Commercial License: USD 10,200 / year
-- University & Academic License: USD 799 / month (20 accounts)
+- A paid Commercial License for any commercial or internal-corporate use
- Free for individual personal and educational use only
+Commercial, enterprise, and academic pricing is not currently published. It
+will be published with the forthcoming Fincept Terminal Private Edition. For
+a quote, contact [email protected]. The absence of published pricing does
+not waive or narrow the Commercial License requirement.
+
================================================================================
TRADEMARK NOTICE
================================================================================
diff --git a/README.md b/README.md
index e0609e7f2..6a9f919f4 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,11 @@
> [!IMPORTANT]
-> **Maintenance notice — June 2026**
-> Due to funding constraints, the public [Fincept Terminal](https://github.com/Fincept-Corporation/FinceptTerminal) is moving to **one update per month** and is **no longer maintained on a daily basis**. The team is now focused on a subscription-based **private edition** of the terminal and a new project, **[Quantcept](https://www.npmjs.com/package/quantcept)**. This open-source repo stays public and will not be deleted.
+> **Fincept Terminal ships in two editions.**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — the private, closed-source build for funds, family offices and research desks. 41 modules, proprietary datasets, multi-agent research, live broker routing, private dataroom, SSO and an SLA, from **$99/user/month**. This is where the team develops daily, and it is the edition to use if the terminal is how you earn.
+>
+> 📖 **This repository** — the free AGPL-3.0 open-source edition, for learning, personal use and academic research. It stays public, it will not be deleted, and it ships **one release a month**.
+>
+> [**Which one do you need? →**](#which-edition-should-you-use) · [Compare](https://fincept.in/comparison) · [Pricing](https://fincept.in/pricing)
# Fincept Terminal
@@ -26,7 +31,9 @@
State-of-the-art financial intelligence platform with institutional-grade financial analytics, AI automation, and unlimited data connectivity.
-[📥 Download](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [⚖️ License](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md) · [💬 Discussions](https://github.com/Fincept-Corporation/FinceptTerminal/discussions) · [💬 Discord](https://discord.gg/ae87a8ygbN) · [🤝 Partner](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+[📥 Download](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 Pricing](https://fincept.in/pricing) · [📖 Manual](https://fincept.in/manual) · [💬 Discussions](https://github.com/Fincept-Corporation/FinceptTerminal/discussions) · [💬 Discord](https://discord.gg/ae87a8ygbN)
+
+<sub>English · [Deutsch](docs/translations/README.de.md) · [Español](docs/translations/README.es.md) · [Français](docs/translations/README.fr.md) · [हिन्दी](docs/translations/README.hi.md) · [日本語](docs/translations/README.ja.md) · [한국어](docs/translations/README.ko.md) · [简体中文](docs/translations/README.zh-CN.md) · [繁體中文](docs/translations/README.zh-TW.md)</sub>
![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
@@ -45,239 +52,162 @@ State-of-the-art financial intelligence platform with institutional-grade financ
## About
-**Fincept Terminal v4** is a pure native C++20 desktop application. It uses **Qt6** for UI and rendering, embedded **Python** for analytics, and delivers professional terminal-class performance in a single native binary.
-
----
+**Fincept Terminal** is a native C++20 desktop terminal for financial research — Qt6 UI, embedded Python 3.11 analytics, one binary, no Electron.
-## Features
+It ships in **two editions on one data core**:
-| **Feature** | **Description** |
-|-------------|-----------------|
-| 📊 **Multi-Asset Analytics** | DCF models, portfolio optimization, risk metrics (VaR, Sharpe), derivatives pricing across equity, fixed income, derivatives, portfolio, and alternatives via embedded Python |
-| 🤖 **AI Agents** | 37 agents across Trader/Investor (Buffett, Graham, Lynch, Munger, Klarman, Marks…), Economic, and Geopolitics frameworks; local LLM support; multi-provider (OpenAI, Anthropic, Gemini, Groq, DeepSeek, MiniMax, OpenRouter, Ollama) |
-| 🌐 **100+ Data Connectors** | DBnomics, Polygon, Kraken, Yahoo Finance, FRED, IMF, World Bank, AkShare, government APIs, plus optional alternative-data overlays such as Adanos market sentiment for equity research |
-| 📈 **Real-Time Trading** | Crypto (Kraken/HyperLiquid WebSocket), equity, algo trading, paper trading engine, 16 broker integrations (Zerodha, Angel One, Upstox, Fyers, Dhan, Groww, Kotak, IIFL, 5paisa, AliceBlue, Shoonya, Motilal, IBKR, Alpaca, Tradier, Saxo) |
-| 🔬 **QuantLib Suite** | 18 quantitative analysis modules — pricing, risk, stochastic, volatility, fixed income |
-| 🚢 **Global Intelligence** | Maritime tracking, geopolitical analysis, relationship mapping, satellite data |
-| 🎨 **Visual Workflows** | Node editor for automation pipelines, MCP tool integration |
-| 🧠 **AI Quant Lab** | ML models, factor discovery, HFT, reinforcement learning trading |
+| | **Open Source** — this repo | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **Built for** | Learning, personal use, academic research | Funds, family offices, research desks |
+| **Price** | Free · AGPL-3.0 | From **$99**/user/month |
+| **Release cadence** | One update per month | Continuous |
---
-## Installation
+## Which edition should you use?
-<!-- DOWNLOAD-TABLE-START -->
-### Option 1 — Download Installer (Recommended)
+| If you are… | Use | Why |
+|---|---|---|
+| A student, hobbyist or independent learner | **Open Source** | Genuinely free, and it stays that way |
+| An academic researcher | **Open Source** | Free for academic use — universities wanting managed seats, see the academic bundle below |
+| A fund, family office, prop desk, bank or fintech | **Enterprise** | AGPL copyleft doesn't apply, and you get private data, live routing, SSO and an SLA |
+| Doing this professionally, for money | **Enterprise** | Cheaper in practice, and the only edition under active daily development |
-Latest release: **v4.3.0** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0)
+> **The honest version.** The open build is real work, not a crippled demo — but it runs on free public feeds, **your** API keys and **your** LLM key, and every AI call is billed to you per token with no ceiling. Community issues are answered best-effort with no response commitment. If the terminal is how you earn, Enterprise is the cheaper and safer seat.
-| Platform | Download | Run |
-|----------|----------|-----|
-| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
-| **Linux x64 (AppImage)** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64-setup.run) | `chmod +x` → run installer |
-| **Linux x64 (Debian/Ubuntu)** | [FinceptTerminal-Linux-x64.deb](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64.deb) | `sudo apt install ./FinceptTerminal-4.3.0-linux-x64.deb` |
-| **Linux x64 (Fedora/RHEL)** | [FinceptTerminal-Linux-x64.rpm](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64.rpm) | `sudo dnf install ./FinceptTerminal-4.3.0-linux-x64.rpm` |
-| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
-<!-- DOWNLOAD-TABLE-END -->
+[**See Enterprise →**](https://fincept.in/enterprise) · [Full comparison](https://fincept.in/comparison) · [Pricing](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
---
-### Option 2 — Quick Start (One-Click Build)
-
-Clone and run the setup script — it installs all dependencies and builds the app automatically:
-
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
-
-The script handles: compiler check, CMake, Qt6, Python, build, and launch.
-
-> **Windows:** No setup script — use the manual build steps in Option 4 below. It's just two commands.
+## Open Source vs Enterprise
+
+| | Open Source | **Enterprise** |
+|---|---|---|
+| **Licence** | AGPL-3.0 — strong copyleft. Ship it or host it, and you publish your changes | Proprietary — no copyleft obligations to manage |
+| **Cost** | Free — you pay your own data and LLM bills | $99 / $199 / $299 per user/month, all in |
+| **Modules** | Core terminal | **41 modules across 6 desks** |
+| **Data** | Free public feeds, rate-limited, bring your own keys | Private and proprietary datasets — deeper history, faster refresh |
+| **Price history** | Whatever the free tiers allow | 1 yr / 5 yr / unlimited · **point-in-time** for honest backtests |
+| **AI budget** | Bring your own LLM key, billed to you per token | 400 / 2,000 / 5,000 credits included per month |
+| **AI research** | Basic market assistant | Multi-agent research that **plans and delegates** · Agent Studio · up to 53 agents · 6 team modes |
+| **Private dataroom** | — | Your filings and models, read only by your own agents — never pooled, never trained on |
+| **Trading** | Paper trading + broker integrations with your own keys | **Live broker routing + live algo deployment** |
+| **Quant** | Community backtesting | Quant Lab, Alpha Arena, volatility analytics, point-in-time backtests |
+| **Security & compliance** | — | SSO/SAML, audit logs, role-based access, data isolation |
+| **Support** | GitHub issues, best-effort, no response commitment | SLA-backed priority triage |
+| **Documentation** | This repo | [**700-page manual**](https://fincept.in/manual) — 41 guides, 472 sections |
+| **Platforms** | Windows, macOS, Linux + hosted web terminal | Windows 10/11, macOS 13+ (Apple silicon), Linux |
+
+Enterprise runs on a **separate account** — free Fincept logins do not sign in to it, and the app stays locked until a subscription is attached. [Create an Enterprise account →](https://fincept.in/enterprise/signup)
---
-### Option 3 — Docker (CI / Developer Environments)
-
-> **Note:** Docker is intended for CI/CD testing and development environments only.
-> For the best experience, use the pre-built installers in **Option 1** above.
-> Docker requires Linux with X11. Windows and macOS are not supported.
-
-```bash
-# Build from source (Linux + X11 required)
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
-
----
-
-### Option 4 — Build from Source (Manual)
-
-> **Versions are pinned.** Use the exact versions below. Newer or older versions are unsupported and may fail to build or produce unstable binaries.
-
-#### Prerequisites (exact versions)
-
-| Tool | Pinned Version | Notes |
-|------|----------------|-------|
-| **Git** | latest | — |
-| **CMake** | **3.27.7** | [Download](https://cmake.org/download/) |
-| **Ninja** | **1.11.1** | [Download](https://github.com/ninja-build/ninja/releases) |
-| **C++ compiler** | **MSVC 19.38** (VS 2022 17.8) / **GCC 12.3** / **Apple Clang 15.0** (Xcode 15.2) | C++20 required |
-| **Qt** | **6.8.3** | [Qt Online Installer](https://www.qt.io/download-qt-installer) |
-| **Python** | **3.11.9** | [python.org](https://www.python.org/downloads/release/python-3119/) |
-| **Platform SDK** | Win10 SDK 10.0.22621.0 / macOS SDK 14.0 (deploy 11.0+) / glibc 2.31+ | — |
-
-#### Install Qt 6.8.3
-
-**Windows:** Qt Online Installer → select `Qt 6.8.3 > MSVC 2022 64-bit` (install path: `C:/Qt/6.8.3/msvc2022_64`)
+## Enterprise — six desks, 41 modules
-**Linux:** Qt Online Installer → `Qt 6.8.3 > Desktop gcc 64-bit` (install path: `~/Qt/6.8.3/gcc_64`). **Or** for system packages, install `qt6-base-dev qt6-charts-dev qt6-tools-dev qt6-base-private-dev libqt6websockets6-dev libgl1-mesa-dev` — note system packages may be a different 6.x minor.
-
-**macOS:** Qt Online Installer → `Qt 6.8.3 > macOS` (install path: `~/Qt/6.8.3/macos`)
-
-#### Build (using CMake presets — recommended)
-
-```bash
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal/fincept-qt
-```
+| Desk | What it does |
+|---|---|
+| **Agentic Research** · 6 | Agents plan the work, delegate to specialists, read live data and your dataroom, return sourced notes |
+| **Quant Lab & Backtesting** · 4 | Signal research, point-in-time backtests, volatility surfaces |
+| **Deep Fundamental Research** · 8 | Equity analysis, valuation, derivatives, M&A analytics |
+| **Markets & Execution** · 7 | Live equities, crypto and prediction markets, broker routing, algo deployment |
+| **Macro & Global Intelligence** · 7 | Statistics, government data, geopolitics, shipping lanes |
+| **Your Own Workspace** · 9 | Dashboard, spreadsheet, notes, files, code, report builder |
-**Step 1 — Configure** (one-time, or after `CMakeLists.txt` changes):
-```powershell
-cmake --preset win-release # Windows (PowerShell)
-cmake --preset linux-release # Linux
-cmake --preset macos-release # macOS
-```
+[Browse the products →](https://fincept.in/products)
-**Step 2 — Compile** (run this for every code change):
-```powershell
-cmake --build --preset win-release # Windows
-cmake --build --preset linux-release # Linux
-cmake --build --preset macos-release # macOS
-```
+### Pricing
-> **Older or RAM-constrained machines:** add `--parallel 4` (or any small number) to cap concurrent compile jobs. The default saturates every core, which can overheat older CPUs and slow the rest of your system. Example: `cmake --build --preset macos-release --parallel 4`.
+| | **Exclusive** | **Exclusive+** ★ most popular | **Exclusive Pro** |
+|---|---|---|---|
+| | **$99**/user/mo | **$199**/user/mo | **$299**/user/mo |
+| AI credits / month | 400 | 2,000 | 5,000 |
+| Portfolios · watchlists | 1 · 3 | 10 · 25 | Unlimited |
+| Price history | 1 year | 5 years | Unlimited |
+| Seats included | 1 | 1 | 2 |
+| Deep research + agent teams | — | ✓ | ✓ |
+| Broker account linking | — | ✓ | ✓ |
+| Live broker trading + algo deployment | — | — | ✓ |
-Debug variants: replace `release` with `debug` (e.g. `win-debug`, `linux-debug`, `macos-debug`).
+Monthly billing · no annual lock-in · no seat minimum · **15% off on quarterly**. That works out to **$1,188–$3,588 per user per year**, against roughly **$27,000** for a Bloomberg seat — [see the full comparison](https://fincept.in/comparison).
-> **Windows prerequisite:** The PowerShell profile at `~/Documents/PowerShell/Microsoft.PowerShell_profile.ps1`
-> auto-initializes VS 2022 on every new terminal — open a fresh PowerShell and cmake works directly.
+**Universities and academic institutions:** one flat bundle — **5 Exclusive Pro seats for $699/month** (list price $1,495). Email [[email protected]](mailto:[email protected]).
-#### Build (manual — if presets can't resolve your Qt path)
+These three plans plus the academic bundle are the entire price list. There is no custom or negotiated enterprise pricing, and no separate commercial licence to buy.
-```powershell
-# Windows (PowerShell)
-cmake -B build/win-release -G Ninja -DCMAKE_BUILD_TYPE=Release `
- -DCMAKE_PREFIX_PATH="C:/Qt/6.8.3/msvc2022_64"
-cmake --build build/win-release
-```
+[**Create Enterprise account**](https://fincept.in/enterprise/signup) · [**Book a walkthrough**](https://calendly.com/nikultilak/fincept-terminal-demo) · [Read the manual](https://fincept.in/manual)
-```bash
-# Linux
-cmake -B build/linux-release -G Ninja -DCMAKE_BUILD_TYPE=Release \
- -DCMAKE_PREFIX_PATH="$HOME/Qt/6.8.3/gcc_64"
-cmake --build build/linux-release
+---
-# macOS
-cmake -B build/macos-release -G Ninja -DCMAKE_BUILD_TYPE=Release \
- -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 \
- -DCMAKE_PREFIX_PATH="$HOME/Qt/6.8.3/macos"
-cmake --build build/macos-release
-```
+## Install the open-source edition
-#### Run
+<!-- DOWNLOAD-TABLE-START -->
+Latest release: **v4.3.0** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.3.0)
-```bash
-./build/<preset>/FinceptTerminal # Linux / macOS (preset build)
-.\build\<preset>\FinceptTerminal.exe # Windows (preset build)
-```
+| Platform | Download | Run |
+|----------|----------|-----|
+| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
+| **Linux x64 (AppImage)** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64-setup.run) | `chmod +x` → run installer |
+| **Linux x64 (Debian/Ubuntu)** | [FinceptTerminal-Linux-x64.deb](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64.deb) | `sudo apt install ./FinceptTerminal-4.3.0-linux-x64.deb` |
+| **Linux x64 (Fedora/RHEL)** | [FinceptTerminal-Linux-x64.rpm](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-linux-x64.rpm) | `sudo dnf install ./FinceptTerminal-4.3.0-linux-x64.rpm` |
+| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.3.0/FinceptTerminal-4.3.0-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
+<!-- DOWNLOAD-TABLE-END -->
-#### Troubleshooting
+**Build from source** — Linux/macOS: `git clone … && ./setup.sh`. Windows and manual builds, the pinned toolchain (**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**) and troubleshooting live in **[docs/GETTING_STARTED.md](docs/GETTING_STARTED.md)**. Versions are pinned — newer or older ones are unsupported.
-1. **"Could not find Qt6 6.8.3"** — verify `CMAKE_PREFIX_PATH` points to the Qt 6.8.3 install, not 6.5/6.6/6.8.
-2. **MSVC version error** — use VS 2022 17.8+ (MSVC 19.38+). Check with `cl /?`.
-3. **Need to unblock with a different Qt minor?** Pass `-DFINCEPT_ALLOW_QT_DRIFT=ON` (local testing only — never for releases or CI).
-4. Clean rebuild: delete `build/<preset>/` and re-run configure.
+> Looking for the Enterprise build? It has its own signed installers for Windows, macOS and Linux, behind an Enterprise login — [get them here](https://fincept.in/enterprise).
---
-## What Sets Us Apart
-
-**Fincept Terminal** is an open-source financial platform built for those who refuse to be limited by traditional software. We compete on **analytics depth** and **data accessibility** — not on insider info or exclusive feeds.
+## What's in the open build
-Recent builds also support optional **Adanos Market Sentiment** connectivity in **Data Sources → Alternative Data**. When configured, Equity Research can surface cross-source retail sentiment snapshots across Reddit, X, finance news, and Polymarket. Without an active Adanos connection, the feature remains dormant and the rest of the app behaves exactly as before.
+| | |
+|---|---|
+| **Multi-asset analytics** | DCF, portfolio optimisation, VaR/Sharpe, derivatives pricing, fixed income, alternatives — via embedded Python |
+| **QuantLib suite** | 18 quantitative modules — pricing, risk, stochastic, volatility, fixed income |
+| **AI agents** | 37 agents across trader/investor, economic and geopolitics frameworks; bring your own key (OpenAI, Anthropic, Gemini, Groq, DeepSeek, OpenRouter, Ollama) |
+| **100+ data connectors** | DBnomics, FRED, IMF, World Bank, AkShare, Polygon, Kraken, Yahoo Finance, government APIs |
+| **Trading** | Crypto and equity feeds, paper-trading engine, 16 broker integrations |
+| **Automation** | Visual node editor, MCP tool integration, AI Quant Lab (ML, factor discovery, RL) |
+| **Global intelligence** | Maritime tracking, geopolitical analysis, relationship mapping |
-- **Native performance** — C++20 with Qt6, no Electron/web overhead
-- **Single binary** — no Node.js, no browser runtime, no JavaScript bundler
-- **Full buy-side analyst toolkit** — equity, portfolio, derivatives, fixed income, corporate finance, alternatives
-- **100+ data connectors** — from Yahoo Finance to government databases
-- **Free & Open Source** (AGPL-3.0) with commercial licenses available
+Native C++20 · Qt6 · embedded Python 3.11 · single binary · no Node.js, no browser runtime.
---
-## Roadmap
+## How this repo is maintained
-| Timeline | Milestone |
-|----------|-----------|
-| **Shipped** | Real-time streaming, 16 broker integrations, multi-account trading, PIN authentication, theme system |
-| **Q2 2026** | Options strategy builder, multi-portfolio management, 50+ AI agents |
-| **Q3 2026** | Programmatic API, ML training UI, institutional features |
-| **Future** | Mobile companion, cloud sync, community marketplace |
+This repo **stays public and will not be deleted**. Everything already released stays released.
+
+It now ships **one release a month** rather than continuous development, because the team's daily work is on Enterprise. Issues and pull requests are still reviewed, and fixes land on the monthly cycle. Security reports go to [[email protected]](mailto:[email protected]).
---
## Contributing
-We're building the future of financial analysis — together.
-
-**Contribute:** New data connectors, AI agents, analytics modules, C++ screens, documentation
+New data connectors, AI agents, analytics modules, C++ screens and documentation are all welcome.
-- [Contributing Guide](docs/CONTRIBUTING.md)
-- [C++ Contributing Guide](fincept-qt/CONTRIBUTING.md)
-- [Python Contributor Guide](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [Report Bug](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [Request Feature](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+[Contributing guide](docs/CONTRIBUTING.md) · [C++ guide](docs/CPP_CONTRIBUTOR_GUIDE.md) · [Python guide](docs/PYTHON_CONTRIBUTOR_GUIDE.md) · [Architecture](docs/ARCHITECTURE.md) · [Report a bug](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [Request a feature](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
---
-## For Universities & Educators
-
-**Bring professional-grade financial analytics to your classroom.**
+## Also from Fincept
-- **$799/month** for 20 accounts
-- Full access to Fincept Data & APIs
-- Perfect for finance, economics, and data science courses
-- Equity, portfolio, derivatives, fixed income, and economics analytics built-in
-
-**Interested?** Email **[email protected]** with your institution name.
-
-[University Licensing Details](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+- **[Fincept Data API](https://docs.fincept.in)** — 500+ REST endpoints, 423,000+ instruments, 2,000+ sources. Free tier included with any account.
+- **[Quantcept](https://quantcept.io)** — open-source, AI-powered command-line finance terminal (Apache-2.0).
---
## License
-> ⚠️ **Cloning, forking, or modifying this repository does NOT grant commercial rights.**
-> A paid Commercial License is required for **any** business or internal company use — including forks that remove or replace Fincept's APIs with your own data sources. See **[Commercial License](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)** for binding terms.
-
-**Dual Licensed: AGPL-3.0 (Open Source) + Fincept Commercial License**
-
-| | |
-|---|---|
-| ✅ **Free under AGPL-3.0** | Personal use · Individual learning · Academic research · Open-source contributions to this repository |
-| ❌ **Commercial License required** | Any business use (paid or free) · Internal company use · Startups at any stage · Hedge funds, brokerages, banks, fintechs · SaaS / hosted offerings · White-label or reselling · Forks that strip or replace Fincept APIs · Consulting deliverables · Employee training or evaluation by for-profit entities |
+**AGPL-3.0-or-later** — full text in [LICENSE](LICENSE).
-The license attaches to the **codebase and any Derivative Work of it**, not to specific API integrations. Substituting Fincept APIs with your own — or with any third party's — does not sever or extinguish the licensing obligation. **These terms apply to every version, branch, tag, and commit of Fincept Terminal — past, present, and future** — and remain in force indefinitely until superseded by a subsequent published version.
+Free for personal use, learning and academic research. AGPL-3.0 is **strong copyleft, not permissive**: distribute a modified build, or run one as a service other people reach, and you must publish your changes under the same licence. For most legal teams that is the row that ends the discussion — which is why firms take **[Enterprise](https://fincept.in/enterprise)**, which is proprietary and carries no copyleft obligations to manage. Personal, non-distributed use carries no obligations.
-**Trademarks.** "Fincept", "Fincept Terminal", and the Fincept logo are trademarks of Fincept Corporation. Use in any forked, derivative, rebranded, or commercial product requires prior written permission. Removal or rebranding of these marks in a fork does not extinguish the underlying licensing obligation.
+Fincept no longer sells a separate commercial or academic licence for this repository. Commercial, enterprise and university needs are served by **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** at the published prices above.
-**Enforcement & Penalties.** Fincept Corporation actively monitors public repositories, app stores, cloud marketplaces, and SaaS platforms for unlicensed Commercial Use, and pursues DMCA takedowns, cease-and-desist notices, and civil action under Indian and international law. Unauthorized commercial use is subject to **liquidated damages starting at USD 50,000 per organization per year**, with higher amounts for unauthorized SaaS distribution, fork-and-replace deployments, and trademark misuse — in addition to backdated license fees, disgorgement of profits, and recovery of legal costs. **Joint and several liability** applies: any company that engages a third-party developer, integrator, or consultancy to build, modify, or deploy the Software is fully liable alongside that developer for any unauthorized use. Governing law: India · Exclusive jurisdiction: Delhi, India.
+**Trademarks.** "Fincept", "Fincept Terminal" and the Fincept logo are trademarks of Fincept Corporation. Use in any forked, derivative, rebranded or commercial product requires prior written permission.
-**Contact for licensing:** [email protected] · Full terms: [docs/COMMERCIAL_LICENSE.md](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+Questions: [[email protected]](mailto:[email protected]) · [Terms](https://fincept.in/terms) · [Privacy](https://fincept.in/privacy)
© 2025–2026 Fincept Corporation. All rights reserved.
diff --git a/docs/COMMERCIAL_LICENSE.md b/docs/COMMERCIAL_LICENSE.md
index 508d1eda0..676dea6ee 100644
--- a/docs/COMMERCIAL_LICENSE.md
+++ b/docs/COMMERCIAL_LICENSE.md
@@ -1,319 +1,86 @@
-# Fincept Terminal — Commercial License
+# Fincept Terminal — Licensing
-**Version:** 2.0
-**In effect from:** April 30, 2026 (and continuing in force until superseded by a subsequent version published by Fincept Corporation)
+**Version:** 3.0
+**In effect from:** August 11, 2026
+**Supersedes:** Commercial License v2.0 (April 30, 2026), which is withdrawn in full
**Licensor:** Fincept Corporation (a company organized under the laws of India)
-**Contact:** [email protected] · +91-9773034108 · https://fincept.in
+**Contact:** [email protected] · https://fincept.in
---
-## 1. Notice — Read First
+## 1. Summary
-> ⚠️ **Cloning, forking, downloading, building, or modifying this repository does NOT grant any right to use Fincept Terminal — or any Derivative Work of it — for Commercial Use.**
-> A separate, paid Commercial License executed with Fincept Corporation is required for any Commercial Use, including **internal use within any for-profit organization**, even where Fincept's data sources, APIs, or service endpoints have been removed, replaced, or rewired.
+This repository — **Fincept Terminal, open-source edition** — is licensed under the **GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)**, and under no other licence.
-This document is a plain-language summary **and** the operative commercial-licensing terms of Fincept Terminal. It supplements — and in case of conflict, governs over — the AGPL-3.0 license under which the Software is also made available for non-commercial purposes.
+Fincept Corporation **no longer sells a separate commercial, enterprise, or academic licence for this repository.** The previous dual-licensing arrangement is discontinued. Commercial, institutional, and university needs are now served by a separate product, **[Fincept Terminal Enterprise](https://fincept.in/enterprise)**, at published prices.
----
-
-## 2. Dual-License Structure
-
-Fincept Corporation is the sole copyright holder of the Software. As copyright holder, Fincept Corporation offers the Software under **two alternative, independent licenses**, and a user must select and comply with **one** of them:
-
-1. **GNU Affero General Public License v3.0 (AGPL-3.0)** — for personal use, individual learning, academic research by individual students, and open-source contribution. Full text: [`/LICENSE`](../LICENSE).
-2. **Fincept Commercial License** — for any Commercial Use, as defined in Section 3 below.
-
-**The Commercial License is not a modification of, addition to, or restriction upon the AGPL-3.0.** It is an alternative license offered by the copyright holder. A user who engages in Commercial Use is required to obtain rights under the Commercial License because the AGPL-3.0 grant offered by Fincept Corporation **never extended to Commercial Use** — Commercial Use was never within the scope of the AGPL-3.0 offer made by the copyright holder. Accordingly, the restrictions in this document do not constitute "further restrictions" within the meaning of AGPL-3.0 § 7; they define the scope of an *alternative* license offering.
-
-A user engaging in Commercial Use without an executed Commercial License is in breach of copyright and subject to all remedies set forth in Sections 12, 13, and 14.
-
-**Acceptance.** Each act of downloading, cloning, forking, building, executing, distributing, modifying, or otherwise using the Software constitutes affirmative acceptance of this License in its then-current published form. Continued use after publication of any new version of this License constitutes acceptance of the new version. A user who does not accept this License must immediately cease use and destroy all copies. The public availability of this License at the Fincept Terminal repository, in every release artifact, and embedded in the Software constitutes constructive notice to all users worldwide.
-
----
-
-## 3. Definitions
-
-For the purposes of this License, the following capitalized terms apply:
-
-- **"Software"** means the source code, object code, binaries, scripts (including all Python scripts in the `scripts/` tree), configuration, documentation, assets, build artifacts, container images, virtual-machine images, model weights and parameters trained or fine-tuned using the Software, datasets, embeddings, feature stores, and any output materially derived from the foregoing, contained in or produced by the Fincept Terminal repository at https://github.com/Fincept-Corporation/FinceptTerminal, in any branch, tag, release, fork, mirror, or commit, in whole or in part. Each script, module, file, broker integration, screen, MCP tool, agent framework, and Python wrapper is severable for purposes of demonstrating use, but **not severable for purposes of escaping this License**. Use of any one component constitutes use of the Software. No portion of the Software qualifies as a "System Library," "Standard Interface," or "Major Component" within the meaning of any open-source license definition.
-
-- **"Modified Version"** means any version of the Software that has been altered, including by the addition, removal, replacement, rewiring, disabling, substitution, translation, porting, or refactoring of any module, file, function, screen, API, data integration, service endpoint, or analytical algorithm.
-
-- **"Derivative Work"** means any software, work product, or system, in source or object form, that is based on, incorporates, links to (statically or dynamically), wraps, calls into, embeds, invokes via API, RPC, message queue, file drop, screen scrape, or any intermediation, or substantially reproduces the Software or any portion thereof. Derivative Work includes, without limitation, any version produced by: (i) compilation of the Software's source tree with or without modification; (ii) replacement, removal, disabling, or rewiring of any module, API, data integration, or service endpoint while retaining any other portion of the Software; (iii) translation, porting, or rewriting of any part of the Software into another programming language or runtime while preserving its architecture, screen layouts, workflow, sequence-structure-and-organization, MCP tool taxonomy, broker abstraction layer, agent framework hierarchy, terminal command syntax, function-code conventions, or feature set; (iv) translation of UI text, terminal commands, or function codes into another language or alphabet; (v) any work whose primary purpose, value, or functionality is materially derived from the Software; or (vi) any system that consumes, accesses, or operates upon the output, datasets, embeddings, model weights, or feature stores produced by the Software. The use of any portion of the Software comprising more than fifty (50) lines of source code, any single source file, any named function or class, any data schema, or any analytical algorithm or workflow expressed in the Software constitutes a Derivative Work; these thresholds are illustrative minima and not safe harbors. The number of intermediate hops, wrappers, gateways, proxies, or microservices between a user and the Software is irrelevant. Substantial similarity in non-literal elements is presumed to be a Derivative Work, with the burden on the alleged infringer to rebut by clear and convincing evidence.
-
-- **"Commercial Use"** means any use of the Software or any Modified Version or Derivative Work, in whole or in part, by, for, on behalf of, or for the benefit of any for-profit entity, governmental body, sovereign entity, central bank, public-sector undertaking, multilateral institution, quasi-governmental agency, non-profit, charity, religious organization, NGO (irrespective of revenue-generating status, tax-exempt status, or sovereign immunity, which is expressly waived to the maximum extent permitted by applicable law), or any individual acting in the course of employment, contracting, consulting, or service for any such entity. Commercial Use includes, without limitation:
-
- (a) **Internal use** within an organization, regardless of whether the Software is exposed to third parties or remains entirely within the organization's network, intranet, air-gapped environment, or internal Git repository;
-
- (b) Use during evaluation, proof-of-concept, pilot, research and development, demonstration, onboarding, or training of employees, contractors, or consultants;
-
- (c) Use to support, augment, replace, or supplement any product, service, research output, regulatory filing, or operational activity of Licensee or its affiliates, whether or not such product, service, or output is sold or generates revenue;
-
- (d) Any installation on or execution upon hardware, networks, virtual machines, containers, cloud accounts, or infrastructure owned, leased, controlled, paid for, or sponsored by any for-profit entity, governmental body, or organization, irrespective of whether the entity directed, knew of, or sanctioned the installation. The "personal use" exemption applies only to natural persons using personally owned and personally paid-for hardware for non-commercial purposes outside the course of employment;
-
- (e) Use of any Modified Version, including any version in which Fincept-provided data sources, APIs, integrations, or service endpoints have been removed, replaced, rewired, or substituted with Licensee's or any third party's data sources, APIs, integrations, or service endpoints;
-
- (f) Access to the Software, directly or indirectly, by API call, REST endpoint, RPC, gRPC, message queue, file drop, screen scrape, RPA bot, headless invocation, or any other intermediation, including pulling, instantiating, executing, mounting, or hosting any container image or virtual-machine image containing the Software;
-
- (g) Internal redistribution within any for-profit organization, including via internal Git repositories, artifact registries, package managers, mirrors, USB transfer, or peer-to-peer transfer;
-
- (h) Bundling, aggregation, integration, or co-installation of the Software with Licensee's products, regardless of any "mere aggregation" exemption recognized in any open-source license;
-
- (i) Executive education, MBA-corporate residencies, paid certificate programs, sponsored research deliverables, expert-witness work, and any course, training, or service generating fees or compensation, even where conducted by an academic institution;
-
- (j) Output that is monetized in any form (paid newsletter, consulting, advisory, expert testimony, structured-product creation, signal generation), regardless of whether the recipient is a for-profit or non-profit entity.
-
- **The substitution of data sources or APIs does not, in any circumstance, convert Commercial Use into non-Commercial Use.** **The personal-use exemption is narrowly construed and applies only to a natural person using personally owned hardware for purposes wholly unrelated to any business, employment, or revenue-generating activity.**
-
-- **"Fincept Marks"** means the names, logos, and trade dress "Fincept", "Fincept Terminal", "Fincept Corporation", and any colorable imitation, transliteration, abbreviation, translation, or variation or derivative thereof.
-
-- **"Fincept Trade Dress"** means the distinctive look and feel of Fincept Terminal, including screen layouts, color palette, terminal command syntax, ticker conventions, function-code conventions, keyboard shortcut conventions, dashboard widget vocabulary, and overall visual identity.
-
-- **"Licensor"** means Fincept Corporation. **"Licensee"** means the natural or legal person exercising rights under this License.
-
----
-
-## 4. When a Commercial License Is Required
-
-A Commercial License is required for **all** of the following — there are no exceptions and no carve-outs for revenue, size, or duration:
-
-- Any business use, paid or free, with revenue or without revenue
-- **Internal use within any company, fund, government body, or for-profit organization** — even if the Software is never exposed to third parties, even after Fincept APIs have been removed or replaced
-- Startups at any stage — pre-revenue, pre-product, pre-seed, evaluation, pilot, or proof-of-concept
-- Hedge funds, proprietary trading firms, banks, brokerages, asset managers, family offices, fintechs, and exchanges
-- SaaS, PaaS, IaaS, or any hosted, managed, or cloud offering of the Software or a Derivative Work
-- White-label, OEM, rebranded, or resold distributions of the Software or a Derivative Work
-- Forks that strip out, replace, disable, or rewire Fincept APIs, data sources, or service endpoints, when used for Commercial Use
-- Consulting, professional services, system-integrator, or contractor deliverables that include or rely on the Software
-- Training, evaluation, demonstration, or onboarding of employees or contractors of any for-profit entity
-- Any use that competes with, substitutes for, or substantially replicates the functionality of Fincept Terminal or any product or service offered by Licensor
-
-If you are uncertain, **assume a Commercial License is required** and contact [email protected].
-
----
-
-## 5. What Cloning, Forking, or Modifying the Repository Does *Not* Grant
-
-The AGPL-3.0 grant attached to the public repository permits a user, for non-commercial purposes only, to view, study, modify, and redistribute the Software under AGPL-3.0 terms. **It does not grant any of the following**, all of which require a separate Commercial License:
-
-1. The right to run the Software inside a company, fund, government body, or any for-profit organization for any purpose, internal or external
-2. The right to use the Software, in any form, in support of any revenue-generating, business, professional, or operational activity
-3. The right to remove, replace, disable, or rewire Fincept's APIs, data integrations, or service endpoints and then use the resulting Modified Version or Derivative Work commercially or internally
-4. The right to use, reproduce, or imitate any of the Fincept Marks or Fincept Trade Dress in any forked, derivative, rebranded, or successor product
-5. The right to relicense, sublicense, sell, lease, or offer paid access to the Software or any Derivative Work
-6. Any rights in or to Fincept-operated data services, API endpoints, hosted infrastructure, or proprietary datasets
-
-The license attaches to the **codebase and any Derivative Work of it**, not to specific API integrations. **Substituting Fincept APIs with your own — or with any third party's — does not sever or extinguish the licensing obligation.**
-
----
-
-## 6. Trademark and Trade Dress
-
-Licensee shall not use the Fincept Marks in connection with any product, service, repository, distribution, or marketing, except as expressly authorized in advance and in writing by Licensor. **Removal, replacement, or rebranding of the Fincept Marks in any fork or Derivative Work does not extinguish Licensor's rights in the underlying Software, nor does it sever the licensing obligations attaching to the codebase.**
-
-Licensee acknowledges that the value of the Fincept Marks lies not only in the literal trademark text but in the Fincept Trade Dress. Licensee shall not, in any forked, derivative, or successor product, replicate the Fincept Trade Dress in a manner likely to cause confusion, mistake, deception, association, or initial-interest confusion as to source or affiliation, even where the literal Fincept Marks have been removed or replaced. **Translation of UI text, terminal commands, function codes, or screen names into another language or alphabet does not extinguish trade-dress protection.** Renaming, abbreviating, or substituting individual screen names, function codes, terminal commands, or keyboard shortcuts does not avoid trade-dress liability where the underlying *system* of conventions is substantially preserved. Any product that retains substantially similar Fincept Trade Dress shall be deemed a Derivative Work for all purposes of this License, and any Commercial Use thereof requires a Commercial License from Licensor.
-
-**Comparative Advertising.** Any use of the Fincept Marks or Fincept Trade Dress in marketing, sales materials, demos, RFP responses, screenshots, or product comparisons by a for-profit competitor or its agents constitutes commercial use of the Marks and is prohibited absent express written permission, irrespective of any nominative-fair-use or comparative-advertising defense.
-
-**Burden of Independent Creation.** Where Licensee or any Third-Party Developer asserts independent creation as a defense to a Derivative Work claim, the burden of proving independent creation rests on the alleged infringer, to be evidenced by contemporaneous design documents, complete commit history, personnel certifications, and clean-room development records, all of which shall be produced to Licensor on demand.
-
-Any Derivative Work that is publicly distributed in source-available form shall prominently display the notice: *"Derived from Fincept Terminal © Fincept Corporation; use of this Derivative Work for Commercial Use requires a separate Commercial License from Fincept Corporation, [email protected]."*
-
----
-
-## 7. Pricing
-
-| Plan | Fee | Includes |
-|------|-----|----------|
-| **Commercial License** | **USD 10,200 / year** per organization | Full Commercial Use rights for one legal entity; Fincept Data & API access; 65,000 credits/month (resets monthly); additional credits available for purchase |
-| **Technical Support** *(optional add-on)* | **USD 149 / month** | Priority support, direct technical assistance, faster response times |
-| **University & Academic** | **USD 799 / month** | 20 accounts for teaching and research at an accredited educational institution; Fincept Data access included; non-commercial classroom use only |
-| **Custom Enterprise** | Contact for pricing | Tailored requirements, custom integrations, higher credit limits, dedicated support, custom SLAs, source-available agreements |
-
-Credits are consumed by Fincept Data Sources and API calls. When credits are exhausted, Licensee may purchase additional credits or wait for the monthly reset. Fees are payable annually in advance and non-refundable except as expressly stated.
-
----
-
-## 8. Patent Grant and Patent Retaliation
-
-Subject to the terms of this License, Licensor grants Licensee a non-exclusive, worldwide, royalty-bearing license under Licensor's patent claims to make, have made, use, offer to sell, sell, import, and have imported the Software, solely as authorized hereunder.
-
-**If Licensee, or any entity controlling, controlled by, or under common control with Licensee, institutes patent litigation (including a cross-claim or counterclaim in a lawsuit) against any entity alleging that the Software, its use, or any contribution to it constitutes direct or contributory patent infringement, then any patent licenses granted to Licensee under this License shall terminate as of the date such litigation is filed.** Patent claims arising from modifications introduced by Licensee are not licensed.
-
----
-
-## 9. Audit Rights
-
-Licensor may, upon thirty (30) days' written notice and not more than once per twelve (12) month period (except where Licensor reasonably suspects breach), audit Licensee's use of the Software through a mutually agreed independent auditor bound by confidentiality. Licensee shall provide reasonable cooperation, including access to deployment records, user counts, infrastructure inventories, and source repositories containing the Software or Derivative Works. If the audit reveals underpayment exceeding five percent (5%) or any unauthorized Commercial Use, Licensee shall pay (a) the unpaid fees calculated retroactively at the then-current rate, (b) interest at 18% per annum or the maximum permitted by law, whichever is lower, and (c) the reasonable costs of the audit.
-
-**Annual Self-Attestation.** Every for-profit user of the Software shall submit, by 31 January of each calendar year, a written attestation to [email protected] stating its license status, the number of users, the number of deployments, and the legal entity name(s) using the Software. Failure to file the attestation is a per se breach triggering the liquidated damages set forth in Section 13.
-
-**Privacy and Trade-Secret Limitations.** Where applicable data-protection law (including the EU General Data Protection Regulation, the Digital Personal Data Protection Act, 2023 (India), or analogous statutes) restricts disclosure of personal data, Licensor shall accept anonymized or pseudonymized data sufficient to verify compliance, comprising at minimum: (i) total user count, (ii) total deployment count, (iii) entity legal name, and (iv) hashed code-base fingerprints. Licensee bears the cost of any data-protection compliance for audit response. Where Licensee asserts trade-secret protection over its source code, Licensor will accept code review by an escrow agent operating under attorney-client privilege, with results delivered as compliance status only. Confidentiality obligations to third parties (NDAs with Licensee's clients) shall not impair Licensor's audit rights; Licensee shall use commercially reasonable efforts to obtain any necessary client consent or shall provide redacted equivalent information. Where applicable foreign blocking statute genuinely prevents disclosure, Licensee shall provide equivalent information from a permitted jurisdiction or pay liquidated damages in lieu of audit pursuant to Section 13.
-
-**Disclosure of Third-Party Developers.** Upon Licensor's written request, Licensee shall provide, within ten (10) business days: (a) the legal name and contact details of any Third-Party Developer engaged with the Software; (b) the scope of work; (c) copies of the relevant engagement agreement or statement of work, redacted only as to commercial pricing terms; and (d) a list of all repositories, deployment locations, and personnel with access to the Software.
-
----
-
-## 10. Termination and Survival
-
-This License terminates automatically and without notice upon any breach by Licensee of any provision. Termination does not relieve Licensee of accrued obligations, including unpaid fees. Upon termination, Licensee shall immediately cease all use, destroy all copies of the Software and all Derivative Works in its possession or control, and certify such destruction in writing within fifteen (15) days.
-
-The following provisions survive termination: Sections 3 (Definitions), 5 (No Implied Grant), 6 (Trademark and Trade Dress), 8 (Patent Retaliation), 9 (Audit, for two years post-termination), 11 (Disclaimer), 12 (Enforcement), 13 (Liquidated Damages and Penalties), 14 (Joint and Several Liability), 15 (Limitation of Liability), 16 (Governing Law), and this Section 10.
-
----
-
-## 11. Disclaimer of Warranties
-
-THE SOFTWARE IS PROVIDED "AS IS" AND "AS AVAILABLE," WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ACCURACY, RELIABILITY, OR THAT THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE. NO INFORMATION OR ADVICE OBTAINED FROM LICENSOR SHALL CREATE ANY WARRANTY NOT EXPRESSLY STATED HEREIN. THE SOFTWARE IS NOT INTENDED FOR USE IN, AND IS NOT WARRANTED FOR USE IN, ANY APPLICATION WHERE FAILURE COULD RESULT IN FINANCIAL LOSS, REGULATORY VIOLATION, OR PERSONAL INJURY. NOTHING IN THE SOFTWARE OR ANY OUTPUT GENERATED BY IT CONSTITUTES INVESTMENT, LEGAL, TAX, ACCOUNTING, OR FINANCIAL ADVICE.
-
----
-
-## 12. Enforcement
-
-Licensor actively monitors public code repositories, container registries, application stores, cloud marketplaces, SaaS platforms, and trademark registers for unlicensed Commercial Use of the Software, Modified Versions, and Derivative Works. Licensor reserves the right, without prior notice, to:
-
-1. Issue takedown notices under the U.S. Digital Millennium Copyright Act (17 U.S.C. § 512), the Information Technology Act, 2000 (India) §§ 65 and 66, the Copyright Act, 1957 (India) §§ 63–63B, and equivalent statutes in other jurisdictions;
-2. Issue cease-and-desist letters to violating organizations and their officers, directors, and counsel;
-3. Seek injunctive and monetary relief, including statutory damages, disgorgement of profits, and recovery of unpaid license fees calculated at the then-current Commercial License rate retroactive to first unauthorized use, plus interest, attorneys' fees, and costs;
-4. Pursue trademark infringement, passing-off, and unfair-competition claims for misuse of the Fincept Marks or Fincept Trade Dress;
-5. Pursue criminal complaints where applicable under the Copyright Act, 1957 (India) §§ 63–63B and equivalent foreign laws.
-
-If you believe you may be using the Software commercially without a license, contact **[email protected]** for a good-faith resolution path.
-
----
-
-## 13. Liquidated Damages and Penalties for Unauthorized Use
-
-**Genuine Pre-Estimate of Loss — Methodology.** The parties expressly acknowledge and stipulate that:
-
-(i) actual damages flowing from unauthorized Commercial Use are inherently difficult to quantify because they include (a) lost Commercial License revenue that cannot be recovered through later licensing, (b) loss of competitive advantage and market share, (c) erosion of the dual-licensing business model that funds the open-source codebase, (d) costs of detection, monitoring, investigation, and enforcement against widespread unauthorized internal use, and (e) reputational and goodwill harm;
-
-(ii) the amounts set forth below are a **genuine pre-estimate of loss**, calculated by reference to: (a) the published annual Commercial License fee of USD 10,200, (b) average industry compliance and detection cost per violation, (c) average revenue diversion per unauthorized deployment based on financial-software industry benchmarks, and (d) the deterrent value reasonably necessary to prevent the well-known "lab leak" pattern in which an internal corporate fork escapes detection for years;
-
-(iii) the amounts are not a penalty *in terrorem*, but reasonable compensation within the meaning of Section 74 of the Indian Contract Act, 1872, and equivalent provisions in other jurisdictions;
-
-(iv) the parties stipulate to the reasonableness of these amounts and waive any defense that they constitute a penalty, are excessive, or are *in terrorem*, except where such waiver is unenforceable as a matter of mandatory law.
-
-Any party engaged in unauthorized Commercial Use of the Software, a Modified Version, or a Derivative Work shall be liable to Licensor for liquidated damages, in addition to all other remedies available in law or equity:
-
-| Violation | Liquidated Damages |
-|-----------|-------------------|
-| **Unauthorized internal corporate use** (per organization, per year of use) | **USD 50,000** or 5× the then-current Commercial License fee, **whichever is greater** |
-| **Unauthorized commercial distribution, hosting, SaaS, or resale** of the Software or any Derivative Work | **USD 250,000** per distinct offering, plus disgorgement of all revenue derived therefrom |
-| **Unauthorized fork that replaces, removes, or rewires Fincept APIs and is used commercially or internally** | **USD 100,000** per organization, plus 5× the then-current Commercial License fee for each year of use, plus full backdated license fees from first unauthorized use |
-| **Unauthorized use of Fincept Marks or Fincept Trade Dress** in a forked, derivative, or rebranded product | **USD 150,000** per mark or trade-dress element, plus mandatory injunction, plus disgorgement of profits |
-| **Failure to comply with audit obligations** under Section 9 | **USD 25,000** per audit cycle, plus full audit costs |
-| **Continued use after notice of breach or termination** | **USD 10,000 per day** until cessation is verified, plus all enforcement costs |
-
-In addition to liquidated damages, Licensor is entitled to recover:
-
-1. All unpaid license fees, calculated retroactively at the then-current Commercial License rate from the date of first unauthorized use, plus interest at 18% per annum or the maximum permitted by law, whichever is lower;
-2. Disgorgement of all profits, revenue, cost savings, and any other economic benefit derived by the violator from unauthorized use;
-3. All attorneys' fees, court fees, expert fees, investigation costs, and other costs of enforcement;
-4. Statutory damages and any additional remedies available under the Copyright Act, 1957 (India), the Trade Marks Act, 1999 (India), the Information Technology Act, 2000 (India), the U.S. Copyright Act (17 U.S.C.), the Lanham Act (15 U.S.C. § 1051 et seq.), and equivalent statutes in any applicable jurisdiction;
-5. Punitive and exemplary damages where permitted by law, particularly for willful or repeated violations.
-
-The liquidated damages stated above are **per violation, cumulative**, and apply **per year of unauthorized use**. Liquidated damages do not constitute a license fee, do not retroactively legitimize unauthorized use, and do not waive Licensor's right to seek injunctive relief, criminal prosecution, or any other remedy.
+Full AGPL-3.0 text: [`/LICENSE`](../LICENSE).
---
-## 14. Joint and Several Liability of Contracting Companies, Developers, Integrators, and Affiliates
-
-**Any organization that engages, hires, contracts with, instructs, or otherwise uses a third party — including but not limited to software development firms, system integrators, IT consultancies, contractors, freelancers, outsourcing vendors, offshore development centers, white-label developers, or value-added resellers (collectively, "Third-Party Developers") — to build, modify, deploy, host, customize, fork, port, rebrand, or otherwise work with the Software, a Modified Version, or any Derivative Work shall be jointly and severally liable with such Third-Party Developer for any unauthorized Commercial Use, breach of this License, or infringement of Licensor's intellectual property.**
-
-Without limiting the generality of the foregoing:
-
-1. **Joint and Several Liability.** The contracting company (the entity for whose benefit the work is performed) and each Third-Party Developer engaged by it (and any subcontractor of such Third-Party Developer) are each fully liable, individually and together, for the entirety of any damages, liquidated damages, license fees, disgorgement, and costs owed to Licensor. Licensor may pursue any one or more of them, in any combination, for the full amount.
-
-2. **No Defense of Delegation.** A contracting company cannot escape liability by claiming that the Third-Party Developer was solely responsible, that the contracting company did not write the code, that the Third-Party Developer represented the work as licensed, or that the contracting company did not know the Software was Fincept Terminal or a Derivative Work. The duty to verify license compliance is **non-delegable**.
-
-3. **No Defense of Lack of Knowledge.** Public availability of this License, the LICENSE file, the README, and the license notices embedded in the Software constitutes constructive notice. Ignorance of the license terms is not a defense for either the contracting company or the Third-Party Developer.
-
-4. **Affiliates, Successors, Phoenix Entities, and Beneficial Users.** Liability extends to all parents, subsidiaries, affiliates, successors, assignees, joint-venture partners, acquirers, and any other person or entity that, directly or indirectly, **funds, controls, benefits from, supplies personnel to, supplies infrastructure to, supplies data to, or receives output, derivative data, or services produced by the use of the Software**, regardless of corporate form, contractual privity, or absence thereof. **Beneficial use, not formal engagement, is the test of liability.** Corporate restructuring, asset transfers, name changes, dissolutions, mergers, acquisitions, share sales, or re-incorporations do not extinguish liability. Any entity that, within twenty-four (24) months before or after a breach, employs more than twenty-five percent (25%) of the same personnel, occupies the same premises, services the same customers, or operates from substantially the same code base as a violating entity shall be deemed a successor for all purposes of this License, irrespective of corporate form or asset transfer. Liability extends through any chain of staffing agencies, BPO/KPO firms, contractors, sub-contractors, labor-leasing entities, or shell companies, regardless of the number of intermediaries.
-
- **Acquirer Liability.** An acquirer of any entity that has used the Software is jointly and severally liable for unauthorized use occurring before, during, and after the acquisition, irrespective of whether the transaction is structured as an asset purchase, stock purchase, merger, or otherwise, and irrespective of any non-assumption clause in the acquisition agreement. Acquirers are deemed to assume Software-license liabilities by operation of this License, with notice provided by the public availability hereof. Licensee shall conduct or commission a software-composition analysis (SCA) before deploying any third-party software with finance functionality; failure to do so constitutes willful blindness.
-
- **Standstill on Transfer.** Upon receipt of any cease-and-desist notice, audit demand, or notice of breach, Licensee shall not transfer, license, assign, or sub-license the Software, any Derivative Work, related personnel, or related infrastructure to any affiliate or third party without Licensor's prior written consent. Any such transfer is void as against Licensor.
+## 2. What AGPL-3.0 means in practice
-5. **Officers, Directors, and Principals.** Where permitted by applicable law, Licensor reserves the right to pursue claims against the officers, directors, partners, and controlling shareholders of any violating entity for willful infringement, breach of fiduciary duty in connection with the infringement, or fraudulent concealment.
+AGPL-3.0 is **strong copyleft**, not a permissive licence. Read this section before you build on the code.
-6. **Indemnification by the Contracting Company.** The contracting company shall indemnify, defend, and hold harmless Licensor from and against any and all claims, losses, damages, fees, and costs arising from the acts or omissions of any Third-Party Developer it engages, regardless of whether the contracting company directed, knew of, or consented to such acts.
+| What you're doing | What AGPL-3.0 requires |
+|---|---|
+| Running the terminal on your own machine, modified or not, without distributing it | Nothing. No obligations. |
+| Distributing a build — internally or externally, modified or not | Provide the complete corresponding source of your version under AGPL-3.0. |
+| Running a modified version as a network service that other people reach | Provide the complete corresponding source of your version to those users, under AGPL-3.0 (AGPL § 13). |
+| Linking it into, or building it into, another product you ship | That product is a derivative work and falls under AGPL-3.0. |
-7. **Right to Joinder.** In any action against a Third-Party Developer, Licensor may, at its sole election, join the contracting company (and vice versa) as a co-defendant in the same proceeding, and the parties consent in advance to such joinder.
+Removing, replacing, or rewiring Fincept's APIs and data integrations does **not** change any of the above. The obligation attaches to the codebase, not to the data sources.
-8. **Public Notice Obligation.** Upon Licensor's request, a contracting company that engages a Third-Party Developer to work with the Software must provide Licensor, within ten (10) business days, with: (a) the legal name and contact details of the Third-Party Developer; (b) the scope of work; (c) copies of the relevant engagement agreement or statement of work redacted only as to commercial pricing terms; and (d) a list of all repositories, deployment locations, and personnel with access to the Software.
-
-9. **No Subcontracting Out of Liability.** Any contractual provision between a contracting company and a Third-Party Developer that purports to allocate or waive liability to Licensor — including indemnities, hold-harmless agreements, or "as-is" disclaimers running between them — shall have no effect against Licensor, who is not a party to such agreement.
-
-This Section 14 is a **material term** of this License. Any breach of it constitutes immediate grounds for termination, injunctive relief, and the maximum liquidated damages set forth in Section 13.
+There is no paid exemption from these terms for this repository. If AGPL-3.0 does not work for your organization, the answer is Enterprise, which is proprietary and carries no copyleft obligations to manage.
---
-## 15. Limitation of Liability
-
-TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL LICENSOR'S AGGREGATE LIABILITY UNDER OR IN CONNECTION WITH THIS LICENSE EXCEED THE TOTAL FEES PAID BY LICENSEE TO LICENSOR IN THE TWELVE (12) MONTHS IMMEDIATELY PRECEDING THE EVENT GIVING RISE TO LIABILITY, OR ONE HUNDRED INDIAN RUPEES (₹100), WHICHEVER IS GREATER. IN NO EVENT SHALL LICENSOR BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, LOST PROFITS, LOST DATA, LOSS OF GOODWILL, OR TRADING LOSSES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS APPLY REGARDLESS OF THE FORM OF ACTION, WHETHER IN CONTRACT, TORT, STRICT LIABILITY, OR OTHERWISE.
-
----
-
-## 16. Governing Law and Jurisdiction
-
-This License shall be governed by and construed in accordance with the laws of the Republic of India, without regard to its conflict-of-laws principles. The United Nations Convention on Contracts for the International Sale of Goods does not apply.
+## 3. Commercial, institutional and academic use
-**Primary Forum.** The courts of **Delhi, India** shall have exclusive jurisdiction over any dispute arising out of or relating to this License, at Licensor's election. Licensee irrevocably submits to the personal jurisdiction of such courts and **expressly waives any forum-non-conveniens defense, any objection of inconvenient forum, and any objection based on lack of personal jurisdiction** in proceedings filed by Licensor.
+**[Fincept Terminal Enterprise](https://fincept.in/enterprise)** is a separate, closed-source product. It is not this codebase, is not published here, and is not covered by AGPL-3.0.
-**Concurrent Forums (at Licensor's Election).** In addition to Delhi, Licensor may, at its sole election, bring proceedings in any forum in which Licensee is resident, incorporated, has assets, operates the Software, or directs services derived from the Software. Licensee consents in advance to non-exclusive jurisdiction in any such forum. Licensee irrevocably appoints Licensor as its agent for service of process in any jurisdiction in which Licensee operates, maintains assets, or directs services derived from the Software, where permitted by local law.
+| | Price |
+|---|---|
+| **Exclusive** | $99 / user / month |
+| **Exclusive+** | $199 / user / month |
+| **Exclusive Pro** | $299 / user / month |
+| **Academic bundle** — 5 Exclusive Pro seats | $699 / month |
-**Continuous Breach for Limitation Purposes.** Each act of unauthorized execution, distribution, modification, or use of the Software, and each day of continued use, constitutes a **separately accruing breach** for limitation-period purposes. License fees, liquidated damages, disgorgement of profits, and other monetary remedies accrue on a continuous-breach basis. The limitation period for each accrued breach runs independently from the date of that breach.
+Monthly billing, no annual lock-in, no seat minimum, 15% off on quarterly. **These are the only prices offered.** There is no custom, negotiated, or enterprise-tier pricing, and no bespoke licensing track.
-**No Waiver, Estoppel, or Acquiescence.** No silence, inaction, delay, public communication, social-media post, marketing statement, conference talk, or course of dealing by Licensor shall constitute a waiver, license, estoppel, acquiescence, laches, or implied license. Public-facing marketing or media that describes the Software as "free" or "open source" refers exclusively to the AGPL-3.0 option for individual non-commercial users and shall not be construed as a Commercial Use license, an implied license, a waiver, or a representation. Licensee may not rely on Licensor's failure to enforce against any third party.
+- Plans and full feature breakdown: [fincept.in/pricing](https://fincept.in/pricing)
+- Comparison against the open edition: [fincept.in/comparison](https://fincept.in/comparison)
+- Create an account: [fincept.in/enterprise/signup](https://fincept.in/enterprise/signup)
+- Universities and academic institutions: email **[email protected]**
-**Statutory Carve-Outs Narrowly Construed.** Any statutory fair-dealing, fair-use, reverse-engineering-for-interoperability, or government-use right asserted by Licensee shall be construed at the minimum extent required by the relevant statute. The burden of demonstrating that use falls within a statutory carve-out is on Licensee. Any use exceeding the statutory minimum is unauthorized. To the extent any government, sovereign, or public-sector entity asserts a statutory carve-out, Commercial License fees shall be paid at the rate published for governmental users, with no waiver of audit, attribution, or trademark rights.
-
-**Worldwide Equitable Relief.** Notwithstanding any provision of this Section, Licensor may seek injunctive or equitable relief in any court of competent jurisdiction worldwide to protect its intellectual property.
+Enterprise runs on a separate backend with separate user records. A free Fincept account does not sign in to it.
---
-## 17. General Provisions
-
-**Severability.** If any provision of this License is held invalid or unenforceable, the remaining provisions shall remain in full force and the invalid provision shall be reformed to the minimum extent necessary to make it enforceable while preserving its intent.
-
-**Entire Agreement.** This License, together with any executed Order Form, constitutes the entire agreement between the parties and supersedes all prior or contemporaneous communications, oral or written, on the subject matter.
-
-**No Waiver.** No failure or delay by Licensor to exercise any right shall operate as a waiver, nor shall any single or partial exercise preclude any other or further exercise.
+## 4. Trademarks
-**Assignment.** Licensee may not assign or transfer this License, by operation of law or otherwise, without Licensor's prior written consent. Any attempted assignment in violation of this provision is void. Licensor may assign this License freely.
+"Fincept", "Fincept Terminal", "Fincept Corporation", and the Fincept logo are trademarks of Fincept Corporation. Trademark rights are **not** granted by AGPL-3.0 and are expressly reserved.
-**Force Majeure.** Neither party is liable for failure to perform due to causes beyond its reasonable control, excluding payment obligations.
+Use of these marks in any forked, derivative, rebranded, or successor product — and any use in marketing, sales material, or product comparison by a for-profit competitor — requires prior written permission from Fincept Corporation. Removing or replacing the marks in a fork does not affect the AGPL-3.0 obligations attaching to the code.
-**Notices.** Notices to Licensor must be sent to [email protected] with a copy by registered post to Fincept Corporation's registered office.
-
-**Export Controls.** Licensee shall comply with all applicable export-control laws of India, the United States, the European Union, and any other applicable jurisdiction.
-
-**Non-Transferability.** Licenses are non-transferable. Annual licenses renew yearly unless cancelled with thirty (30) days' notice prior to the renewal date.
+AGPL-3.0 § 7(e) permits the licensor to require removal of licensor trademarks from modified versions; Fincept Corporation exercises that right. Rebrand your fork.
---
-## 18. How to Obtain a Commercial License
+## 5. Warranty and liability
-1. **Contact** — email **[email protected]** with: (a) legal name of the organization, (b) country of incorporation, (c) intended use case, (d) number of users, (e) whether you are using or plan to use a Modified Version or Derivative Work.
-2. **Agreement** — review and execute the Commercial License Agreement (this document, formalized as an Order Form).
-3. **Payment** — complete payment in accordance with the Order Form.
-4. **Access** — receive credentials and Commercial Use rights.
+The Software is provided **"as is"**, without warranty of any kind, express or implied, as set out in AGPL-3.0 §§ 15 and 16. Nothing in the Software, and no output generated by it, constitutes investment, legal, tax, accounting, or financial advice. It is not warranted for any use where failure could cause financial loss or regulatory breach.
---
-## Trademark Notice
+## 6. Effect of this version
-"Fincept", "Fincept Terminal", and the Fincept logo are trademarks of Fincept Corporation. All rights reserved. Use of these marks — including in any forked, derivative, rebranded, or commercial product — requires prior written permission.
+This document replaces the Fincept Terminal Commercial License v2.0 in its entirety. The commercial-licence requirement, audit and self-attestation obligations, liquidated-damages schedule, and joint-and-several-liability provisions set out in that version are **withdrawn and are not asserted against any user of this repository.**
-© 2025–2026 Fincept Corporation. All rights reserved.
+Copyright in the Software remains with Fincept Corporation. AGPL-3.0 remains in force, and its terms are enforceable as written.
---
-**Document Version:** 2.0
-**In Force From:** April 30, 2026
-**Status:** Current and binding. These terms remain in full force and effect indefinitely until expressly superseded by a subsequent version published by Fincept Corporation at this location. The date above marks the most recent revision; it is **not** an expiry date.
-
-**Scope of Application.** This License governs all current and future use of the Software, including use of historical versions, regardless of when those versions were originally published. Any Commercial Use of any version of Fincept Terminal — past, present, or future, including any branch, tag, release, or commit — is subject to the terms of this License.
+**Questions:** [email protected] · [Terms](https://fincept.in/terms) · [Privacy](https://fincept.in/privacy)
-For the open-source license terms, see [`/LICENSE`](../LICENSE).
+© 2025–2026 Fincept Corporation. Licensed under AGPL-3.0-or-later.
diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.md
index 0429f4e19..f4dd31b94 100644
--- a/docs/GETTING_STARTED.md
+++ b/docs/GETTING_STARTED.md
@@ -7,22 +7,28 @@ Welcome to Fincept Terminal! This guide will get you from zero to your first con
## What is Fincept Terminal?
-Fincept Terminal is an **open-source financial analysis platform** — a free, open-source alternative to legacy professional financial terminals. Version 4 is a native C++20 application built with Qt6.
+Fincept Terminal is a native C++20 desktop terminal for financial research — Qt6 UI, embedded Python 3.11 analytics, one binary.
+
+It ships in **two editions on one data core**:
+
+- **Open source** (this repository) — AGPL-3.0, free for learning, personal use and academic research. Ships one release a month. **This guide covers building it.**
+- **[Enterprise](https://fincept.in/enterprise)** — the private, closed-source build for funds, family offices and research desks: 41 modules, proprietary datasets, multi-agent research, live broker routing, SSO and an SLA, from $99/user/month. It is not built from this repository.
### The Big Picture
-**Current Reality:**
-- Legacy professional terminals: $20,000+/year per user
+**Current reality:**
+- Legacy professional terminals: ~$27,000/year per seat
- Industry-standard market data subscriptions: $20,000+/year
- Professional tools locked behind paywalls
-**Our Vision:**
-- 100% free and open source
-- Integrate 100+ data sources (stocks, crypto, forex, economic data, news, etc.)
-- AI-powered analysis and insights
+**What this repository is for:**
+- 100+ data source integrations (stocks, crypto, forex, economic data, news)
+- AI-powered analysis — bring your own LLM key
- Native C++ performance — no browser/JS overhead
- Built by the community, for the community
+Contributions land in the open-source edition. Private datasets, point-in-time history, included AI credits and live execution are [Enterprise](https://fincept.in/enterprise) features.
+
### Technology Decisions (and Why)
- **C++20 + Qt6** — Native performance, polished UI, single binary
diff --git a/docs/translations/README.de.md b/docs/translations/README.de.md
index 696f7b515..21131d785 100644
--- a/docs/translations/README.de.md
+++ b/docs/translations/README.de.md
@@ -1,216 +1,192 @@
-# Fincept-Terminal
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
-
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
### **Ihr Denken ist die einzige Grenze. Die Daten sind es nicht.**
Hochmoderne Financial-Intelligence-Plattform mit Finanzanalysen auf institutionellem Niveau, KI-Automatisierung und unbegrenzter Datenkonnektivität.
-[📥 Herunterladen](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 Dokumente](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 Diskussionen](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 Zwietracht](https://discord.gg/ae87a8ygbN)·[🤝Partner](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+[📥 Download](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 Preise](https://fincept.in/pricing) · [📖 Handbuch](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
+> [!IMPORTANT]
+> **Fincept Terminal gibt es in zwei Editionen.**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — der private, quelloffen nicht verfügbare Build für Fonds, Family Offices und Research-Desks. 41 Module, proprietäre Datensätze, Multi-Agenten-Research, Live-Broker-Routing, privater Datenraum, SSO und ein SLA, ab **99 $/Nutzer/Monat**. Hier arbeitet das Team täglich weiter — und dies ist die Edition, wenn Sie mit dem Terminal Geld verdienen.
+>
+> 📖 **Dieses Repository** — die kostenlose Open-Source-Edition unter AGPL-3.0, für Lernzwecke, private Nutzung und akademische Forschung. Es bleibt öffentlich, wird nicht gelöscht und erhält **ein Release pro Monat**.
+>
+> [**Welche Edition brauchen Sie? →**](#welche-edition-sollten-sie-nutzen) · [Vergleich](https://fincept.in/comparison) · [Preise](https://fincept.in/pricing)
-## Um
+---
-**Fincept Terminal vch**ist eine rein native C++20-Desktopanwendung. Es nutzt**Qt6**für Benutzeroberfläche und Rendering, eingebettet**Python**für Analysen und liefert eine Leistung professioneller Terminal-Klasse in einer einzigen nativen Binärdatei.
+## Über
-* * *
+**Fincept Terminal** ist ein natives C++20-Desktop-Terminal für Finanzresearch — Qt6-Oberfläche, eingebettete Python-3.11-Analytik, eine einzige Binärdatei, kein Electron.
-## Merkmale
+Es erscheint in **zwei Editionen auf einem gemeinsamen Datenkern**:
-| **Besonderheit** | **Beschreibung** |
-| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 📊**Multi-Asset-Analyse** | DCF-Modelle, Portfoliooptimierung, Risikometriken (VaR, Sharpe), Derivatpreisgestaltung über Aktien, Anleihen, Derivate, Portfolio und Alternativen via eingebettetes Python |
-| 🤖**KI-Agenten** | Über 20 Investorenpersönlichkeiten (Buffett, Dalio, Graham), Hedgefonds-Strategien, lokale LLM-Unterstützung, Multi-Provider (OpenAI, Anthropic, Gemini, Groq, DeepSeek, MiniMax, OpenRouter, Ollama) |
-| 🌐**Über 100 Datenanschlüsse** | DBnomics, Polygon, Kraken, Yahoo Finance, FRED, IWF, Weltbank, AkShare, Regierungs-APIs sowie optionale alternative Daten-Overlays wie Adanos-Marktstimmung für Aktienanalysen |
-| 📈**Echtzeithandel** | Krypto (Kraken/HyperLiquid WebSocket), Aktien, Algo-Handel, Papierhandelsmaschine |
-| 🔬**QuantLib Suite** | 18 quantitative Analysemodule – Preisgestaltung, Risiko, Stochastik, Volatilität, festverzinsliche Wertpapiere |
-| 🚢**Globale Intelligenz** | Maritime Verfolgung, geopolitische Analyse, Beziehungskartierung, Satellitendaten |
-| 🎨**Visuelle Arbeitsabläufe** | Knoteneditor für Automatisierungspipelines, MCP-Tool-Integration |
-| 🧠**AI Quant Lab** | ML-Modelle, Faktorerkennung, HFT, Reinforcement Learning Trading |
+| | **Open Source** — dieses Repo | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **Gedacht für** | Lernen, private Nutzung, akademische Forschung | Fonds, Family Offices, Research-Desks |
+| **Preis** | Kostenlos · AGPL-3.0 | Ab **99 $**/Nutzer/Monat |
+| **Release-Takt** | Ein Update pro Monat | Fortlaufend |
-* * *
+---
-## Installation
+## Welche Edition sollten Sie nutzen?
-### Option 1 – Vorgefertigte Binärdatei herunterladen (empfohlen)
+| Wenn Sie … sind | Nutzen Sie | Warum |
+|---|---|---|
+| Studierende, Hobbyisten oder unabhängig Lernende | **Open Source** | Wirklich kostenlos — und das bleibt so |
+| Akademisch Forschende | **Open Source** | Kostenlos für akademische Nutzung — Hochschulen mit Bedarf an verwalteten Plätzen: siehe Hochschulpaket unten |
+| Fonds, Family Office, Eigenhandel, Bank oder Fintech | **Enterprise** | Kein AGPL-Copyleft, dafür private Daten, Live-Routing, SSO und ein SLA |
+| Beruflich damit Geld verdienend | **Enterprise** | In der Praxis günstiger — und die einzige Edition mit täglicher Weiterentwicklung |
-Vorgefertigte Binärdateien sind auf der verfügbar[Seite „Veröffentlichungen“.](https://github.com/Fincept-Corporation/FinceptTerminal/releases). Keine Build-Tools erforderlich – einfach extrahieren und ausführen.
+> **Ehrlich gesagt:** Der offene Build ist echte Arbeit, kein beschnittenes Demo — aber er läuft auf kostenlosen öffentlichen Feeds, **Ihren** API-Schlüsseln und **Ihrem** LLM-Schlüssel, und jeder KI-Aufruf wird Ihnen pro Token in Rechnung gestellt, ohne Obergrenze. Community-Issues werden nach bestem Bemühen und ohne Reaktionszusage bearbeitet. Wenn Sie mit dem Terminal Ihr Geld verdienen, ist Enterprise der günstigere und sicherere Platz.
-| Plattform | Herunterladen | Laufen |
-| ------------------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **Windows x64** | `FinceptTerminal-Windows-x64.zip` | Extrahieren →`FinceptTerminal.exe` |
-| **Windows ARM64** | `FinceptTerminal-Windows-arm64.zip` | Extrahieren →`FinceptTerminal.exe` |
-| **Linux x64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x`→`./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS (Apple Silicon)** | `FinceptTerminal-macOS-arm64.tar.gz` | Extrahieren →`./FinceptTerminal` |
-| **macOS (Intel)** | `FinceptTerminal-macOS-x64.tar.gz` | Extrahieren →`./FinceptTerminal` |
-| **macOS (universell)** | `FinceptTerminal-macOS-universal.tar.gz` | Extrahieren →`./FinceptTerminal` |
+[**Enterprise ansehen →**](https://fincept.in/enterprise) · [Vollständiger Vergleich](https://fincept.in/comparison) · [Preise](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
-* * *
+---
-### Option 2 – Schnellstart (One-Click Build)
+## Open Source vs. Enterprise
-Klonen Sie das Setup-Skript und führen Sie es aus – es installiert alle Abhängigkeiten und erstellt die App automatisch:
+| | Open Source | **Enterprise** |
+|---|---|---|
+| **Lizenz** | AGPL-3.0 — starkes Copyleft. Wer ausliefert oder hostet, muss seine Änderungen offenlegen | Proprietär — keine Copyleft-Pflichten zu verwalten |
+| **Kosten** | Kostenlos — Daten- und LLM-Rechnungen zahlen Sie selbst | 99 $ / 199 $ / 299 $ pro Nutzer und Monat, alles inklusive |
+| **Module** | Kern-Terminal | **41 Module über 6 Desks** |
+| **Daten** | Kostenlose öffentliche Feeds, ratenbegrenzt, eigene Schlüssel nötig | Private und proprietäre Datensätze — längere Historie, schnellere Aktualisierung |
+| **Kurshistorie** | Was die Gratis-Stufen hergeben | 1 Jahr / 5 Jahre / unbegrenzt · **Point-in-Time** für ehrliche Backtests |
+| **KI-Budget** | Eigener LLM-Schlüssel, Abrechnung pro Token an Sie | 400 / 2.000 / 5.000 Credits pro Monat inklusive |
+| **KI-Research** | Einfacher Marktassistent | Multi-Agenten-Research, die **plant und delegiert** · Agent Studio · bis zu 53 Agenten · 6 Team-Modi |
+| **Privater Datenraum** | — | Ihre Filings und Modelle, nur von Ihren eigenen Agenten gelesen — nie zusammengeführt, nie zum Training genutzt |
+| **Handel** | Papierhandel + Broker-Anbindungen mit eigenen Schlüsseln | **Live-Broker-Routing + Live-Algo-Deployment** |
+| **Quant** | Community-Backtesting | Quant Lab, Alpha Arena, Volatilitätsanalytik, Point-in-Time-Backtests |
+| **Sicherheit & Compliance** | — | SSO/SAML, Audit-Logs, rollenbasierte Zugriffe, Datenisolierung |
+| **Support** | GitHub-Issues, nach bestem Bemühen, ohne Reaktionszusage | SLA-gestützte priorisierte Bearbeitung |
+| **Dokumentation** | Dieses Repo | [**700-seitiges Handbuch**](https://fincept.in/manual) — 41 Leitfäden, 472 Abschnitte |
+| **Plattformen** | Windows, macOS, Linux + gehostetes Web-Terminal | Windows 10/11, macOS 13+ (Apple Silicon), Linux |
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
+Enterprise läuft über ein **separates Konto** — kostenlose Fincept-Logins funktionieren dort nicht, und die App bleibt gesperrt, bis ein Abonnement hinterlegt ist. [Enterprise-Konto anlegen →](https://fincept.in/enterprise/signup)
-```bat
-# Windows — run from Developer Command Prompt for VS 2022
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-setup.bat
-```
+---
-Das Skript übernimmt Folgendes: Compilerprüfung, CMake, Qt6, Python, Build und Start.
+## Enterprise — sechs Desks, 41 Module
-* * *
+| Desk | Funktion |
+|---|---|
+| **Agentic Research** · 6 | Agenten planen die Arbeit, delegieren an Spezialisten, lesen Live-Daten und Ihren Datenraum und liefern belegte Notizen |
+| **Quant Lab & Backtesting** · 4 | Signalforschung, Point-in-Time-Backtests, Volatilitätsflächen |
+| **Deep Fundamental Research** · 8 | Aktienanalyse, Bewertung, Derivate, M&A-Analytik |
+| **Markets & Execution** · 7 | Live-Aktien, Krypto und Prognosemärkte, Broker-Routing, Algo-Deployment |
+| **Macro & Global Intelligence** · 7 | Statistik, Regierungsdaten, Geopolitik, Schifffahrtsrouten |
+| **Ihr eigener Workspace** · 9 | Dashboard, Tabellenkalkulation, Notizen, Dateien, Code, Report-Builder |
-### Option 3 – Docker
+[Produkte ansehen →](https://fincept.in/products)
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+### Preise
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+| | **Exclusive** | **Exclusive+** ★ beliebteste | **Exclusive Pro** |
+|---|---|---|---|
+| | **99 $**/Nutzer/Monat | **199 $**/Nutzer/Monat | **299 $**/Nutzer/Monat |
+| KI-Credits / Monat | 400 | 2.000 | 5.000 |
+| Portfolios · Watchlists | 1 · 3 | 10 · 25 | Unbegrenzt |
+| Kurshistorie | 1 Jahr | 5 Jahre | Unbegrenzt |
+| Enthaltene Plätze | 1 | 1 | 2 |
+| Deep Research + Agenten-Teams | — | ✓ | ✓ |
+| Broker-Konto verknüpfen | — | ✓ | ✓ |
+| Live-Broker-Handel + Algo-Deployment | — | — | ✓ |
-> **Notiz:**Docker ist in erster Linie für Linux gedacht. macOS und Windows erfordern eine zusätzliche XServer-Konfiguration.
+Monatliche Abrechnung · keine Jahresbindung · kein Platz-Minimum · **15 % Rabatt bei quartalsweiser Zahlung**. Das ergibt **1.188–3.588 $ pro Nutzer und Jahr** gegenüber rund **27.000 $** für einen Bloomberg-Platz — [zum vollständigen Vergleich](https://fincept.in/comparison).
-* * *
+**Hochschulen und akademische Einrichtungen:** ein pauschales Paket — **5 Exclusive-Pro-Plätze für 699 $/Monat** (Listenpreis 1.495 $). E-Mail an [[email protected]](mailto:[email protected]).
-### Option 4 – Aus dem Quellcode erstellen (manuell)
+Diese drei Pläne plus das Hochschulpaket sind die vollständige Preisliste. Es gibt keine individuellen oder verhandelten Enterprise-Preise und keine separate kommerzielle Lizenz mehr zu kaufen.
-> **Versionen sind gepinnt** (Qt 6.7.2, CMake 3.27.7, MSVC 19.38 / GCC 12.3 / Apple Clang 15.0, Python 3.11.9). Um Übersetzungsdrift zu vermeiden, folgen Sie der offiziellen englischen Anleitung:
->
-> 👉 **[README.md (English) — Build from Source](../../README.md#option-4--build-from-source-manual)**
->
-> Schnellstart mit CMake-Presets:
-> ```bash
-> ./setup.sh # Linux / macOS — automatisiertes Setup
-> setup.bat # Windows (VS 2022 Developer Cmd)
->
-> # Oder manuell:
-> cd FinceptTerminal/fincept-qt
-> cmake --preset linux-release && cmake --build --preset linux-release
-> cmake --preset macos-release && cmake --build --preset macos-release
-> cmake --preset win-release && cmake --build --preset win-release
-> ```
+[**Enterprise-Konto anlegen**](https://fincept.in/enterprise/signup) · [**Demo buchen**](https://calendly.com/nikultilak/fincept-terminal-demo) · [Handbuch lesen](https://fincept.in/manual)
-* * *
+---
-## Was uns auszeichnet
+## Open-Source-Edition installieren
-**Fincept-Terminal**ist eine Open-Source-Finanzplattform, die für diejenigen entwickelt wurde, die sich nicht durch traditionelle Software einschränken lassen. Wir konkurrieren weiter**Analysetiefe**Und**Datenzugänglichkeit**– nicht auf Insiderinformationen oder exklusiven Feeds.
+Fertige Installationsprogramme für **Windows x64**, **Linux x64** (`.run` / `.deb` / `.rpm`) und **macOS (Apple Silicon)** finden Sie auf der [Releases-Seite](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest).
-Aktuelle Builds unterstützen auch optional**Adanos-Marktstimmung**Konnektivität in**Datenquellen → Alternative Daten**. Bei entsprechender Konfiguration kann Equity Research quellenübergreifende Schnappschüsse der Einzelhandelsstimmung auf Reddit, X, Finanznachrichten und Polymarket anzeigen. Ohne aktive Adanos-Verbindung bleibt die Funktion inaktiv und der Rest der App verhält sich genauso wie zuvor.
+**Aus dem Quellcode bauen** — Linux/macOS: `git clone … && ./setup.sh`. Windows, manuelle Builds, die fixierte Toolchain (**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**) und Fehlerbehebung stehen in **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)**. Die Versionen sind fixiert — neuere oder ältere werden nicht unterstützt.
-- **Native Leistung**– C++20 mit Qt6, kein Electron/Web-Overhead
-- **Einzelne Binärdatei**– kein Node.js, keine Browser-Laufzeitumgebung, kein JavaScript-Bundler
-- **Vollständiges Buy-Side-Analyst-Toolkit**— Aktien, Portfolio, Derivate, Anleihen, Corporate Finance, Alternativen
-- **Über 100 Datenanschlüsse**– von Yahoo Finance bis hin zu Regierungsdatenbanken
-- **Kostenlos und Open Source**(AGPL-3.0) mit kommerziellen Lizenzen verfügbar
+> Sie suchen den Enterprise-Build? Er hat eigene signierte Installer für Windows, macOS und Linux hinter einem Enterprise-Login — [hier erhältlich](https://fincept.in/enterprise).
-* * *
+---
-## Roadmap
+## Was im offenen Build steckt
-| Zeitleiste | Meilenstein |
-| ------------------- | ----------------------------------------------------------------------------------- |
-| **1. Quartal 2026** | Echtzeit-Streaming, erweitertes Backtesting, Broker-Integrationen |
-| **Erbrechen 2026** | Optionsstrategie-Builder, Multi-Portfolio-Management, über 50 KI-Agenten |
-| **KZ 2026** | Programmatische API, Benutzeroberfläche für ML-Training, institutionelle Funktionen |
-| **Zukunft** | Mobiler Begleiter, Cloud-Synchronisierung, Community-Marktplatz |
+| | |
+|---|---|
+| **Multi-Asset-Analytik** | DCF, Portfoliooptimierung, VaR/Sharpe, Derivatebewertung, Anleihen, Alternatives — über eingebettetes Python |
+| **QuantLib-Suite** | 18 quantitative Module — Pricing, Risiko, Stochastik, Volatilität, Fixed Income |
+| **KI-Agenten** | 37 Agenten aus den Bereichen Trader/Investor, Ökonomie und Geopolitik; eigener Schlüssel nötig (OpenAI, Anthropic, Gemini, Groq, DeepSeek, OpenRouter, Ollama) |
+| **100+ Datenkonnektoren** | DBnomics, FRED, IWF, Weltbank, AkShare, Polygon, Kraken, Yahoo Finance, Behörden-APIs |
+| **Handel** | Krypto- und Aktien-Feeds, Papierhandels-Engine, 16 Broker-Anbindungen |
+| **Automatisierung** | Visueller Node-Editor, MCP-Tool-Integration, AI Quant Lab (ML, Faktorforschung, RL) |
+| **Globale Aufklärung** | Maritimes Tracking, geopolitische Analyse, Beziehungskartierung |
-* * *
+Natives C++20 · Qt6 · eingebettetes Python 3.11 · eine Binärdatei · kein Node.js, keine Browser-Runtime.
-## Mitwirken
+---
-Wir gestalten die Zukunft der Finanzanalyse – gemeinsam.
+## Wie dieses Repo gepflegt wird
-**Beitragen:**Neue Datenkonnektoren, KI-Agenten, Analysemodule, C++-Bildschirme, Dokumentation
+Dieses Repository **bleibt öffentlich und wird nicht gelöscht**. Alles bereits Veröffentlichte bleibt veröffentlicht.
-- [Mitwirkender Leitfaden](docs/CONTRIBUTING.md)
-- [Leitfaden für C++-Beiträge](fincept-qt/CONTRIBUTING.md)
-- [Leitfaden für Python-Mitwirkende](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [Fehler melden](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [Anforderungsfunktion](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+Es erscheint jetzt **ein Release pro Monat** statt fortlaufender Entwicklung, weil das Team täglich an Enterprise arbeitet. Issues und Pull Requests werden weiterhin geprüft, Fixes kommen im Monatstakt. Sicherheitsmeldungen an [[email protected]](mailto:[email protected]).
-* * *
+---
-## Für Universitäten und Pädagogen
-
-**Bringen Sie professionelle Finanzanalysen in Ihren Unterricht.**
+## Mitwirken
-- **799 $/Monat**für 20 Konten
-- Voller Zugriff auf Fincept-Daten und APIs
-- Perfekt für Finanz-, Wirtschafts- und Datenwissenschaftskurse
-- Integrierte Analytik für Aktien, Portfolio, Derivate, Anleihen und Wirtschaft
+Neue Datenkonnektoren, KI-Agenten, Analysemodule, C++-Screens und Dokumentation sind alle willkommen.
-**Interessiert?**E-Mail**[[email protected]](mailto:[email protected])**mit dem Namen Ihrer Institution.
+[Contributing-Leitfaden](../CONTRIBUTING.md) · [C++-Leitfaden](../CPP_CONTRIBUTOR_GUIDE.md) · [Python-Leitfaden](../PYTHON_CONTRIBUTOR_GUIDE.md) · [Architektur](../ARCHITECTURE.md) · [Fehler melden](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [Feature vorschlagen](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-[Details zur Universitätslizenzierung](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+---
-* * *
+## Ebenfalls von Fincept
-## Lizenz
+- **[Fincept Data API](https://docs.fincept.in)** — über 500 REST-Endpunkte, mehr als 423.000 Instrumente, über 2.000 Quellen. Kostenlose Stufe zu jedem Konto.
+- **[Quantcept](https://quantcept.io)** — quelloffenes, KI-gestütztes Finanz-Terminal für die Kommandozeile (Apache-2.0).
-**Doppellizenz: AGPL-3.0 (Open Source) + kommerziell**
+---
-### Open Source (AGPL-3.0)
+## Lizenz
-- Kostenlos für den persönlichen, pädagogischen und nichtkommerziellen Gebrauch
-- Erfordert Freigabeänderungen, wenn es verteilt oder als Netzwerkdienst verwendet wird
-- Volle Transparenz des Quellcodes
+**AGPL-3.0-or-later** — vollständiger Text in [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE).
-### Kommerzielle Lizenz
+Kostenlos für private Nutzung, Lernzwecke und akademische Forschung. AGPL-3.0 ist **starkes Copyleft, nicht permissiv**: Wer einen modifizierten Build verbreitet oder als Dienst betreibt, den andere erreichen, muss seine Änderungen unter derselben Lizenz veröffentlichen. Für die meisten Rechtsabteilungen endet die Diskussion genau hier — und deshalb nehmen Firmen **[Enterprise](https://fincept.in/enterprise)**, das proprietär ist und keine Copyleft-Pflichten mit sich bringt. Private, nicht verbreitete Nutzung bringt keinerlei Pflichten mit sich.
-- Erforderlich für die geschäftliche Nutzung oder den kommerziellen Zugriff auf Fincept-Daten/APIs
-- Kontakt:**[[email protected]](mailto:[email protected])**
-- Einzelheiten:[Leitfaden für kommerzielle Lizenzen](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+Fincept verkauft für dieses Repository **keine separate kommerzielle oder akademische Lizenz mehr**. Kommerzieller, institutioneller und universitärer Bedarf wird über **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** zu den oben genannten Preisen abgedeckt.
-### Marken
+**Marken.** „Fincept", „Fincept Terminal" und das Fincept-Logo sind Marken der Fincept Corporation. Die Verwendung in geforkten, abgeleiteten, umbenannten oder kommerziellen Produkten bedarf der vorherigen schriftlichen Genehmigung.
-„Fincept Terminal“ und „Fincept“ sind Marken der Fincept Corporation.
+Fragen: [[email protected]](mailto:[email protected]) · [AGB](https://fincept.in/terms) · [Datenschutz](https://fincept.in/privacy)
-© 2025-2026 Fincept Corporation. Alle Rechte vorbehalten.
+© 2025–2026 Fincept Corporation. Alle Rechte vorbehalten.
-* * *
+---
<div align="center">
### **Ihr Denken ist die einzige Grenze. Die Daten sind es nicht.**
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
-
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+⭐ **Stern vergeben** · 🔄 **Teilen** · 🤝 **Mitwirken**
-⭐**Stern**· 🔄**Aktie**· 🤝**Beitragen**
+<sub>Englisches Original: <a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.es.md b/docs/translations/README.es.md
index 9c522de1a..f37b6f5f5 100644
--- a/docs/translations/README.es.md
+++ b/docs/translations/README.es.md
@@ -1,216 +1,192 @@
-# Terminal Fincept
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
-
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
### **Tu pensamiento es el único límite. Los datos no lo son.**
-Plataforma de inteligencia financiera de última generación con análisis financiero de nivel institucional, automatización de IA y conectividad de datos ilimitada.
+Plataforma de inteligencia financiera de última generación, con analítica de nivel institucional, automatización con IA y conectividad de datos sin límites.
-[📥 Descargar](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 Documentos](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 Discusiones](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 Discordia](https://discord.gg/ae87a8ygbN)·[🤝 Socio](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+[📥 Descargar](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 Precios](https://fincept.in/pricing) · [📖 Manual](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
+> [!IMPORTANT]
+> **Fincept Terminal se distribuye en dos ediciones.**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — la versión privada y de código cerrado para fondos, family offices y mesas de análisis. 41 módulos, conjuntos de datos propietarios, investigación multiagente, enrutamiento en vivo a brókers, sala de datos privada, SSO y SLA, desde **99 $/usuario/mes**. Es donde el equipo desarrolla a diario, y es la edición que necesitas si el terminal es tu medio de vida.
+>
+> 📖 **Este repositorio** — la edición libre de código abierto bajo AGPL-3.0, para aprendizaje, uso personal e investigación académica. Sigue siendo público, no se eliminará y recibe **una versión al mes**.
+>
+> [**¿Cuál necesitas? →**](#qué-edición-deberías-usar) · [Comparativa](https://fincept.in/comparison) · [Precios](https://fincept.in/pricing)
+
+---
## Acerca de
-**Terminal fincept vch**es una aplicación de escritorio nativa pura de C++20. se utiliza**qt6**para interfaz de usuario y renderizado, integrado**Pitón**para análisis y ofrece rendimiento de clase terminal profesional en un único binario nativo.
+**Fincept Terminal** es un terminal de escritorio nativo en C++20 para investigación financiera — interfaz Qt6, analítica con Python 3.11 embebido, un solo binario, sin Electron.
-* * *
+Se distribuye en **dos ediciones sobre un mismo núcleo de datos**:
-## Características
+| | **Código abierto** — este repo | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **Pensado para** | Aprendizaje, uso personal, investigación académica | Fondos, family offices, mesas de análisis |
+| **Precio** | Gratis · AGPL-3.0 | Desde **99 $**/usuario/mes |
+| **Cadencia de versiones** | Una actualización al mes | Continua |
-| **Característica** | **Descripción** |
-| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| 📊**Análisis multiactivo** | Modelos DCF, optimización de cartera, métricas de riesgo (VaR, Sharpe), valoración de derivados en renta variable, renta fija, derivados, cartera y alternativos a través de Python integrado |
-| 🤖**Agentes de IA** | Más de 20 personas de inversores (Buffett, Dalio, Graham), estrategias de fondos de cobertura, soporte de LLM local, múltiples proveedores (OpenAI, Anthropic, Gemini, Groq, DeepSeek, MiniMax, OpenRouter, Ollama) |
-| 🌐**Más de 100 conectores de datos** | DBnomics, Polygon, Kraken, Yahoo Finance, FRED, FMI, Banco Mundial, AkShare, API gubernamentales, además de superposiciones de datos alternativos opcionales, como el sentimiento del mercado de Adanos para la investigación de acciones. |
-| 📈**Comercio en tiempo real** | Cripto (Kraken/HyperLiquid WebSocket), acciones, comercio algorítmico, motor de comercio de papel |
-| 🔬**Suite QuantLib** | 18 módulos de análisis cuantitativo: fijación de precios, riesgo, estocástico, volatilidad, renta fija |
-| 🚢**Inteligencia global** | Seguimiento marítimo, análisis geopolítico, mapeo de relaciones, datos satelitales. |
-| 🎨**Flujos de trabajo visuales** | Editor de nodos para canales de automatización, integración de herramientas MCP |
-| 🧠**Laboratorio cuantitativo de IA** | Modelos de aprendizaje automático, descubrimiento de factores, HFT, comercio de aprendizaje por refuerzo |
+---
-* * *
+## ¿Qué edición deberías usar?
-## Instalación
+| Si eres… | Usa | Por qué |
+|---|---|---|
+| Estudiante, aficionado o autodidacta | **Código abierto** | Es realmente gratis, y va a seguir siéndolo |
+| Investigador académico | **Código abierto** | Gratis para uso académico — universidades que quieran licencias gestionadas: ver el paquete académico abajo |
+| Un fondo, family office, mesa propietaria, banco o fintech | **Enterprise** | El copyleft de AGPL no aplica, y obtienes datos privados, enrutamiento en vivo, SSO y SLA |
+| Alguien que hace esto profesionalmente, por dinero | **Enterprise** | En la práctica sale más barato, y es la única edición en desarrollo diario |
-### Opción 1: descargar binario prediseñado (recomendado)
+> **La versión honesta.** La edición abierta es trabajo real, no una demo capada — pero funciona con fuentes públicas gratuitas, **tus** claves de API y **tu** clave de LLM, y cada llamada de IA se te factura por token, sin techo. Las incidencias de la comunidad se atienden según disponibilidad, sin compromiso de respuesta. Si el terminal es tu forma de ganarte la vida, Enterprise es la licencia más barata y más segura.
-Los archivos binarios prediseñados están disponibles en[Página de lanzamientos](https://github.com/Fincept-Corporation/FinceptTerminal/releases). No se requieren herramientas de compilación: simplemente extraiga y ejecute.
+[**Ver Enterprise →**](https://fincept.in/enterprise) · [Comparativa completa](https://fincept.in/comparison) · [Precios](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
-| Plataforma | Descargar | Correr |
-| ------------------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **Ventanas x64** | `FinceptTerminal-Windows-x64.zip` | Extraer →`FinceptTerminal.exe` |
-| **ventanas ARM64** | `FinceptTerminal-Windows-arm64.zip` | Extraer →`FinceptTerminal.exe` |
-| **Linuxx64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x`→`./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS (Apple Silicio)** | `FinceptTerminal-macOS-arm64.tar.gz` | Extraer →`./FinceptTerminal` |
-| **MacOS (Intel)** | `FinceptTerminal-macOS-x64.tar.gz` | Extraer →`./FinceptTerminal` |
-| **macOS (universal)** | `FinceptTerminal-macOS-universal.tar.gz` | Extraer →`./FinceptTerminal` |
+---
-* * *
+## Código abierto vs. Enterprise
-### Opción 2: Inicio rápido (compilación con un clic)
+| | Código abierto | **Enterprise** |
+|---|---|---|
+| **Licencia** | AGPL-3.0 — copyleft fuerte. Si lo distribuyes o lo alojas, publicas tus cambios | Propietaria — sin obligaciones de copyleft que gestionar |
+| **Coste** | Gratis — pagas tus propias facturas de datos y de LLM | 99 $ / 199 $ / 299 $ por usuario y mes, todo incluido |
+| **Módulos** | Terminal base | **41 módulos en 6 mesas** |
+| **Datos** | Fuentes públicas gratuitas, con límite de peticiones, claves propias | Conjuntos de datos privados y propietarios — más histórico, refresco más rápido |
+| **Histórico de precios** | Lo que permitan las capas gratuitas | 1 año / 5 años / ilimitado · **point-in-time** para backtests honestos |
+| **Presupuesto de IA** | Tu propia clave de LLM, facturada por token | 400 / 2.000 / 5.000 créditos incluidos al mes |
+| **Investigación con IA** | Asistente de mercado básico | Investigación multiagente que **planifica y delega** · Agent Studio · hasta 53 agentes · 6 modos de equipo |
+| **Sala de datos privada** | — | Tus informes y modelos, leídos solo por tus agentes — nunca agrupados, nunca usados para entrenar |
+| **Trading** | Papel + integraciones de bróker con claves propias | **Enrutamiento en vivo a brókers + despliegue de algos en vivo** |
+| **Quant** | Backtesting comunitario | Quant Lab, Alpha Arena, analítica de volatilidad, backtests point-in-time |
+| **Seguridad y cumplimiento** | — | SSO/SAML, registros de auditoría, control de acceso por roles, aislamiento de datos |
+| **Soporte** | Issues de GitHub, según disponibilidad, sin compromiso | Atención prioritaria con SLA |
+| **Documentación** | Este repo | [**Manual de 700 páginas**](https://fincept.in/manual) — 41 guías, 472 secciones |
+| **Plataformas** | Windows, macOS, Linux + terminal web alojado | Windows 10/11, macOS 13+ (Apple silicon), Linux |
-Clona y ejecuta el script de instalación: instala todas las dependencias y crea la aplicación automáticamente:
+Enterprise funciona con una **cuenta independiente** — las cuentas gratuitas de Fincept no sirven para entrar, y la aplicación permanece bloqueada hasta que se asocia una suscripción. [Crear cuenta Enterprise →](https://fincept.in/enterprise/signup)
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
+---
-```bat
-# Windows — run from Developer Command Prompt for VS 2022
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-setup.bat
-```
+## Enterprise — seis mesas, 41 módulos
-El script maneja: verificación del compilador, CMake, Qt6, Python, compilación y lanzamiento.
+| Mesa | Qué hace |
+|---|---|
+| **Agentic Research** · 6 | Los agentes planifican el trabajo, delegan en especialistas, leen datos en vivo y tu sala de datos, y devuelven notas con fuentes |
+| **Quant Lab & Backtesting** · 4 | Investigación de señales, backtests point-in-time, superficies de volatilidad |
+| **Deep Fundamental Research** · 8 | Análisis de renta variable, valoración, derivados, analítica de M&A |
+| **Markets & Execution** · 7 | Renta variable, cripto y mercados de predicción en vivo, enrutamiento a brókers, despliegue de algos |
+| **Macro & Global Intelligence** · 7 | Estadística, datos gubernamentales, geopolítica, rutas marítimas |
+| **Tu propio espacio de trabajo** · 9 | Panel, hoja de cálculo, notas, archivos, código, generador de informes |
-* * *
+[Ver los productos →](https://fincept.in/products)
-### Opción 3: ventana acoplable
+### Precios
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+| | **Exclusive** | **Exclusive+** ★ el más elegido | **Exclusive Pro** |
+|---|---|---|---|
+| | **99 $**/usuario/mes | **199 $**/usuario/mes | **299 $**/usuario/mes |
+| Créditos de IA / mes | 400 | 2.000 | 5.000 |
+| Carteras · listas de seguimiento | 1 · 3 | 10 · 25 | Ilimitadas |
+| Histórico de precios | 1 año | 5 años | Ilimitado |
+| Licencias incluidas | 1 | 1 | 2 |
+| Deep research + equipos de agentes | — | ✓ | ✓ |
+| Vinculación de cuenta de bróker | — | ✓ | ✓ |
+| Trading en vivo + despliegue de algos | — | — | ✓ |
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+Facturación mensual · sin permanencia anual · sin mínimo de licencias · **15 % de descuento trimestral**. Son **1.188–3.588 $ por usuario y año**, frente a unos **27.000 $** de una licencia Bloomberg — [ver la comparativa completa](https://fincept.in/comparison).
-> **Nota:**Docker está destinado principalmente a Linux. macOS y Windows requieren una configuración XServer adicional.
+**Universidades e instituciones académicas:** un paquete único — **5 licencias Exclusive Pro por 699 $/mes** (precio de lista 1.495 $). Escribe a [[email protected]](mailto:[email protected]).
-* * *
+Estos tres planes más el paquete académico son la lista de precios completa. No hay precios enterprise negociados ni a medida, ni una licencia comercial aparte que comprar.
-### Opción 4: compilar desde el código fuente (manual)
+[**Crear cuenta Enterprise**](https://fincept.in/enterprise/signup) · [**Reservar una demo**](https://calendly.com/nikultilak/fincept-terminal-demo) · [Leer el manual](https://fincept.in/manual)
-> **Las versiones están ancladas** (Qt 6.7.2, CMake 3.27.7, MSVC 19.38 / GCC 12.3 / Apple Clang 15.0, Python 3.11.9). Para evitar divergencias de traducción, consulte las instrucciones oficiales en inglés:
->
-> 👉 **[README.md (English) — Build from Source](../../README.md#option-4--build-from-source-manual)**
->
-> Inicio rápido con presets de CMake:
-> ```bash
-> ./setup.sh # Linux / macOS — instalación automatizada
-> setup.bat # Windows (VS 2022 Developer Cmd)
->
-> # O manual:
-> cd FinceptTerminal/fincept-qt
-> cmake --preset linux-release && cmake --build --preset linux-release
-> cmake --preset macos-release && cmake --build --preset macos-release
-> cmake --preset win-release && cmake --build --preset win-release
-> ```
+---
-* * *
+## Instalar la edición de código abierto
-## Lo que nos diferencia
+Los instaladores para **Windows x64**, **Linux x64** (`.run` / `.deb` / `.rpm`) y **macOS (Apple silicon)** están en la [página de releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest).
-**Terminal Fincept**es una plataforma financiera de código abierto creada para aquellos que se niegan a verse limitados por el software tradicional. Competimos en**profundidad analítica**y**accesibilidad a los datos**– no en información privilegiada ni en feeds exclusivos.
+**Compilar desde el código** — Linux/macOS: `git clone … && ./setup.sh`. Windows, compilaciones manuales, el conjunto de herramientas fijado (**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**) y la resolución de problemas están en **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)**. Las versiones están fijadas — otras no están soportadas.
-Las versiones recientes también admiten opciones opcionales.**Sentimiento del mercado de Adanos**conectividad en**Fuentes de datos → Datos alternativos**. Cuando se configura, Equity Research puede mostrar instantáneas del sentimiento minorista de fuentes cruzadas en Reddit, X, noticias financieras y Polymarket. Sin una conexión activa de Adanos, la función permanece inactiva y el resto de la aplicación se comporta exactamente como antes.
+> ¿Buscas la compilación Enterprise? Tiene sus propios instaladores firmados para Windows, macOS y Linux, detrás de un inicio de sesión Enterprise — [consíguelos aquí](https://fincept.in/enterprise).
-- **Rendimiento nativo**— C++20 con Qt6, sin sobrecarga de Electron/web
-- **binario único**— sin Node.js, sin tiempo de ejecución del navegador, sin paquete de JavaScript
-- **Kit completo de analista buy-side**— renta variable, cartera, derivados, renta fija, finanzas corporativas, alternativos
-- **Más de 100 conectores de datos**— desde Yahoo Finance hasta las bases de datos gubernamentales
-- **Gratis y de código abierto**(AGPL-3.0) con licencias comerciales disponibles
+---
-* * *
+## Qué incluye la edición abierta
-## Hoja de ruta
+| | |
+|---|---|
+| **Analítica multiactivo** | DCF, optimización de carteras, VaR/Sharpe, valoración de derivados, renta fija, alternativos — vía Python embebido |
+| **Suite QuantLib** | 18 módulos cuantitativos — pricing, riesgo, estocástico, volatilidad, renta fija |
+| **Agentes de IA** | 37 agentes de trader/inversor, economía y geopolítica; con tu propia clave (OpenAI, Anthropic, Gemini, Groq, DeepSeek, OpenRouter, Ollama) |
+| **Más de 100 conectores** | DBnomics, FRED, FMI, Banco Mundial, AkShare, Polygon, Kraken, Yahoo Finance, APIs gubernamentales |
+| **Trading** | Feeds de cripto y renta variable, motor de paper trading, 16 integraciones de bróker |
+| **Automatización** | Editor de nodos visual, integración de herramientas MCP, AI Quant Lab (ML, descubrimiento de factores, RL) |
+| **Inteligencia global** | Seguimiento marítimo, análisis geopolítico, mapa de relaciones |
-| Línea de tiempo | Hito |
-| ---------------------------- | ---------------------------------------------------------------------------------------------------------------- |
-| **Primer trimestre de 2026** | Transmisión en tiempo real, backtesting avanzado, integraciones de corredores |
-| **vómitos 2026** | Creador de estrategias de opciones, gestión de carteras múltiples, más de 50 agentes de IA |
-| **KZ 2026** | API programática, interfaz de usuario de capacitación de aprendizaje automático, características institucionales |
-| **Futuro** | Compañero móvil, sincronización en la nube, mercado comunitario |
+C++20 nativo · Qt6 · Python 3.11 embebido · un solo binario · sin Node.js ni navegador.
-* * *
+---
-## Contribuyendo
+## Cómo se mantiene este repositorio
-Estamos construyendo juntos el futuro del análisis financiero.
+Este repositorio **sigue siendo público y no se va a eliminar**. Todo lo ya publicado permanece publicado.
-**Contribuir:**Nuevos conectores de datos, agentes de IA, módulos de análisis, pantallas C++, documentación
+Ahora publica **una versión al mes** en lugar de desarrollo continuo, porque el trabajo diario del equipo está en Enterprise. Las issues y los pull requests se siguen revisando, y las correcciones llegan en el ciclo mensual. Los informes de seguridad, a [[email protected]](mailto:[email protected]).
-- [Guía contribuyente](docs/CONTRIBUTING.md)
-- [Guía de contribución de C++](fincept-qt/CONTRIBUTING.md)
-- [Guía para contribuyentes de Python](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [Informar error](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [Solicitar función](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+---
-* * *
+## Contribuir
-## Para universidades y educadores
+Nuevos conectores de datos, agentes de IA, módulos de analítica, pantallas C++ y documentación: todo es bienvenido.
-**Lleve análisis financieros de nivel profesional a su salón de clases.**
+[Guía de contribución](../CONTRIBUTING.md) · [Guía C++](../CPP_CONTRIBUTOR_GUIDE.md) · [Guía Python](../PYTHON_CONTRIBUTOR_GUIDE.md) · [Arquitectura](../ARCHITECTURE.md) · [Reportar un fallo](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [Proponer una función](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-- **$799/mes**por 20 cuentas
-- Acceso completo a los datos y API de Fincept
-- Perfecto para cursos de finanzas, economía y ciencia de datos
-- Análisis integrado de renta variable, cartera, derivados, renta fija y economía
+---
-**¿Interesado?**Correo electrónico**[[email protected]](mailto:[email protected])**con el nombre de su institución.
+## También de Fincept
-[Detalles de la licencia universitaria](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+- **[Fincept Data API](https://docs.fincept.in)** — más de 500 endpoints REST, más de 423.000 instrumentos, más de 2.000 fuentes. Capa gratuita incluida con cualquier cuenta.
+- **[Quantcept](https://quantcept.io)** — terminal financiero de línea de comandos, de código abierto y con IA (Apache-2.0).
-* * *
+---
## Licencia
-**Licencia dual: AGPL-3.0 (código abierto) + Comercial**
-
-### Código abierto (AGPL-3.0)
-
-- Gratis para uso personal, educativo y no comercial
-- Requiere modificaciones para compartir cuando se distribuye o se utiliza como servicio de red
-- Transparencia total del código fuente
+**AGPL-3.0-or-later** — texto completo en [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE).
-### Licencia Comercial
+Gratis para uso personal, aprendizaje e investigación académica. AGPL-3.0 es **copyleft fuerte, no permisiva**: si distribuyes una compilación modificada, o la ejecutas como servicio al que acceden otras personas, debes publicar tus cambios bajo la misma licencia. Para la mayoría de los departamentos legales, ahí se acaba la discusión — y por eso las firmas eligen **[Enterprise](https://fincept.in/enterprise)**, que es propietaria y no arrastra obligaciones de copyleft. El uso personal, sin distribución, no conlleva ninguna obligación.
-- Requerido para uso comercial o para acceder comercialmente a Fincept Data/API
-- Contacto:**[[email protected]](mailto:[email protected])**
-- Detalles:[Guía de licencia comercial](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+Fincept **ya no vende una licencia comercial o académica aparte** para este repositorio. Las necesidades comerciales, institucionales y universitarias se cubren con **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** a los precios publicados arriba.
-### Marcas registradas
+**Marcas.** «Fincept», «Fincept Terminal» y el logotipo de Fincept son marcas de Fincept Corporation. Su uso en cualquier producto bifurcado, derivado, renombrado o comercial requiere autorización previa por escrito.
-"Fincept Terminal" y "Fincept" son marcas comerciales de Fincept Corporation.
+Consultas: [[email protected]](mailto:[email protected]) · [Términos](https://fincept.in/terms) · [Privacidad](https://fincept.in/privacy)
-© 2025-2026 Corporación Fincept. Reservados todos los derechos.
+© 2025–2026 Fincept Corporation. Todos los derechos reservados.
-* * *
+---
<div align="center">
### **Tu pensamiento es el único límite. Los datos no lo son.**
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
-
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+⭐ **Estrella** · 🔄 **Comparte** · 🤝 **Contribuye**
-⭐**Estrella**· 🔄**Compartir**· 🤝**Contribuir**
+<sub>Original en inglés: <a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.fr.md b/docs/translations/README.fr.md
index 2e14c2cce..46e64cfd2 100644
--- a/docs/translations/README.fr.md
+++ b/docs/translations/README.fr.md
@@ -1,281 +1,192 @@
-# Terminal Fincept
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
-
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
### **Votre réflexion est la seule limite. Les données ne le sont pas.**
-Plateforme de renseignement financier de pointe avec analyses financières de niveau institutionnel, automatisation de l'IA et connectivité de données illimitée.
+Plateforme d'intelligence financière de pointe : analyse de niveau institutionnel, automatisation par IA et connectivité de données sans limite.
-[📥 Télécharger](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 Documents](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 Discussions](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 Discorde](https://discord.gg/ae87a8ygbN)·[🤝 Partenaire](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+[📥 Télécharger](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 Tarifs](https://fincept.in/pricing) · [📖 Manuel](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
-
-## À propos
-
-**Fincept Terminal vch**est une application de bureau C++20 purement native. Il utilise**Qt6**pour l'interface utilisateur et le rendu, intégré**Python**pour l'analyse et offre des performances de classe terminal professionnel dans un seul binaire natif.
-
-* * *
-
-## Caractéristiques
-
-| **Fonctionnalité** | **Description** |
-| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 📊**Analyses multi-actifs** | Modèles DCF, optimisation de portefeuille, mesures de risque (VaR, Sharpe), tarification des produits dérivés sur actions, taux, dérivés, portefeuille et alternatifs via Python intégré |
-| 🤖**AI Agents** | Plus de 20 personnalités d'investisseurs (Buffett, Dalio, Graham), stratégies de hedge funds, support LLM local, multi-fournisseurs (OpenAI, Anthropic, Gemini, Groq, DeepSeek, MiniMax, OpenRouter, Ollama) |
-| 🌐**Plus de 100 connecteurs de données** | DBnomics, Polygon, Kraken, Yahoo Finance, FRED, FMI, Banque mondiale, AkShare, API gouvernementales, ainsi que des superpositions de données alternatives facultatives telles que le sentiment du marché Adanos pour la recherche sur les actions. |
-| 📈**Trading en temps réel** | Crypto (Kraken/HyperLiquid WebSocket), actions, trading algo, moteur de trading papier |
-| 🔬**QuantLib Suite** | 18 modules d'analyse quantitative — tarification, risque, stochastique, volatilité, titres à revenu fixe |
-| 🚢**Renseignement mondial** | Suivi maritime, analyse géopolitique, cartographie des relations, données satellite |
-| 🎨**Flux de travail visuels** | Éditeur de nœuds pour les pipelines d'automatisation, intégration de l'outil MCP |
-| 🧠**AI Quant Lab** | Modèles ML, découverte de facteurs, HFT, trading d'apprentissage par renforcement |
-
-* * *
-
-## Installation
-
-### Option 1 — Télécharger le binaire prédéfini (recommandé)
-
-Des binaires prédéfinis sont disponibles sur le[Page des versions](https://github.com/Fincept-Corporation/FinceptTerminal/releases). Aucun outil de construction requis : il suffit d'extraire et d'exécuter.
-
-| Plate-forme | Télécharger | Courir |
-| -------------------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **Windows x64** | `FinceptTerminal-Windows-x64.zip` | Extraire →`FinceptTerminal.exe` |
-| **WindowsARM64** | `FinceptTerminal-Windows-arm64.zip` | Extraire →`FinceptTerminal.exe` |
-| **Linuxx64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x`→`./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS (Apple Silicium)** | `FinceptTerminal-macOS-arm64.tar.gz` | Extraire →`./FinceptTerminal` |
-| **macOS (Intel)** | `FinceptTerminal-macOS-x64.tar.gz` | Extraire →`./FinceptTerminal` |
-| **macOS (universel)** | `FinceptTerminal-macOS-universal.tar.gz` | Extraire →`./FinceptTerminal` |
-
-* * *
-
-### Option 2 — Démarrage rapide (construction en un clic)
-
-Clonez et exécutez le script d'installation : il installe toutes les dépendances et crée automatiquement l'application :
+> [!IMPORTANT]
+> **Fincept Terminal existe en deux éditions.**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — la version privée, à code fermé, destinée aux fonds, family offices et desks de recherche. 41 modules, jeux de données propriétaires, recherche multi-agents, routage courtier en direct, data room privée, SSO et SLA, à partir de **99 $/utilisateur/mois**. C'est là que l'équipe développe au quotidien, et c'est l'édition à prendre si le terminal est votre gagne-pain.
+>
+> 📖 **Ce dépôt** — l'édition open source gratuite sous AGPL-3.0, pour l'apprentissage, l'usage personnel et la recherche académique. Il reste public, ne sera pas supprimé, et reçoit **une version par mois**.
+>
+> [**Laquelle vous faut-il ? →**](#choisir-votre-édition) · [Comparatif](https://fincept.in/comparison) · [Tarifs](https://fincept.in/pricing)
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
+---
-```bat
-# Windows — run from Developer Command Prompt for VS 2022
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-setup.bat
-```
+## À propos
-Le script gère : la vérification du compilateur, CMake, Qt6, Python, la construction et le lancement.
+**Fincept Terminal** est un terminal de bureau natif en C++20 dédié à la recherche financière — interface Qt6, analyse Python 3.11 embarquée, un seul binaire, sans Electron.
-* * *
+Il existe en **deux éditions sur un socle de données commun** :
-### Option 3 — Docker
+| | **Open source** — ce dépôt | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **Conçu pour** | L'apprentissage, l'usage personnel, la recherche académique | Fonds, family offices, desks de recherche |
+| **Prix** | Gratuit · AGPL-3.0 | À partir de **99 $**/utilisateur/mois |
+| **Rythme des versions** | Une mise à jour par mois | En continu |
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+---
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+## Choisir votre édition
-> **Note:**Docker est principalement destiné à Linux. macOS et Windows nécessitent une configuration XServer supplémentaire.
+| Si vous êtes… | Prenez | Pourquoi |
+|---|---|---|
+| Étudiant, amateur ou autodidacte | **Open source** | Vraiment gratuit, et ça ne changera pas |
+| Chercheur académique | **Open source** | Gratuit pour l'usage académique — les universités souhaitant des postes gérés : voir l'offre académique ci-dessous |
+| Un fonds, family office, desk propriétaire, une banque ou une fintech | **Enterprise** | Le copyleft AGPL ne s'applique pas, et vous obtenez données privées, routage en direct, SSO et SLA |
+| Quelqu'un qui en vit professionnellement | **Enterprise** | Moins cher en pratique, et la seule édition en développement quotidien |
-* * *
+> **Pour être franc.** L'édition ouverte est un vrai produit, pas une démo bridée — mais elle fonctionne avec des flux publics gratuits, **vos** clés d'API et **votre** clé LLM, et chaque appel d'IA vous est facturé au token, sans plafond. Les tickets communautaires sont traités au mieux, sans engagement de délai. Si le terminal est votre outil de travail, Enterprise est le poste le moins cher et le plus sûr.
-### Option 4 — Construire à partir de la source (manuel)
+[**Découvrir Enterprise →**](https://fincept.in/enterprise) · [Comparatif complet](https://fincept.in/comparison) · [Tarifs](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
-> **Les versions sont épinglées** (Qt 6.7.2, CMake 3.27.7, MSVC 19.38 / GCC 12.3 / Apple Clang 15.0, Python 3.11.9). Pour éviter la dérive de traduction, suivez les instructions officielles en anglais :
->
-> 👉 **[README.md (English) — Build from Source](../../README.md#option-4--build-from-source-manual)**
->
-> Démarrage rapide avec les presets CMake :
-> ```bash
-> ./setup.sh # Linux / macOS — installation automatisée
-> setup.bat # Windows (VS 2022 Developer Cmd)
->
-> # Ou manuellement :
-> cd FinceptTerminal/fincept-qt
-> cmake --preset linux-release && cmake --build --preset linux-release
-> cmake --preset macos-release && cmake --build --preset macos-release
-> cmake --preset win-release && cmake --build --preset win-release
-> ```
+---
-<details>
-<summary>Instructions originales (obsolètes — conservées pour référence)</summary>
+## Open source vs Enterprise
-#### Conditions préalables
+| | Open source | **Enterprise** |
+|---|---|---|
+| **Licence** | AGPL-3.0 — copyleft fort. Si vous distribuez ou hébergez, vous publiez vos modifications | Propriétaire — aucune obligation de copyleft à gérer |
+| **Coût** | Gratuit — vous payez vos propres factures de données et de LLM | 99 $ / 199 $ / 299 $ par utilisateur et par mois, tout compris |
+| **Modules** | Terminal de base | **41 modules répartis sur 6 desks** |
+| **Données** | Flux publics gratuits, limités en débit, clés à fournir | Jeux de données privés et propriétaires — historique plus profond, rafraîchissement plus rapide |
+| **Historique de prix** | Ce que permettent les offres gratuites | 1 an / 5 ans / illimité · **point-in-time** pour des backtests honnêtes |
+| **Budget IA** | Votre clé LLM, facturée au token | 400 / 2 000 / 5 000 crédits inclus par mois |
+| **Recherche IA** | Assistant de marché basique | Recherche multi-agents qui **planifie et délègue** · Agent Studio · jusqu'à 53 agents · 6 modes d'équipe |
+| **Data room privée** | — | Vos documents et modèles, lus uniquement par vos agents — jamais mutualisés, jamais utilisés pour l'entraînement |
+| **Trading** | Papier + intégrations courtier avec vos clés | **Routage courtier en direct + déploiement d'algos en direct** |
+| **Quant** | Backtesting communautaire | Quant Lab, Alpha Arena, analyse de volatilité, backtests point-in-time |
+| **Sécurité et conformité** | — | SSO/SAML, journaux d'audit, contrôle d'accès par rôle, isolation des données |
+| **Support** | Issues GitHub, au mieux, sans engagement de réponse | Traitement prioritaire adossé à un SLA |
+| **Documentation** | Ce dépôt | [**Manuel de 700 pages**](https://fincept.in/manual) — 41 guides, 472 sections |
+| **Plateformes** | Windows, macOS, Linux + terminal web hébergé | Windows 10/11, macOS 13+ (Apple silicon), Linux |
-| Outil | Version | Fenêtres | Linux | macOS |
-| ------------------- | ------- | --------------------------------------------------------------- | --------------------- | ---------------------------------- |
-| **Git** | dernier | `winget install Git.Git` | `apt install git` | `brew install git` |
-| **CMake** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
-| **Compilateur C++** | C++20 | MSVC2022 ([Studio visuel](https://visualstudio.microsoft.com/)) | `apt install g++` | XcodeCLT :`xcode-select --install` |
-| **Qt6** | 6.5+ | Voir ci-dessous | Voir ci-dessous | Voir ci-dessous |
-| **Python** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+Enterprise fonctionne avec un **compte distinct** — les identifiants Fincept gratuits ne permettent pas de s'y connecter, et l'application reste verrouillée tant qu'aucun abonnement n'y est rattaché. [Créer un compte Enterprise →](https://fincept.in/enterprise/signup)
-#### Installer Qt6
+---
-**Fenêtres :**
+## Enterprise — six desks, 41 modules
-```powershell
-# Via Qt online installer (recommended — includes windeployqt)
-# Download from https://www.qt.io/download-qt-installer
-# Select: Qt 6.x > MSVC 2022 64-bit
+| Desk | Rôle |
+|---|---|
+| **Agentic Research** · 6 | Les agents planifient le travail, délèguent aux spécialistes, lisent les données en direct et votre data room, et rendent des notes sourcées |
+| **Quant Lab & Backtesting** · 4 | Recherche de signaux, backtests point-in-time, surfaces de volatilité |
+| **Deep Fundamental Research** · 8 | Analyse actions, valorisation, dérivés, analyse M&A |
+| **Markets & Execution** · 7 | Actions, crypto et marchés prédictifs en direct, routage courtier, déploiement d'algos |
+| **Macro & Global Intelligence** · 7 | Statistiques, données publiques, géopolitique, routes maritimes |
+| **Votre espace de travail** · 9 | Tableau de bord, tableur, notes, fichiers, code, générateur de rapports |
-# Or via winget
-winget install Qt.QtCreator
-```
+[Voir les produits →](https://fincept.in/products)
-**Linux (Ubuntu/Debian) :**
+### Tarifs
-```bash
-sudo apt install -y \
- qt6-base-dev qt6-charts-dev qt6-tools-dev \
- libqt6sql6-sqlite libqt6websockets6-dev \
- libgl1-mesa-dev libglu1-mesa-dev
-```
+| | **Exclusive** | **Exclusive+** ★ le plus choisi | **Exclusive Pro** |
+|---|---|---|---|
+| | **99 $**/utilisateur/mois | **199 $**/utilisateur/mois | **299 $**/utilisateur/mois |
+| Crédits IA / mois | 400 | 2 000 | 5 000 |
+| Portefeuilles · listes de suivi | 1 · 3 | 10 · 25 | Illimités |
+| Historique de prix | 1 an | 5 ans | Illimité |
+| Postes inclus | 1 | 1 | 2 |
+| Deep research + équipes d'agents | — | ✓ | ✓ |
+| Liaison compte courtier | — | ✓ | ✓ |
+| Trading en direct + déploiement d'algos | — | — | ✓ |
-**macOS :**
+Facturation mensuelle · sans engagement annuel · sans minimum de postes · **15 % de remise au trimestre**. Soit **1 188 à 3 588 $ par utilisateur et par an**, contre environ **27 000 $** pour un poste Bloomberg — [voir le comparatif complet](https://fincept.in/comparison).
-```bash
-brew install qt
-```
+**Universités et établissements académiques :** une offre forfaitaire — **5 postes Exclusive Pro pour 699 $/mois** (prix catalogue 1 495 $). Écrivez à [[email protected]](mailto:[email protected]).
-#### Construire
+Ces trois formules et l'offre académique constituent la totalité de la grille tarifaire. Il n'existe ni tarif enterprise sur mesure ou négocié, ni licence commerciale distincte à acheter.
-```bash
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal/fincept-qt
+[**Créer un compte Enterprise**](https://fincept.in/enterprise/signup) · [**Réserver une démo**](https://calendly.com/nikultilak/fincept-terminal-demo) · [Lire le manuel](https://fincept.in/manual)
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+---
-# Windows (from Developer Command Prompt for VS 2022)
-cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/Qt/6.x.x/msvc2022_64"
-cmake --build build --config Release --parallel
-```
+## Installer l'édition open source
-#### Courir
+Les installateurs pour **Windows x64**, **Linux x64** (`.run` / `.deb` / `.rpm`) et **macOS (Apple silicon)** se trouvent sur la [page des releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest).
-```bash
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal.exe # Windows
-```
+**Compiler depuis les sources** — Linux/macOS : `git clone … && ./setup.sh`. Windows, compilation manuelle, chaîne d'outils figée (**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**) et dépannage : voir **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)**. Les versions sont figées — les autres ne sont pas prises en charge.
-</details>
+> Vous cherchez la version Enterprise ? Elle dispose de ses propres installateurs signés pour Windows, macOS et Linux, derrière une authentification Enterprise — [à récupérer ici](https://fincept.in/enterprise).
-* * *
+---
-## Ce qui nous distingue
+## Ce que contient l'édition ouverte
-**Terminal Fincept**est une plateforme financière open source conçue pour ceux qui refusent d'être limités par les logiciels traditionnels. Nous sommes en compétition sur**profondeur d'analyse**et**accessibilité des données**– pas sur les informations privilégiées ou les flux exclusifs.
+| | |
+|---|---|
+| **Analyse multi-actifs** | DCF, optimisation de portefeuille, VaR/Sharpe, valorisation de dérivés, taux, actifs alternatifs — via Python embarqué |
+| **Suite QuantLib** | 18 modules quantitatifs — pricing, risque, stochastique, volatilité, taux |
+| **Agents IA** | 37 agents trader/investisseur, économie et géopolitique ; avec votre propre clé (OpenAI, Anthropic, Gemini, Groq, DeepSeek, OpenRouter, Ollama) |
+| **Plus de 100 connecteurs** | DBnomics, FRED, FMI, Banque mondiale, AkShare, Polygon, Kraken, Yahoo Finance, API publiques |
+| **Trading** | Flux crypto et actions, moteur de paper trading, 16 intégrations courtier |
+| **Automatisation** | Éditeur de nœuds visuel, intégration d'outils MCP, AI Quant Lab (ML, découverte de facteurs, RL) |
+| **Renseignement global** | Suivi maritime, analyse géopolitique, cartographie de relations |
-Les versions récentes prennent également en charge les options facultatives**Adanos Market Sentiment**connectivité dans**Sources de données → Données alternatives**. Une fois configuré, Equity Research peut générer des instantanés du sentiment des détaillants multi-sources sur Reddit, X, Finance News et Polymarket. Sans connexion Adanos active, la fonctionnalité reste inactive et le reste de l'application se comporte exactement comme avant.
+C++20 natif · Qt6 · Python 3.11 embarqué · un seul binaire · sans Node.js ni navigateur.
-- **Performances natives**— C++20 avec Qt6, pas de surcharge Electron/Web
-- **Binaire simple**- pas de Node.js, pas d'exécution de navigateur, pas de bundle JavaScript
-- **Boîte à outils complète d'analyste buy-side**— actions, portefeuille, dérivés, taux, finance d'entreprise, alternatifs
-- **Plus de 100 connecteurs de données**— de Yahoo Finance aux bases de données gouvernementales
-- **Gratuit et open source**(AGPL-3.0) avec licences commerciales disponibles
+---
-* * *
+## Comment ce dépôt est maintenu
-## Feuille de route
+Ce dépôt **reste public et ne sera pas supprimé**. Tout ce qui a été publié le reste.
-| Chronologie | Jalon |
-| ----------- | -------------------------------------------------------------------------------------------- |
-| **T1 2026** | Streaming en temps réel, backtesting avancé, intégrations de courtiers |
-| **Q2 2026** | Constructeur de stratégie d'options, gestion multi-portefeuilles, plus de 50 agents IA |
-| **KZ 2026** | API programmatique, interface utilisateur de formation ML, fonctionnalités institutionnelles |
-| **Avenir** | Compagnon mobile, synchronisation cloud, marché communautaire |
+Il passe à **une version par mois** plutôt qu'un développement continu, l'équipe travaillant au quotidien sur Enterprise. Les issues et pull requests sont toujours examinées, et les correctifs arrivent au rythme mensuel. Signalements de sécurité : [[email protected]](mailto:[email protected]).
-* * *
+---
## Contribuer
-Nous construisons l’avenir de l’analyse financière – ensemble.
-
-**Contribuer:**Nouveaux connecteurs de données, agents IA, modules d'analyse, écrans C++, documentation
-
-- [Guide de contribution](docs/CONTRIBUTING.md)
-- [Guide de contribution C++](fincept-qt/CONTRIBUTING.md)
-- [Guide du contributeur Python](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [Signaler un bug](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [Fonctionnalité de demande](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+Nouveaux connecteurs de données, agents IA, modules d'analyse, écrans C++ et documentation : tout est bienvenu.
-* * *
+[Guide de contribution](../CONTRIBUTING.md) · [Guide C++](../CPP_CONTRIBUTOR_GUIDE.md) · [Guide Python](../PYTHON_CONTRIBUTOR_GUIDE.md) · [Architecture](../ARCHITECTURE.md) · [Signaler un bug](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [Proposer une fonctionnalité](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-## Pour les universités et les enseignants
+---
-**Apportez des analyses financières de qualité professionnelle à votre classe.**
+## Également chez Fincept
-- **799 $/mois**pour 20 comptes
-- Accès complet aux données et API Fincept
-- Parfait pour les cours de finance, d'économie et de science des données
-- Analyses intégrées actions, portefeuille, dérivés, taux et économie
+- **[Fincept Data API](https://docs.fincept.in)** — plus de 500 endpoints REST, plus de 423 000 instruments, plus de 2 000 sources. Palier gratuit inclus avec tout compte.
+- **[Quantcept](https://quantcept.io)** — terminal financier en ligne de commande, open source et propulsé par l'IA (Apache-2.0).
-**Intéressé?**E-mail**[[email protected]](mailto:[email protected])**avec le nom de votre établissement.
-
-[Détails de la licence universitaire](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-* * *
+---
## Licence
-**Double licence : AGPL-3.0 (Open Source) + Commerciale**
-
-### Source ouverte (AGPL-3.0)
-
-- Gratuit pour un usage personnel, éducatif et non commercial
-- Nécessite des modifications de partage lorsqu'il est distribué ou utilisé comme service réseau
-- Transparence totale du code source
+**AGPL-3.0-or-later** — texte intégral dans [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE).
-### Licence commerciale
+Gratuit pour l'usage personnel, l'apprentissage et la recherche académique. AGPL-3.0 est une licence **copyleft forte, non permissive** : si vous distribuez une version modifiée, ou si vous l'exploitez comme un service accessible à d'autres, vous devez publier vos modifications sous la même licence. Pour la plupart des directions juridiques, c'est la ligne qui clôt le débat — d'où le choix d'**[Enterprise](https://fincept.in/enterprise)** par les sociétés : propriétaire, sans aucune obligation de copyleft à gérer. L'usage personnel non distribué n'entraîne aucune obligation.
-- Requis pour un usage professionnel ou pour accéder commercialement aux données/API Fincept
-- Contact:**[[email protected]](mailto:[email protected])**
-- Détails:[Guide des licences commerciales](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+Fincept **ne vend plus de licence commerciale ou académique distincte** pour ce dépôt. Les besoins commerciaux, institutionnels et universitaires sont couverts par **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** aux tarifs publiés ci-dessus.
-### Marques déposées
+**Marques.** « Fincept », « Fincept Terminal » et le logo Fincept sont des marques de Fincept Corporation. Leur usage dans tout produit forké, dérivé, renommé ou commercial requiert une autorisation écrite préalable.
-« Fincept Terminal » et « Fincept » sont des marques commerciales de Fincept Corporation.
+Questions : [[email protected]](mailto:[email protected]) · [Conditions](https://fincept.in/terms) · [Confidentialité](https://fincept.in/privacy)
-© 2025-2026 Fincept Corporation. Tous droits réservés.
+© 2025–2026 Fincept Corporation. Tous droits réservés.
-* * *
+---
<div align="center">
### **Votre réflexion est la seule limite. Les données ne le sont pas.**
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
-
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+⭐ **Star** · 🔄 **Partager** · 🤝 **Contribuer**
-⭐**Étoile**· 🔄**Partager**· 🤝**Contribuer**
+<sub>Version originale anglaise : <a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.hi.md b/docs/translations/README.hi.md
index 472314ba5..7f4c60007 100644
--- a/docs/translations/README.hi.md
+++ b/docs/translations/README.hi.md
@@ -1,282 +1,192 @@
-# फिनसेप्ट टर्मिनल
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+### **आपकी सोच ही एकमात्र सीमा है। डेटा नहीं।**
-### **आपकी सोच ही एकमात्र सीमा है. डेटा नहीं है.**
+संस्थागत स्तर के वित्तीय विश्लेषण, AI ऑटोमेशन और असीमित डेटा कनेक्टिविटी वाला अत्याधुनिक फाइनेंशियल इंटेलिजेंस प्लेटफ़ॉर्म।
-सीएफए-स्तरीय एनालिटिक्स, एआई ऑटोमेशन और असीमित डेटा कनेक्टिविटी के साथ अत्याधुनिक वित्तीय खुफिया मंच।
+[📥 डाउनलोड](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 मूल्य](https://fincept.in/pricing) · [📖 मैनुअल](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-[📥 Download](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 दस्तावेज़](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬चर्चाएँ](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 कलह](https://discord.gg/ae87a8ygbN)·[🤝साथी](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
-
-## के बारे में
-
-**फिनसेप्ट टर्मिनल वीसीएच**एक शुद्ध देशी C++20 डेस्कटॉप एप्लिकेशन है - पिछले टॉरी/रिएक्ट/रस्ट स्टैक से एक पूर्ण पुनर्लेखन। यह उपयोगकर्ता है**Qt6**यूआई और रेंडरिंग के लिए, एंबेडेड**अजगर**एनालिटिक्स के लिए, और एकल देशी बाइनरी में ब्लूमबर्ग-टर्मिनल-क्लास प्रदर्शन प्रदान करता है।
-
-* * *
-
-## विशेषताएँ
-
-| **विशेषता** | **विवरण** |
-| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| 📊**सीएफए-स्तर विश्लेषिकी** | डीसीएफ मॉडल, पोर्टफोलियो अनुकूलन, जोखिम मेट्रिक्स (वीएआर, शार्प), एम्बेडेड पायथन के माध्यम से डेरिवेटिव मूल्य निर्धारण |
-| 🤖**एआई एजेंट** | 20+ निवेशक व्यक्तित्व (बफेट, डेलियो, ग्राहम), हेज फंड रणनीतियाँ, स्थानीय एलएलएम समर्थन, बहु-प्रदाता (ओपनएआई, एंथ्रोपिक, जेमिनी, ग्रोक, डीपसीक, मिनीमैक्स, ओपनराउटर, ओलामा) |
-| 🌐**100+ डेटा कनेक्टर** | डीबीनॉमिक्स, पॉलीगॉन, क्रैकन, याहू फाइनेंस, एफआरईडी, आईएमएफ, विश्व बैंक, अक्शेयर, सरकारी एपीआई, साथ ही वैकल्पिक वैकल्पिक-डेटा ओवरले जैसे कि इक्विटी रिसर्च के लिए एडानोस मार्केट सेंटीमेंट |
-| 📈**रीयल-टाइम ट्रेडिंग** | क्रिप्टो (क्रैकेन/हाइपरलिक्विड वेबसॉकेट), इक्विटी, एल्गो ट्रेडिंग, पेपर ट्रेडिंग इंजन |
-| 🔬**क्वांटलिब सुइट** | 18 मात्रात्मक विश्लेषण मॉड्यूल - मूल्य निर्धारण, जोखिम, स्टोकेस्टिक, अस्थिरता, निश्चित आय |
-| 🚢**ग्लोबल इंटेलिजेंस** | समुद्री ट्रैकिंग, भू-राजनीतिक विश्लेषण, संबंध मानचित्रण, उपग्रह डेटा |
-| 🎨**विज़ुअल वर्कफ़्लोज़** | स्वचालन पाइपलाइनों के लिए नोड संपादक, एमसीपी उपकरण एकीकरण |
-| 🧠**एआई क्वांट लैब** | एमएल मॉडल, कारक खोज, एचएफटी, सुदृढीकरण शिक्षण ट्रेडिंग |
-
-* * *
-
-## इंस्टालेशन
-
-### विकल्प 1 - पूर्व-निर्मित बाइनरी डाउनलोड करें (अनुशंसित)
-
-पूर्व-निर्मित बायनेरिज़ पर उपलब्ध हैं[पेज जारी करता है](https://github.com/Fincept-Corporation/FinceptTerminal/releases). किसी निर्माण उपकरण की आवश्यकता नहीं है - बस निकालें और चलाएं।
-
-| प्लैटफ़ॉर्म | Download | दौड़ना |
-| ------------------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **विंडोज़ x64** | `FinceptTerminal-Windows-x64.zip` | निकालें →`FinceptTerminal.exe` |
-| **विंडोज़ एआरएम64** | `FinceptTerminal-Windows-arm64.zip` | निकालें →`FinceptTerminal.exe` |
-| **लिनक्स x64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x`→`./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS (एप्पल सिलिकॉन)** | `FinceptTerminal-macOS-arm64.tar.gz` | निकालें →`./FinceptTerminal` |
-| **मैकओएस (इंटेल)** | `FinceptTerminal-macOS-x64.tar.gz` | निकालें →`./FinceptTerminal` |
-| **मैकओएस (यूनिवर्सल)** | `FinceptTerminal-macOS-universal.tar.gz` | निकालें →`./FinceptTerminal` |
-
-* * *
-
-### विकल्प 2 - त्वरित प्रारंभ (एक-क्लिक निर्माण)
-
-सेटअप स्क्रिप्ट को क्लोन करें और चलाएँ - यह सभी निर्भरताएँ स्थापित करता है और स्वचालित रूप से ऐप बनाता है:
-
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
+> [!IMPORTANT]
+> **Fincept Terminal दो संस्करणों में उपलब्ध है।**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — फंड्स, फैमिली ऑफिस और रिसर्च डेस्क के लिए बनाया गया निजी, क्लोज़्ड-सोर्स बिल्ड। 41 मॉड्यूल, प्रोप्राइटरी डेटासेट, मल्टी-एजेंट रिसर्च, लाइव ब्रोकर रूटिंग, निजी डेटारूम, SSO और SLA — **$99/उपयोगकर्ता/माह** से शुरू। टीम रोज़ाना यहीं काम करती है, और अगर टर्मिनल से आपकी कमाई होती है तो यही संस्करण लेना चाहिए।
+>
+> 📖 **यह रिपॉज़िटरी** — AGPL-3.0 के तहत मुफ़्त ओपन-सोर्स संस्करण, सीखने, निजी उपयोग और शैक्षणिक शोध के लिए। यह सार्वजनिक रहेगा, हटाया नहीं जाएगा, और **महीने में एक रिलीज़** देता है।
+>
+> [**आपको कौन सा चाहिए? →**](#कौन-सा-संस्करण-चुनें) · [तुलना](https://fincept.in/comparison) · [मूल्य](https://fincept.in/pricing)
-```bat
-# Windows — run from Developer Command Prompt for VS 2022
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-setup.bat
-```
+---
-स्क्रिप्ट हैंडल करती है: कंपाइलर चेक, सीएमके, क्यूटी6, पायथन, बिल्ड और लॉन्च।
+## परिचय
-* * *
+**Fincept Terminal** वित्तीय शोध के लिए बना एक नेटिव C++20 डेस्कटॉप टर्मिनल है — Qt6 इंटरफ़ेस, एम्बेडेड Python 3.11 एनालिटिक्स, एक ही बाइनरी, कोई Electron नहीं।
-### विकल्प 3 - डॉकर
+यह **एक ही डेटा कोर पर दो संस्करणों** में आता है:
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+| | **ओपन सोर्स** — यह रिपो | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **किसके लिए** | सीखना, निजी उपयोग, शैक्षणिक शोध | फंड्स, फैमिली ऑफिस, रिसर्च डेस्क |
+| **मूल्य** | मुफ़्त · AGPL-3.0 | **$99**/उपयोगकर्ता/माह से |
+| **रिलीज़ चक्र** | महीने में एक अपडेट | निरंतर |
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+---
-> **टिप्पणी:**डॉकर मुख्य रूप से लिनक्स के लिए है। macOS और Windows को अतिरिक्त XServer कॉन्फ़िगरेशन की आवश्यकता होती है।
+## कौन सा संस्करण चुनें
-* * *
+| यदि आप हैं… | चुनें | क्यों |
+|---|---|---|
+| छात्र, शौकिया या स्वतंत्र रूप से सीखने वाले | **ओपन सोर्स** | सचमुच मुफ़्त है, और आगे भी रहेगा |
+| शैक्षणिक शोधकर्ता | **ओपन सोर्स** | शैक्षणिक उपयोग के लिए मुफ़्त — प्रबंधित सीटें चाहने वाले विश्वविद्यालय नीचे शैक्षणिक बंडल देखें |
+| फंड, फैमिली ऑफिस, प्रॉप डेस्क, बैंक या फिनटेक | **Enterprise** | AGPL कॉपीलेफ्ट लागू नहीं होता, और निजी डेटा, लाइव रूटिंग, SSO तथा SLA मिलता है |
+| पेशेवर रूप से, कमाई के लिए यह काम करने वाले | **Enterprise** | व्यवहार में सस्ता, और रोज़ाना विकसित हो रहा एकमात्र संस्करण |
-### विकल्प 4 - स्रोत से निर्माण (मैनुअल)
+> **साफ़ बात।** ओपन बिल्ड असली काम है, कोई अधूरा डेमो नहीं — लेकिन यह मुफ़्त सार्वजनिक फीड, **आपकी** API कुंजियों और **आपकी** LLM कुंजी पर चलता है, और हर AI कॉल प्रति-टोकन आपके ही खाते में जाता है, बिना किसी ऊपरी सीमा के। कम्युनिटी इश्यू यथासंभव प्रयास से देखे जाते हैं, किसी उत्तर की गारंटी नहीं। अगर टर्मिनल से आपकी कमाई होती है, तो Enterprise सस्ता और सुरक्षित विकल्प है।
-> **संस्करण तय हैं** (Qt 6.7.2, CMake 3.27.7, MSVC 19.38 / GCC 12.3 / Apple Clang 15.0, Python 3.11.9)। अनुवाद विचलन से बचने के लिए, आधिकारिक अंग्रेज़ी निर्देशों का पालन करें:
->
-> 👉 **[README.md (English) — Build from Source](../../README.md#option-4--build-from-source-manual)**
->
-> CMake प्रीसेट के साथ त्वरित शुरुआत:
-> ```bash
-> ./setup.sh # Linux / macOS — स्वचालित सेटअप
-> setup.bat # Windows (VS 2022 Developer Cmd)
->
-> # या मैन्युअल:
-> cd FinceptTerminal/fincept-qt
-> cmake --preset linux-release && cmake --build --preset linux-release
-> cmake --preset macos-release && cmake --build --preset macos-release
-> cmake --preset win-release && cmake --build --preset win-release
-> ```
+[**Enterprise देखें →**](https://fincept.in/enterprise) · [पूरी तुलना](https://fincept.in/comparison) · [मूल्य](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
-<details>
-<summary>मूल निर्देश (पुराने - संदर्भ के लिए रखे गए)</summary>
+---
+## ओपन सोर्स बनाम Enterprise
-#### आवश्यक शर्तें
+| | ओपन सोर्स | **Enterprise** |
+|---|---|---|
+| **लाइसेंस** | AGPL-3.0 — मज़बूत कॉपीलेफ्ट। वितरित या होस्ट करने पर अपने बदलाव प्रकाशित करने होंगे | प्रोप्राइटरी — कोई कॉपीलेफ्ट दायित्व नहीं |
+| **लागत** | मुफ़्त — डेटा और LLM का बिल आपका | $99 / $199 / $299 प्रति उपयोगकर्ता/माह, सब शामिल |
+| **मॉड्यूल** | कोर टर्मिनल | **6 डेस्क में 41 मॉड्यूल** |
+| **डेटा** | मुफ़्त सार्वजनिक फीड, रेट-सीमित, अपनी कुंजियाँ लाएँ | निजी और प्रोप्राइटरी डेटासेट — लंबा इतिहास, तेज़ रिफ़्रेश |
+| **मूल्य इतिहास** | जितना मुफ़्त टियर दे | 1 वर्ष / 5 वर्ष / असीमित · ईमानदार बैकटेस्ट के लिए **पॉइंट-इन-टाइम** |
+| **AI बजट** | अपनी LLM कुंजी, प्रति टोकन आपका बिल | हर महीने 400 / 2,000 / 5,000 क्रेडिट शामिल |
+| **AI रिसर्च** | बुनियादी मार्केट असिस्टेंट | मल्टी-एजेंट रिसर्च जो **योजना बनाती और काम बाँटती है** · Agent Studio · 53 एजेंट तक · 6 टीम मोड |
+| **निजी डेटारूम** | — | आपकी फाइलिंग और मॉडल, केवल आपके अपने एजेंट पढ़ते हैं — न साझा, न ट्रेनिंग में प्रयुक्त |
+| **ट्रेडिंग** | पेपर ट्रेडिंग + अपनी कुंजियों से ब्रोकर इंटीग्रेशन | **लाइव ब्रोकर रूटिंग + लाइव एल्गो डिप्लॉयमेंट** |
+| **क्वांट** | कम्युनिटी बैकटेस्टिंग | Quant Lab, Alpha Arena, वोलैटिलिटी एनालिटिक्स, पॉइंट-इन-टाइम बैकटेस्ट |
+| **सुरक्षा और अनुपालन** | — | SSO/SAML, ऑडिट लॉग, भूमिका-आधारित एक्सेस, डेटा आइसोलेशन |
+| **सहायता** | GitHub इश्यू, यथासंभव प्रयास, उत्तर की गारंटी नहीं | SLA-समर्थित प्राथमिकता |
+| **दस्तावेज़ीकरण** | यह रिपो | [**700-पृष्ठ का मैनुअल**](https://fincept.in/manual) — 41 गाइड, 472 खंड |
+| **प्लेटफ़ॉर्म** | Windows, macOS, Linux + होस्टेड वेब टर्मिनल | Windows 10/11, macOS 13+ (Apple silicon), Linux |
-| औजार | संस्करण | खिड़कियाँ | लिनक्स | मैक ओएस |
-| ---------------- | ------- | ---------------------------------------------------------------------- | --------------------- | --------------------------------------- |
-| **गिट** | नवीनतम | `winget install Git.Git` | `apt install git` | `brew install git` |
-| **सीएमके** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
-| **सी++ कंपाइलर** | सी++20 | एमएसवीसी 2022 ([विजुअल स्टूडियो](https://visualstudio.microsoft.com/)) | `apt install g++` | एक्सकोड सीएलटी:`xcode-select --install` |
-| **Qt6** | 6.5+ | नीचे देखें | नीचे देखें | नीचे देखें |
-| **अजगर** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+Enterprise के लिए **अलग खाता** चाहिए — मुफ़्त Fincept लॉगिन वहाँ काम नहीं करते, और सब्सक्रिप्शन जुड़ने तक ऐप लॉक रहता है। [Enterprise खाता बनाएँ →](https://fincept.in/enterprise/signup)
-#### Qt6 स्थापित करें
+---
-**खिड़कियाँ:**
+## Enterprise — छह डेस्क, 41 मॉड्यूल
-```powershell
-# Via Qt online installer (recommended — includes windeployqt)
-# Download from https://www.qt.io/download-qt-installer
-# Select: Qt 6.x > MSVC 2022 64-bit
+| डेस्क | क्या करता है |
+|---|---|
+| **Agentic Research** · 6 | एजेंट काम की योजना बनाते हैं, विशेषज्ञों को सौंपते हैं, लाइव डेटा और आपका डेटारूम पढ़ते हैं, और स्रोत-सहित नोट देते हैं |
+| **Quant Lab & Backtesting** · 4 | सिग्नल रिसर्च, पॉइंट-इन-टाइम बैकटेस्ट, वोलैटिलिटी सरफेस |
+| **Deep Fundamental Research** · 8 | इक्विटी विश्लेषण, वैल्यूएशन, डेरिवेटिव, M&A एनालिटिक्स |
+| **Markets & Execution** · 7 | लाइव इक्विटी, क्रिप्टो और प्रेडिक्शन मार्केट, ब्रोकर रूटिंग, एल्गो डिप्लॉयमेंट |
+| **Macro & Global Intelligence** · 7 | सांख्यिकी, सरकारी डेटा, भू-राजनीति, शिपिंग मार्ग |
+| **आपका अपना वर्कस्पेस** · 9 | डैशबोर्ड, स्प्रेडशीट, नोट्स, फाइलें, कोड, रिपोर्ट बिल्डर |
-# Or via winget
-winget install Qt.QtCreator
-```
+[उत्पाद देखें →](https://fincept.in/products)
-**लिनक्स (उबंटू/डेबियन):**
+### मूल्य
-```bash
-sudo apt install -y \
- qt6-base-dev qt6-charts-dev qt6-tools-dev \
- libqt6sql6-sqlite libqt6websockets6-dev \
- libgl1-mesa-dev libglu1-mesa-dev
-```
+| | **Exclusive** | **Exclusive+** ★ सबसे लोकप्रिय | **Exclusive Pro** |
+|---|---|---|---|
+| | **$99**/उपयोगकर्ता/माह | **$199**/उपयोगकर्ता/माह | **$299**/उपयोगकर्ता/माह |
+| AI क्रेडिट / माह | 400 | 2,000 | 5,000 |
+| पोर्टफोलियो · वॉचलिस्ट | 1 · 3 | 10 · 25 | असीमित |
+| मूल्य इतिहास | 1 वर्ष | 5 वर्ष | असीमित |
+| शामिल सीटें | 1 | 1 | 2 |
+| डीप रिसर्च + एजेंट टीम | — | ✓ | ✓ |
+| ब्रोकर खाता लिंकिंग | — | ✓ | ✓ |
+| लाइव ब्रोकर ट्रेडिंग + एल्गो डिप्लॉयमेंट | — | — | ✓ |
-**मैक ओएस:**
+मासिक बिलिंग · कोई वार्षिक बंधन नहीं · कोई न्यूनतम सीट नहीं · **तिमाही पर 15% छूट**। यानी **$1,188–$3,588 प्रति उपयोगकर्ता प्रति वर्ष**, जबकि एक Bloomberg सीट लगभग **$27,000** की है — [पूरी तुलना देखें](https://fincept.in/comparison)।
-```bash
-brew install qt
-```
+**विश्वविद्यालय और शैक्षणिक संस्थान:** एक फ्लैट बंडल — **5 Exclusive Pro सीटें $699/माह में** (सूची मूल्य $1,495)। ईमेल करें: [[email protected]](mailto:[email protected])।
-#### निर्माण
+ये तीन प्लान और शैक्षणिक बंडल ही पूरी मूल्य सूची हैं। कोई कस्टम या मोल-भाव वाली एंटरप्राइज़ कीमत नहीं है, और खरीदने के लिए कोई अलग वाणिज्यिक लाइसेंस भी नहीं है।
-```bash
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal/fincept-qt
+[**Enterprise खाता बनाएँ**](https://fincept.in/enterprise/signup) · [**डेमो बुक करें**](https://calendly.com/nikultilak/fincept-terminal-demo) · [मैनुअल पढ़ें](https://fincept.in/manual)
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+---
-# Windows (from Developer Command Prompt for VS 2022)
-cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/Qt/6.x.x/msvc2022_64"
-cmake --build build --config Release --parallel
-```
+## ओपन-सोर्स संस्करण इंस्टॉल करें
-#### दौड़ना
+**Windows x64**, **Linux x64** (`.run` / `.deb` / `.rpm`) और **macOS (Apple silicon)** के इंस्टॉलर [रिलीज़ पेज](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest) पर उपलब्ध हैं।
-```bash
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal.exe # Windows
-```
+**सोर्स से बिल्ड करें** — Linux/macOS: `git clone … && ./setup.sh`। Windows, मैनुअल बिल्ड, पिन किया गया टूलचेन (**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**) और समस्या-निवारण **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)** में हैं। संस्करण पिन किए गए हैं — नए या पुराने समर्थित नहीं हैं।
-</details>
+> Enterprise बिल्ड चाहिए? उसके अपने साइन किए हुए इंस्टॉलर Windows, macOS और Linux के लिए Enterprise लॉगिन के पीछे हैं — [यहाँ से लें](https://fincept.in/enterprise)।
-* * *
+---
-## जो हमें अलग करता है
+## ओपन बिल्ड में क्या है
-**फिनसेप्ट टर्मिनल**एक खुला स्रोत वित्तीय मंच है जो उन लोगों के लिए बनाया गया है जो पारंपरिक सॉफ्टवेयर तक सीमित होने से इनकार करते हैं। हम प्रतिस्पर्धा करते हैं**विश्लेषणात्मक गहराई**और**डेटा पहुंच**- अंदरूनी जानकारी या विशेष फ़ीड पर नहीं।
+| | |
+|---|---|
+| **मल्टी-एसेट एनालिटिक्स** | DCF, पोर्टफोलियो ऑप्टिमाइज़ेशन, VaR/Sharpe, डेरिवेटिव प्राइसिंग, फिक्स्ड इनकम, ऑल्टरनेटिव्स — एम्बेडेड Python से |
+| **QuantLib सुइट** | 18 क्वांटिटेटिव मॉड्यूल — प्राइसिंग, रिस्क, स्टोकैस्टिक, वोलैटिलिटी, फिक्स्ड इनकम |
+| **AI एजेंट** | ट्रेडर/निवेशक, आर्थिक और भू-राजनीतिक फ्रेमवर्क के 37 एजेंट; अपनी कुंजी लाएँ (OpenAI, Anthropic, Gemini, Groq, DeepSeek, OpenRouter, Ollama) |
+| **100+ डेटा कनेक्टर** | DBnomics, FRED, IMF, विश्व बैंक, AkShare, Polygon, Kraken, Yahoo Finance, सरकारी API |
+| **ट्रेडिंग** | क्रिप्टो और इक्विटी फीड, पेपर-ट्रेडिंग इंजन, 16 ब्रोकर इंटीग्रेशन |
+| **ऑटोमेशन** | विज़ुअल नोड एडिटर, MCP टूल इंटीग्रेशन, AI Quant Lab (ML, फैक्टर डिस्कवरी, RL) |
+| **वैश्विक इंटेलिजेंस** | समुद्री ट्रैकिंग, भू-राजनीतिक विश्लेषण, संबंध मानचित्रण |
-हालिया बिल्ड भी वैकल्पिक का समर्थन करते हैं**एडानोस मार्केट सेंटीमेंट**में कनेक्टिविटी**डेटा स्रोत → वैकल्पिक डेटा**. कॉन्फ़िगर होने पर, इक्विटी रिसर्च रेडिट, एक्स, फाइनेंस न्यूज़ और पॉलीमार्केट में क्रॉस-सोर्स रिटेल सेंटीमेंट स्नैपशॉट पेश कर सकता है। सक्रिय एडानोस कनेक्शन के बिना, सुविधा निष्क्रिय रहती है और बाकी ऐप बिल्कुल पहले की तरह ही व्यवहार करता है।
+नेटिव C++20 · Qt6 · एम्बेडेड Python 3.11 · एकल बाइनरी · न Node.js, न ब्राउज़र रनटाइम।
-- **मूल प्रदर्शन**- Qt6 के साथ C++20, कोई इलेक्ट्रॉन/वेब ओवरहेड नहीं
-- **एकल बाइनरी**- कोई Node.js नहीं, कोई ब्राउज़र रनटाइम नहीं, कोई जावास्क्रिप्ट बंडलर नहीं
-- **सीएफए स्तर का विश्लेषण**- पायथन मॉड्यूल के माध्यम से संपूर्ण पाठ्यक्रम कवरेज
-- **100+ डेटा कनेक्टर**- याहू फाइनेंस से लेकर सरकारी डेटाबेस तक
-- **मुफ़्त और खुला स्रोत**(एजीपीएल-3.0) वाणिज्यिक लाइसेंस के साथ उपलब्ध है
+---
-* * *
+## यह रिपॉज़िटरी कैसे मेंटेन होती है
-## रोडमैप
+यह रिपॉज़िटरी **सार्वजनिक रहेगी और हटाई नहीं जाएगी**। जो पहले रिलीज़ हो चुका है, वह रिलीज़ ही रहेगा।
-| समय | मील का पत्थर |
-| -------------- | -------------------------------------------------------------- |
-| **Q1 2026** | वास्तविक समय स्ट्रीमिंग, उन्नत बैकटेस्टिंग, ब्रोकर एकीकरण |
-| **उल्टी 2026** | विकल्प रणनीति बिल्डर, मल्टी-पोर्टफोलियो प्रबंधन, 50+ एआई एजेंट |
-| **केजेड 2026** | प्रोग्रामेटिक एपीआई, एमएल प्रशिक्षण यूआई, संस्थागत विशेषताएं |
-| **भविष्य** | मोबाइल साथी, क्लाउड सिंक, सामुदायिक बाज़ार |
+अब निरंतर विकास के बजाय **महीने में एक रिलीज़** आती है, क्योंकि टीम का रोज़मर्रा का काम Enterprise पर है। इश्यू और पुल रिक्वेस्ट अब भी देखे जाते हैं, और फ़िक्स मासिक चक्र में आते हैं। सुरक्षा रिपोर्ट: [[email protected]](mailto:[email protected])।
-* * *
+---
## योगदान
-हम वित्तीय विश्लेषण का भविष्य एक साथ मिलकर बना रहे हैं।
-
-**योगदान देना:**नए डेटा कनेक्टर, एआई एजेंट, एनालिटिक्स मॉड्यूल, सी++ स्क्रीन, दस्तावेज़ीकरण
-
-- [योगदान मार्गदर्शिका](docs/CONTRIBUTING.md)
-- [C++ योगदान मार्गदर्शिका](fincept-qt/CONTRIBUTING.md)
-- [पायथन योगदानकर्ता गाइड](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [रिपोर्ट बग](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [फ़ीचर का अनुरोध करें](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+नए डेटा कनेक्टर, AI एजेंट, एनालिटिक्स मॉड्यूल, C++ स्क्रीन और दस्तावेज़ — सभी का स्वागत है।
-* * *
+[योगदान गाइड](../CONTRIBUTING.md) · [C++ गाइड](../CPP_CONTRIBUTOR_GUIDE.md) · [Python गाइड](../PYTHON_CONTRIBUTOR_GUIDE.md) · [आर्किटेक्चर](../ARCHITECTURE.md) · [बग रिपोर्ट करें](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [फीचर सुझाएँ](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-## विश्वविद्यालयों और शिक्षकों के लिए
+---
-**अपनी कक्षा में पेशेवर स्तर का वित्तीय विश्लेषण लाएँ।**
+## Fincept से और भी
-- **$799/माह**20 खातों के लिए
-- फिनसेप्ट डेटा और एपीआई तक पूर्ण पहुंच
-- वित्त, अर्थशास्त्र और डेटा विज्ञान पाठ्यक्रमों के लिए बिल्कुल सही
-- सीएफए पाठ्यक्रम विश्लेषण अंतर्निहित
+- **[Fincept Data API](https://docs.fincept.in)** — 500+ REST एंडपॉइंट, 4,23,000+ इंस्ट्रूमेंट, 2,000+ स्रोत। किसी भी खाते के साथ मुफ़्त टियर।
+- **[Quantcept](https://quantcept.io)** — ओपन-सोर्स, AI-संचालित कमांड-लाइन फाइनेंस टर्मिनल (Apache-2.0)।
-**इच्छुक?**ईमेल**[[email protected]](mailto:[email protected])**आपके संस्थान के नाम के साथ.
-
-[विश्वविद्यालय लाइसेंसिंग विवरण](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-* * *
+---
## लाइसेंस
-**दोहरा लाइसेंस: एजीपीएल-3.0 (ओपन सोर्स) + वाणिज्यिक**
-
-### खुला स्रोत (एजीपीएल-3.0)
-
-- व्यक्तिगत, शैक्षिक और गैर-व्यावसायिक उपयोग के लिए निःशुल्क
-- नेटवर्क सेवा के रूप में वितरित या उपयोग किए जाने पर साझाकरण संशोधन की आवश्यकता होती है
-- पूर्ण स्रोत कोड पारदर्शिता
+**AGPL-3.0-or-later** — पूरा पाठ [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE) में।
-### वाणिज्यिक लाइसेंस
+निजी उपयोग, सीखने और शैक्षणिक शोध के लिए मुफ़्त। AGPL-3.0 **मज़बूत कॉपीलेफ्ट है, परमिसिव नहीं**: संशोधित बिल्ड वितरित करने पर, या उसे ऐसी सेवा के रूप में चलाने पर जिस तक दूसरे पहुँचते हों, आपको अपने बदलाव उसी लाइसेंस के तहत प्रकाशित करने होंगे। ज़्यादातर कानूनी टीमों के लिए बहस यहीं खत्म हो जाती है — इसीलिए कंपनियाँ **[Enterprise](https://fincept.in/enterprise)** लेती हैं, जो प्रोप्राइटरी है और जिसमें कोई कॉपीलेफ्ट दायित्व नहीं है। निजी, बिना वितरण वाले उपयोग पर कोई दायित्व नहीं है।
-- व्यावसायिक उपयोग के लिए या व्यावसायिक रूप से फिनसेप्ट डेटा/एपीआई तक पहुंचने के लिए आवश्यक है
-- संपर्क करना:**[[email protected]](mailto:[email protected])**
-- विवरण:[वाणिज्यिक लाइसेंस गाइड](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+Fincept इस रिपॉज़िटरी के लिए **अब अलग वाणिज्यिक या शैक्षणिक लाइसेंस नहीं बेचता**। वाणिज्यिक, संस्थागत और विश्वविद्यालयीय ज़रूरतें ऊपर दिए गए प्रकाशित मूल्यों पर **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** से पूरी होती हैं।
-### ट्रेडमार्क
+**ट्रेडमार्क।** "Fincept", "Fincept Terminal" और Fincept लोगो, Fincept Corporation के ट्रेडमार्क हैं। किसी भी फोर्क, व्युत्पन्न, रीब्रांडेड या वाणिज्यिक उत्पाद में इनके उपयोग हेतु पूर्व लिखित अनुमति आवश्यक है।
-"फिनसेप्ट टर्मिनल" और "फिनसेप्ट" फिनसेप्ट कॉर्पोरेशन के ट्रेडमार्क हैं।
+प्रश्न: [[email protected]](mailto:[email protected]) · [शर्तें](https://fincept.in/terms) · [गोपनीयता](https://fincept.in/privacy)
-© 2025-2026 फिनसेप्ट कॉर्पोरेशन। सर्वाधिकार सुरक्षित।
+© 2025–2026 Fincept Corporation. सर्वाधिकार सुरक्षित।
-* * *
+---
<div align="center">
-### **आपकी सोच ही एकमात्र सीमा है. डेटा नहीं है.**
-
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
+### **आपकी सोच ही एकमात्र सीमा है। डेटा नहीं।**
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+⭐ **स्टार करें** · 🔄 **साझा करें** · 🤝 **योगदान दें**
-⭐**तारा**· 🔄**शेयर करना**· 🤝**योगदान देना**
+<sub>मूल अंग्रेज़ी संस्करण: <a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.ja.md b/docs/translations/README.ja.md
index ea7d00efe..e73227477 100644
--- a/docs/translations/README.ja.md
+++ b/docs/translations/README.ja.md
@@ -1,267 +1,192 @@
-# フィンセプトターミナル
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+### **限界はあなたの思考だけ。データではない。**
-### **あなたの思考だけが限界です。データはそうではありません。**
+機関投資家水準の金融分析、AI による自動化、無制限のデータ接続を備えた最先端の金融インテリジェンス・プラットフォーム。
-機関投資家グレードの財務分析、AI 自動化、無制限のデータ接続を備えた最先端の金融インテリジェンス プラットフォーム。
+[📥 ダウンロード](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 料金](https://fincept.in/pricing) · [📖 マニュアル](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-[📥 ダウンロード](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 ドキュメント](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 ディスカッション](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬不協和音](https://discord.gg/ae87a8ygbN)·[🤝パートナー](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
-
-## について
-
-**Fincept ターミナル vch**は純粋なネイティブ C++20 デスクトップ アプリケーションです。使用します**Qt6**UI とレンダリング用、埋め込み**パイソン**分析用に提供され、単一のネイティブ バイナリでブルームバーグ ターミナル クラスのパフォーマンスを実現します。
-
-* * *
-
-## 特徴
-
-| **特徴** | **説明** |
-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
-| 📊**マルチアセット分析** | DCF モデル、ポートフォリオの最適化、リスク指標 (VaR、Sharpe)、株式・債券・デリバティブ・ポートフォリオ・オルタナティブ全般のデリバティブ価格設定を組み込み Python により提供 |
-| 🤖**AIエージェント** | 20 人以上の投資家ペルソナ (バフェット、ダリオ、グラハム)、ヘッジファンド戦略、ローカル LLM サポート、マルチプロバイダー (OpenAI、Anthropic、Gemini、Groq、DeepSeek、MiniMax、OpenRouter、Ollama) |
-| 🌐**100以上のデータコネクタ** | DBnomics、Polygon、Kraken、Yahoo Finance、FRED、IMF、世界銀行、AkShare、政府 API、さらに株式調査のための Adanos 市場センチメントなどのオプションの代替データ オーバーレイ |
-| 📈**リアルタイム取引** | 暗号 (Kraken/HyperLiquid WebSocket)、株式、アルゴ取引、ペーパー取引エンジン |
-| 🔬**クアントリブ スイート** | 18 個の定量分析モジュール — 価格設定、リスク、確率論、ボラティリティ、債券 |
-| 🚢**グローバルインテリジェンス** | 海洋追跡、地政学的分析、関係マッピング、衛星データ |
-| 🎨**ビジュアルワークフロー** | 自動化パイプライン用のノードエディター、MCPツール統合 |
-| 🧠**AI Quant Lab** | ML モデル、因子発見、HFT、強化学習取引 |
-
-* * *
-
-## インストール
-
-### オプション 1 — ビルド済みバイナリをダウンロードする (推奨)
-
-事前に構築されたバイナリは、[リリースページ](https://github.com/Fincept-Corporation/FinceptTerminal/releases)。ビルド ツールは必要ありません。抽出して実行するだけです。
-
-| プラットフォーム | ダウンロード | 走る |
-| ------------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **Windows x64** | `FinceptTerminal-Windows-x64.zip` | 抽出→`FinceptTerminal.exe` |
-| **Windows ARM64** | `FinceptTerminal-Windows-arm64.zip` | 抽出→`FinceptTerminal.exe` |
-| **Linux x64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x`→`./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS(アップルシリコン)** | `FinceptTerminal-macOS-arm64.tar.gz` | 抽出→`./FinceptTerminal` |
-| **macOS (インテル)** | `FinceptTerminal-macOS-x64.tar.gz` | 抽出→`./FinceptTerminal` |
-| **macOS (ユニバーサル)** | `FinceptTerminal-macOS-universal.tar.gz` | 抽出→`./FinceptTerminal` |
-
-* * *
+> [!IMPORTANT]
+> **Fincept Terminal には 2 つのエディションがあります。**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — ファンド、ファミリーオフィス、リサーチデスク向けのプライベート(クローズドソース)ビルド。41 モジュール、独自データセット、マルチエージェント・リサーチ、ライブ・ブローカールーティング、プライベート・データルーム、SSO、SLA を備え、**1 ユーザー月額 99 ドル**から。チームが日々開発しているのはこちらであり、ターミナルで収益を上げるならこのエディションです。
+>
+> 📖 **このリポジトリ** — AGPL-3.0 の無償オープンソース版。学習、個人利用、学術研究向けです。公開のまま維持され、削除されることはなく、**月 1 回のリリース**を行います。
+>
+> [**どちらを選ぶべきか →**](#どちらのエディションを選ぶべきか) · [比較](https://fincept.in/comparison) · [料金](https://fincept.in/pricing)
-### オプション 2 — クイック スタート (ワンクリック ビルド)
+---
-セットアップ スクリプトをクローンして実行します。これにより、すべての依存関係がインストールされ、アプリが自動的に構築されます。
+## 概要
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
+**Fincept Terminal** は金融リサーチのためのネイティブ C++20 デスクトップ・ターミナルです。UI は Qt6、分析は組み込み Python 3.11、単一バイナリで動作し、Electron は使用しません。
-```bat
-# Windows — run from Developer Command Prompt for VS 2022
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-setup.bat
-```
+**共通のデータコア上に 2 つのエディション**があります。
-このスクリプトは、コンパイラ チェック、CMake、Qt6、Python、ビルド、起動を処理します。
+| | **オープンソース** — 本リポジトリ | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **対象** | 学習、個人利用、学術研究 | ファンド、ファミリーオフィス、リサーチデスク |
+| **価格** | 無償 · AGPL-3.0 | **月額 99 ドル**/ユーザー〜 |
+| **リリース頻度** | 月 1 回の更新 | 継続的 |
-* * *
+---
-### オプション 3 — ドッカー
+## どちらのエディションを選ぶべきか
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+| あなたが… | 選ぶべきは | 理由 |
+|---|---|---|
+| 学生・趣味・独学の方 | **オープンソース** | 本当に無償で、今後もそのままです |
+| 学術研究者 | **オープンソース** | 学術利用は無償。管理されたシートが必要な大学は下記の学術バンドルをご覧ください |
+| ファンド、ファミリーオフィス、自己勘定デスク、銀行、フィンテック | **Enterprise** | AGPL のコピーレフトが適用されず、独自データ、ライブルーティング、SSO、SLA が得られます |
+| これを職業として、収益のために行っている方 | **Enterprise** | 実質的に安く、日々開発が進む唯一のエディションです |
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+> **率直に言えば。** オープン版は手を抜いたデモではなく、実用に足る製品です。ただし無償の公開フィード、**あなたの** API キー、**あなたの** LLM キーで動作し、AI の呼び出しはすべてトークン単位で上限なくあなたに課金されます。コミュニティの Issue はベストエフォートで、応答の保証はありません。ターミナルが収益の手段であるなら、Enterprise のほうが安全で結果的に安く済みます。
-> **注記:**Docker は主に Linux を対象としています。 macOS および Windows では、追加の XServer 構成が必要です。
+[**Enterprise を見る →**](https://fincept.in/enterprise) · [詳細比較](https://fincept.in/comparison) · [料金](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
-* * *
+---
-### オプション 4 — ソースからビルドする (手動)
+## オープンソース版と Enterprise の比較
-> **⚠️ 重要:**ソースからビルドするには、固定されたツールチェーン (MSVC 19.38 / GCC 12.3 / Apple Clang 15、CMake 3.27.7、Qt 6.7.2、Python 3.11.9) が必要です。常に最新のステップについては、英語の README を参照してください:[ソースからビルド (手動)](https://github.com/Fincept-Corporation/FinceptTerminal#option-4--build-from-source-manual)。以下の翻訳は古くなっており、参考用にのみ保存されています。
+| | オープンソース | **Enterprise** |
+|---|---|---|
+| **ライセンス** | AGPL-3.0 — 強いコピーレフト。配布・ホスティングすれば改変内容の公開義務が生じます | プロプライエタリ — 管理すべきコピーレフト義務なし |
+| **費用** | 無償 — データ費と LLM 費は自己負担 | 1 ユーザー月額 99/199/299 ドル、すべて込み |
+| **モジュール** | コア・ターミナル | **6 デスク・41 モジュール** |
+| **データ** | 無償の公開フィード、レート制限あり、キーは自前 | 独自・専有データセット — 長い履歴、速い更新 |
+| **価格履歴** | 無償枠で許される範囲 | 1 年/5 年/無制限 · 正確なバックテストのための**ポイント・イン・タイム** |
+| **AI 予算** | 自前の LLM キー、トークン単位で自己負担 | 月あたり 400/2,000/5,000 クレジット込み |
+| **AI リサーチ** | 基本的なマーケット・アシスタント | **計画し委任する**マルチエージェント・リサーチ · Agent Studio · 最大 53 エージェント · 6 チームモード |
+| **プライベート・データルーム** | — | 自社の開示資料やモデルを、自分のエージェントのみが参照。他社と共有されず、学習にも使われません |
+| **取引** | ペーパートレード+自前キーによるブローカー連携 | **ライブ・ブローカールーティング+ライブ・アルゴ配備** |
+| **クオンツ** | コミュニティ版バックテスト | Quant Lab、Alpha Arena、ボラティリティ分析、ポイント・イン・タイム・バックテスト |
+| **セキュリティ/コンプライアンス** | — | SSO/SAML、監査ログ、ロールベース・アクセス、データ分離 |
+| **サポート** | GitHub Issue、ベストエフォート、応答保証なし | SLA に基づく優先対応 |
+| **ドキュメント** | 本リポジトリ | [**700 ページのマニュアル**](https://fincept.in/manual) — 41 ガイド、472 セクション |
+| **対応 OS** | Windows、macOS、Linux + ホスト型 Web ターミナル | Windows 10/11、macOS 13+(Apple シリコン)、Linux |
-<details>
-<summary>元の手順 (古い — 参考用に保存)</summary>
+Enterprise には**別アカウント**が必要です。無償の Fincept アカウントではログインできず、サブスクリプションが紐づくまでアプリはロックされたままです。[Enterprise アカウントを作成 →](https://fincept.in/enterprise/signup)
-#### 前提条件
+---
-| 道具 | バージョン | 窓 | Linux | macOS |
-| ------------ | ----- | ------------------------------------------------------------ | --------------------- | ---------------------------------- |
-| **Git** | 最新 | `winget install Git.Git` | `apt install git` | `brew install git` |
-| **CMake** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
-| **C++コンパイラ** | C++20 | MSVC 2022 ([ビジュアルスタジオ](https://visualstudio.microsoft.com/)) | `apt install g++` | Xcode CLT:`xcode-select --install` |
-| **Qt6** | 6.5+ | 以下を参照してください | 以下を参照してください | 以下を参照してください |
-| **パイソン** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+## Enterprise — 6 デスク、41 モジュール
-#### Qt6をインストールする
+| デスク | 内容 |
+|---|---|
+| **Agentic Research** · 6 | エージェントが作業を計画し、専門エージェントに委任し、ライブデータと自社データルームを読み、出典付きのノートを返します |
+| **Quant Lab & Backtesting** · 4 | シグナル研究、ポイント・イン・タイム・バックテスト、ボラティリティ・サーフェス |
+| **Deep Fundamental Research** · 8 | 株式分析、バリュエーション、デリバティブ、M&A 分析 |
+| **Markets & Execution** · 7 | 株式・暗号資産・予測市場のライブ取引、ブローカールーティング、アルゴ配備 |
+| **Macro & Global Intelligence** · 7 | 統計、政府データ、地政学、海上航路 |
+| **自分専用のワークスペース** · 9 | ダッシュボード、表計算、ノート、ファイル、コード、レポートビルダー |
-**Windows:**
+[製品一覧を見る →](https://fincept.in/products)
-```powershell
-# Via Qt online installer (recommended — includes windeployqt)
-# Download from https://www.qt.io/download-qt-installer
-# Select: Qt 6.x > MSVC 2022 64-bit
+### 料金
-# Or via winget
-winget install Qt.QtCreator
-```
+| | **Exclusive** | **Exclusive+** ★ 一番人気 | **Exclusive Pro** |
+|---|---|---|---|
+| | **月額 99 ドル**/ユーザー | **月額 199 ドル**/ユーザー | **月額 299 ドル**/ユーザー |
+| AI クレジット/月 | 400 | 2,000 | 5,000 |
+| ポートフォリオ · ウォッチリスト | 1 · 3 | 10 · 25 | 無制限 |
+| 価格履歴 | 1 年 | 5 年 | 無制限 |
+| 含まれるシート数 | 1 | 1 | 2 |
+| ディープリサーチ+エージェントチーム | — | ✓ | ✓ |
+| ブローカー口座連携 | — | ✓ | ✓ |
+| ライブ取引+アルゴ配備 | — | — | ✓ |
-**Linux (Ubuntu/Debian):**
+月次請求 · 年間契約の縛りなし · 最低シート数なし · **四半期払いで 15% 割引**。年間では **1 ユーザーあたり 1,188〜3,588 ドル**で、Bloomberg の 1 シート約 **27,000 ドル**と比べられます — [詳細な比較を見る](https://fincept.in/comparison)。
-```bash
-sudo apt install -y \
- qt6-base-dev qt6-charts-dev qt6-tools-dev \
- libqt6sql6-sqlite libqt6websockets6-dev \
- libgl1-mesa-dev libglu1-mesa-dev
-```
+**大学・学術機関向け:** 一律のバンドル — **Exclusive Pro 5 シートを月額 699 ドル**(定価 1,495 ドル)。[[email protected]](mailto:[email protected]) までご連絡ください。
-**macOS:**
+この 3 プランと学術バンドルが料金表のすべてです。個別交渉によるエンタープライズ価格はなく、別途購入する商用ライセンスもありません。
-```bash
-brew install qt
-```
+[**Enterprise アカウントを作成**](https://fincept.in/enterprise/signup) · [**デモを予約**](https://calendly.com/nikultilak/fincept-terminal-demo) · [マニュアルを読む](https://fincept.in/manual)
-#### 建てる
+---
-```bash
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal/fincept-qt
+## オープンソース版のインストール
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+**Windows x64**、**Linux x64**(`.run` / `.deb` / `.rpm`)、**macOS(Apple シリコン)**向けのインストーラーは[リリースページ](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest)にあります。
-# Windows (from Developer Command Prompt for VS 2022)
-cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/Qt/6.x.x/msvc2022_64"
-cmake --build build --config Release --parallel
-```
+**ソースからのビルド** — Linux/macOS: `git clone … && ./setup.sh`。Windows、手動ビルド、固定されたツールチェーン(**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**)、トラブルシューティングは **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)** を参照してください。バージョンは固定です。これより新しい/古いものはサポートされません。
-#### 走る
+> Enterprise ビルドをお探しですか。Windows、macOS、Linux 向けに署名済みインストーラーが用意されており、Enterprise ログインの内側にあります — [こちらから入手](https://fincept.in/enterprise)。
-```bash
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal.exe # Windows
-```
+---
-</details>
+## オープン版の内容
-* * *
+| | |
+|---|---|
+| **マルチアセット分析** | DCF、ポートフォリオ最適化、VaR/シャープ、デリバティブ・プライシング、債券、オルタナティブ — 組み込み Python 経由 |
+| **QuantLib スイート** | 18 の定量モジュール — プライシング、リスク、確率過程、ボラティリティ、債券 |
+| **AI エージェント** | トレーダー/投資家、経済、地政学の各フレームワークにわたる 37 エージェント。キーは自前(OpenAI、Anthropic、Gemini、Groq、DeepSeek、OpenRouter、Ollama) |
+| **100 以上のデータコネクタ** | DBnomics、FRED、IMF、世界銀行、AkShare、Polygon、Kraken、Yahoo Finance、政府 API |
+| **取引** | 暗号資産・株式フィード、ペーパートレード・エンジン、16 のブローカー連携 |
+| **自動化** | ビジュアル・ノードエディタ、MCP ツール連携、AI Quant Lab(ML、ファクター探索、強化学習) |
+| **グローバル・インテリジェンス** | 海上輸送トラッキング、地政学分析、関係マッピング |
-## 当社の特徴
+ネイティブ C++20 · Qt6 · 組み込み Python 3.11 · 単一バイナリ · Node.js もブラウザランタイムも不要。
-**フィンセプトターミナル**は、従来のソフトウェアによる制限を拒否する人々のために構築されたオープンソースの金融プラットフォームです。私たちは次の点で競争します**分析の深さ**そして**データへのアクセシビリティ**— インサイダー情報や限定フィードではありません。
+---
-最近のビルドではオプションもサポートされています**アダノス市場センチメント**の接続性**データソース → 代替データ**。 Equity Research を構成すると、Reddit、X、金融ニュース、Polymarket にわたるクロスソースの小売センチメント スナップショットを表示できます。アクティブな Adanos 接続がないと、この機能は休止状態のままになり、アプリの残りの部分は以前とまったく同じように動作します。
+## 本リポジトリの保守方針
-- **ネイティブパフォーマンス**— Qt6 を使用した C++20、Electron/Web オーバーヘッドなし
-- **単一バイナリ**— Node.js、ブラウザ ランタイム、JavaScript バンドラーなし
-- **完全なバイサイド アナリスト ツールキット**— 株式、ポートフォリオ、デリバティブ、債券、コーポレート ファイナンス、オルタナティブ
-- **100以上のデータコネクタ**— Yahoo Financeから政府データベースまで
-- **無料&オープンソース**(AGPL-3.0) 商用ライセンスも利用可能
+本リポジトリは**公開のまま維持され、削除されません**。すでにリリースされたものはリリースされたままです。
-* * *
+継続的な開発ではなく、現在は**月 1 回のリリース**となります。チームの日常的な作業が Enterprise にあるためです。Issue とプルリクエストは引き続きレビューされ、修正は月次サイクルで反映されます。セキュリティ報告は [[email protected]](mailto:[email protected]) へ。
-## ロードマップ
+---
-| タイムライン | マイルストーン |
-| ----------------- | ------------------------------------------ |
-| **2026 年第 1 四半期** | リアルタイムストリーミング、高度なバックテスト、ブローカー統合 |
-| **嘔吐 2026** | オプション戦略ビルダー、マルチポートフォリオ管理、50 人以上の AI エージェント |
-| **KZ2026** | プログラマティック API、ML トレーニング UI、制度的機能 |
-| **未来** | モバイル コンパニオン、クラウド同期、コミュニティ マーケットプレイス |
+## コントリビュート
-* * *
+新しいデータコネクタ、AI エージェント、分析モジュール、C++ 画面、ドキュメント — いずれも歓迎します。
-## 貢献する
+[コントリビュートガイド](../CONTRIBUTING.md) · [C++ ガイド](../CPP_CONTRIBUTOR_GUIDE.md) · [Python ガイド](../PYTHON_CONTRIBUTOR_GUIDE.md) · [アーキテクチャ](../ARCHITECTURE.md) · [バグ報告](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [機能リクエスト](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-私たちは財務分析の未来を一緒に構築しています。
+---
-**貢献する:**新しいデータ コネクタ、AI エージェント、分析モジュール、C++ 画面、ドキュメント
+## Fincept の他のプロダクト
-- [貢献ガイド](docs/CONTRIBUTING.md)
-- [C++ 貢献ガイド](fincept-qt/CONTRIBUTING.md)
-- [Python 貢献者ガイド](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [バグを報告する](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [リクエスト機能](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+- **[Fincept Data API](https://docs.fincept.in)** — 500 以上の REST エンドポイント、423,000 以上の銘柄、2,000 以上のソース。どのアカウントにも無償枠が付属します。
+- **[Quantcept](https://quantcept.io)** — オープンソースの AI 搭載コマンドライン金融ターミナル(Apache-2.0)。
-* * *
-
-## 大学および教育者向け
-
-**プロレベルの財務分析を教室に導入しましょう。**
-
-- **$799/月**20アカウントの場合
-- Fincept データと API へのフルアクセス
-- 金融、経済、データ サイエンスのコースに最適
-- 株式・ポートフォリオ・デリバティブ・債券・経済学の分析を標準搭載
-
-**興味がある?**電子メール**[[email protected]](mailto:[email protected])**あなたの機関名を付けてください。
-
-[大学ライセンスの詳細](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-* * *
+---
## ライセンス
-**デュアルライセンス: AGPL-3.0 (オープンソース) + 商用**
+**AGPL-3.0-or-later** — 全文は [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE) にあります。
-### オープンソース (AGPL-3.0)
+個人利用、学習、学術研究には無償です。AGPL-3.0 は**寛容型ではなく、強いコピーレフト**です。改変したビルドを配布する場合、あるいは他者がアクセスするサービスとして稼働させる場合、改変内容を同じライセンスで公開しなければなりません。多くの法務部門にとって議論はこの一点で決着します。だからこそ企業は、プロプライエタリで管理すべきコピーレフト義務のない **[Enterprise](https://fincept.in/enterprise)** を選びます。配布を伴わない個人利用には義務は生じません。
-- 個人、教育、非営利目的での使用は無料
-- ネットワークサービスとして配布または使用する場合は、共有の変更が必要です
-- ソースコードの完全な透明性
+Fincept は本リポジトリについて、**個別の商用ライセンスや学術ライセンスの販売を終了しました**。商用・機関・大学の用途は、上記の公開価格による **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** が対応します。
-### 商用ライセンス
+**商標。** 「Fincept」「Fincept Terminal」および Fincept ロゴは Fincept Corporation の商標です。フォーク、派生物、リブランド製品、商用製品での使用には事前の書面による許可が必要です。
-- ビジネスで使用する場合、または商業的に Fincept データ/API にアクセスする場合に必要
-- 接触:**[[email protected]](mailto:[email protected])**
-- 詳細:[商用ライセンスガイド](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+お問い合わせ: [[email protected]](mailto:[email protected]) · [利用規約](https://fincept.in/terms) · [プライバシー](https://fincept.in/privacy)
-### 商標
+© 2025–2026 Fincept Corporation. All rights reserved.
-「Fincept Terminal」および「Fincept」はFincept Corporationの商標です。
-
-© 2025-2026 Fincept Corporation.無断転載を禁じます。
-
-* * *
+---
<div align="center">
-### **あなたの思考だけが限界です。データはそうではありません。**
-
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
+### **限界はあなたの思考だけ。データではない。**
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+⭐ **スター** · 🔄 **シェア** · 🤝 **コントリビュート**
-⭐**星**· 🔄**共有**· 🤝**貢献する**
+<sub>英語原文: <a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.ko.md b/docs/translations/README.ko.md
index 7013bb59c..c3fd8408b 100644
--- a/docs/translations/README.ko.md
+++ b/docs/translations/README.ko.md
@@ -1,267 +1,192 @@
-# 핀셉트 터미널
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+### **한계는 당신의 사고뿐입니다. 데이터가 아니라.**
-### **당신의 생각이 유일한 한계입니다. 데이터는 그렇지 않습니다.**
+기관 수준의 금융 분석, AI 자동화, 무제한 데이터 연결을 갖춘 최첨단 금융 인텔리전스 플랫폼.
-기관급 금융 분석, AI 자동화 및 무제한 데이터 연결을 갖춘 최첨단 금융 인텔리전스 플랫폼입니다.
+[📥 다운로드](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 요금제](https://fincept.in/pricing) · [📖 매뉴얼](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-[📥 다운로드](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 문서](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 토론](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 불화](https://discord.gg/ae87a8ygbN)·[🤝 파트너](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
-
-## 에 대한
-
-**Fincept 터미널 vch**순수 네이티브 C++20 데스크톱 애플리케이션입니다. 그것은 사용한다**Qt6**UI 및 렌더링용, 임베디드**파이썬**분석을 위해 단일 네이티브 바이너리로 전문 금융 터미널 수준의 성능을 제공합니다.
-
-* * *
-
-## 특징
-
-| **특징** | **설명** |
-| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
-| 📊**멀티 자산 분석** | DCF 모델, 포트폴리오 최적화, 위험 지표(VaR, Sharpe), 주식·채권·파생상품·포트폴리오·대체투자 전반의 파생 상품 가격을 내장된 Python을 통해 제공 |
-| 🤖**AI 에이전트** | 20명 이상의 투자자 페르소나(Buffett, Dalio, Graham), 헤지 펀드 전략, 현지 LLM 지원, 다중 제공자(OpenAI, Anthropic, Gemini, Groq, DeepSeek, MiniMax, OpenRouter, Ollama) |
-| 🌐**100개 이상의 데이터 커넥터** | DBnomics, Polygon, Kraken, Yahoo Finance, FRED, IMF, World Bank, AkShare, 정부 API 및 주식 조사를 위한 Adanos 시장 심리와 같은 선택적 대체 데이터 오버레이 |
-| 📈**실시간 거래** | 암호화폐(Kraken/HyperLiquid WebSocket), 주식, 알고 트레이딩, 종이 트레이딩 엔진 |
-| 🔬**QuantLib 스위트** | 18개의 정량 분석 ​​모듈 — 가격 책정, 리스크, 확률론적, 변동성, 채권 |
-| 🚢**글로벌 인텔리전스** | 해양 추적, 지정학적 분석, 관계 매핑, 위성 데이터 |
-| 🎨**시각적 워크플로** | 자동화 파이프라인을 위한 노드 편집기, MCP 도구 통합 |
-| 🧠**AI 퀀트 연구실** | ML 모델, 요인 발견, HFT, 강화 학습 거래 |
-
-* * *
-
-## 설치
-
-### 옵션 1 - 사전 구축된 바이너리 다운로드(권장)
-
-사전 구축된 바이너리는 다음에서 사용할 수 있습니다.[릴리스 페이지](https://github.com/Fincept-Corporation/FinceptTerminal/releases). 빌드 도구가 필요하지 않습니다. 추출하고 실행하기만 하면 됩니다.
-
-| 플랫폼 | 다운로드 | 달리다 |
-| ----------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **윈도우 x64** | `FinceptTerminal-Windows-x64.zip` | 추출 →`FinceptTerminal.exe` |
-| **윈도우 ARM64** | `FinceptTerminal-Windows-arm64.zip` | 추출 →`FinceptTerminal.exe` |
-| **리눅스 x64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x`→`./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS(애플 실리콘)** | `FinceptTerminal-macOS-arm64.tar.gz` | 추출 →`./FinceptTerminal` |
-| **맥OS(인텔)** | `FinceptTerminal-macOS-x64.tar.gz` | 추출 →`./FinceptTerminal` |
-| **macOS(유니버설)** | `FinceptTerminal-macOS-universal.tar.gz` | 추출 →`./FinceptTerminal` |
-
-* * *
+> [!IMPORTANT]
+> **Fincept Terminal은 두 가지 에디션으로 제공됩니다.**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — 펀드, 패밀리 오피스, 리서치 데스크를 위한 비공개 클로즈드소스 빌드. 41개 모듈, 독점 데이터셋, 멀티 에이전트 리서치, 실시간 브로커 라우팅, 프라이빗 데이터룸, SSO, SLA를 제공하며 **사용자당 월 99달러**부터. 팀이 매일 개발하는 쪽이 이 에디션이며, 터미널로 수익을 낸다면 이쪽을 쓰셔야 합니다.
+>
+> 📖 **이 저장소** — AGPL-3.0 기반의 무료 오픈소스 에디션. 학습, 개인 사용, 학술 연구용입니다. 계속 공개로 유지되고 삭제되지 않으며, **월 1회 릴리스**됩니다.
+>
+> [**어느 쪽이 필요한가요? →**](#어떤-에디션을-선택해야-할까) · [비교](https://fincept.in/comparison) · [요금제](https://fincept.in/pricing)
-### 옵션 2 - 빠른 시작(원클릭 빌드)
+---
-설정 스크립트를 복제하고 실행하세요. 모든 종속성을 설치하고 앱을 자동으로 빌드합니다.
+## 소개
-```bash
-# Linux / macOS
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
+**Fincept Terminal**은 금융 리서치를 위한 네이티브 C++20 데스크톱 터미널입니다. Qt6 UI, 내장 Python 3.11 분석 엔진, 단일 바이너리로 동작하며 Electron을 쓰지 않습니다.
-```bat
-# Windows — run from Developer Command Prompt for VS 2022
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-setup.bat
-```
+**하나의 데이터 코어 위에 두 가지 에디션**으로 제공됩니다.
-스크립트는 컴파일러 확인, CMake, Qt6, Python, 빌드 및 실행을 처리합니다.
+| | **오픈소스** — 이 저장소 | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **대상** | 학습, 개인 사용, 학술 연구 | 펀드, 패밀리 오피스, 리서치 데스크 |
+| **가격** | 무료 · AGPL-3.0 | **월 99달러**/사용자부터 |
+| **릴리스 주기** | 월 1회 업데이트 | 상시 |
-* * *
+---
-### 옵션 3 - 도커
+## 어떤 에디션을 선택해야 할까
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+| 당신이… | 선택 | 이유 |
+|---|---|---|
+| 학생, 취미 사용자, 독학하는 분 | **오픈소스** | 정말로 무료이며, 앞으로도 그렇습니다 |
+| 학술 연구자 | **오픈소스** | 학술 용도는 무료 — 관리형 좌석이 필요한 대학은 아래 학술 번들 참고 |
+| 펀드, 패밀리 오피스, 자기자본 데스크, 은행, 핀테크 | **Enterprise** | AGPL 카피레프트가 적용되지 않고, 독점 데이터·실시간 라우팅·SSO·SLA를 받습니다 |
+| 이 일을 직업으로, 돈을 벌기 위해 하는 분 | **Enterprise** | 실질적으로 더 저렴하고, 매일 개발되는 유일한 에디션입니다 |
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+> **솔직히 말하면.** 오픈 빌드는 기능을 깎아낸 데모가 아니라 실제로 쓸 만한 제품입니다. 다만 무료 공개 피드와 **당신의** API 키, **당신의** LLM 키로 동작하며, 모든 AI 호출은 상한 없이 토큰 단위로 당신에게 청구됩니다. 커뮤니티 이슈는 최선을 다해 처리되지만 응답을 보장하지 않습니다. 터미널이 밥벌이 수단이라면 Enterprise가 더 싸고 안전한 선택입니다.
-> **메모:**Docker는 주로 Linux용으로 만들어졌습니다. macOS 및 Windows에는 추가 XServer 구성이 필요합니다.
+[**Enterprise 보기 →**](https://fincept.in/enterprise) · [전체 비교](https://fincept.in/comparison) · [요금제](https://fincept.in/pricing) · [FAQ](https://fincept.in/faq)
-* * *
+---
-### 옵션 4 - 소스에서 빌드(수동)
+## 오픈소스 vs Enterprise
-> **⚠️ 중요:**소스에서 빌드하려면 고정된 도구 체인(MSVC 19.38 / GCC 12.3 / Apple Clang 15, CMake 3.27.7, Qt 6.7.2, Python 3.11.9)이 필요합니다. 항상 최신 단계는 영어 README를 참조하세요:[소스에서 빌드(수동)](https://github.com/Fincept-Corporation/FinceptTerminal#option-4--build-from-source-manual). 아래 번역은 오래되었으며 참고용으로만 보존됩니다.
+| | 오픈소스 | **Enterprise** |
+|---|---|---|
+| **라이선스** | AGPL-3.0 — 강한 카피레프트. 배포하거나 호스팅하면 변경 사항을 공개해야 합니다 | 독점 — 관리할 카피레프트 의무 없음 |
+| **비용** | 무료 — 데이터와 LLM 비용은 본인 부담 | 사용자당 월 99 / 199 / 299달러, 전부 포함 |
+| **모듈** | 코어 터미널 | **6개 데스크, 41개 모듈** |
+| **데이터** | 무료 공개 피드, 요청 제한 있음, 키는 직접 준비 | 독점 데이터셋 — 더 긴 이력, 더 빠른 갱신 |
+| **가격 이력** | 무료 등급이 허용하는 범위 | 1년 / 5년 / 무제한 · 정직한 백테스트를 위한 **포인트 인 타임** |
+| **AI 예산** | 본인 LLM 키, 토큰 단위로 본인 청구 | 매월 400 / 2,000 / 5,000 크레딧 포함 |
+| **AI 리서치** | 기본 마켓 어시스턴트 | **계획하고 위임하는** 멀티 에이전트 리서치 · Agent Studio · 최대 53개 에이전트 · 6가지 팀 모드 |
+| **프라이빗 데이터룸** | — | 공시 자료와 모델을 본인 에이전트만 읽습니다. 타사와 섞이지 않고 학습에도 쓰이지 않습니다 |
+| **트레이딩** | 모의 매매 + 본인 키로 브로커 연동 | **실시간 브로커 라우팅 + 실시간 알고 배포** |
+| **퀀트** | 커뮤니티 백테스팅 | Quant Lab, Alpha Arena, 변동성 분석, 포인트 인 타임 백테스트 |
+| **보안·컴플라이언스** | — | SSO/SAML, 감사 로그, 역할 기반 접근 제어, 데이터 격리 |
+| **지원** | GitHub 이슈, 최선 노력, 응답 보장 없음 | SLA 기반 우선 대응 |
+| **문서** | 이 저장소 | [**700쪽 매뉴얼**](https://fincept.in/manual) — 41개 가이드, 472개 섹션 |
+| **플랫폼** | Windows, macOS, Linux + 호스팅 웹 터미널 | Windows 10/11, macOS 13+ (애플 실리콘), Linux |
-<details>
-<summary>원본 지침 (오래됨 — 참고용으로 보존)</summary>
+Enterprise는 **별도 계정**으로 동작합니다. 무료 Fincept 계정으로는 로그인되지 않으며, 구독이 연결될 때까지 앱은 잠긴 상태로 유지됩니다. [Enterprise 계정 만들기 →](https://fincept.in/enterprise/signup)
-#### 전제조건
+---
-| 도구 | 버전 | 윈도우 | 리눅스 | macOS |
-| ------------ | ----- | ----------------------------------------------------------- | --------------------- | ---------------------------------- |
-| **힘내** | 최신 | `winget install Git.Git` | `apt install git` | `brew install git` |
-| **CMake** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
-| **C++ 컴파일러** | C++20 | MSVC 2022 ([비주얼 스튜디오](https://visualstudio.microsoft.com/)) | `apt install g++` | Xcode CLT:`xcode-select --install` |
-| **Qt6** | 6.5+ | 아래를 참조하세요 | 아래를 참조하세요 | 아래를 참조하세요 |
-| **파이썬** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+## Enterprise — 6개 데스크, 41개 모듈
-#### Qt6 설치
+| 데스크 | 하는 일 |
+|---|---|
+| **Agentic Research** · 6 | 에이전트가 작업을 계획하고 전문 에이전트에 위임하며, 실시간 데이터와 데이터룸을 읽어 출처가 달린 노트를 작성합니다 |
+| **Quant Lab & Backtesting** · 4 | 시그널 리서치, 포인트 인 타임 백테스트, 변동성 곡면 |
+| **Deep Fundamental Research** · 8 | 주식 분석, 밸류에이션, 파생상품, M&A 분석 |
+| **Markets & Execution** · 7 | 주식·암호화폐·예측시장 실시간 거래, 브로커 라우팅, 알고 배포 |
+| **Macro & Global Intelligence** · 7 | 통계, 정부 데이터, 지정학, 해상 항로 |
+| **나만의 워크스페이스** · 9 | 대시보드, 스프레드시트, 노트, 파일, 코드, 리포트 빌더 |
-**윈도우:**
+[제품 살펴보기 →](https://fincept.in/products)
-```powershell
-# Via Qt online installer (recommended — includes windeployqt)
-# Download from https://www.qt.io/download-qt-installer
-# Select: Qt 6.x > MSVC 2022 64-bit
+### 요금제
-# Or via winget
-winget install Qt.QtCreator
-```
+| | **Exclusive** | **Exclusive+** ★ 가장 인기 | **Exclusive Pro** |
+|---|---|---|---|
+| | **월 99달러**/사용자 | **월 199달러**/사용자 | **월 299달러**/사용자 |
+| AI 크레딧 / 월 | 400 | 2,000 | 5,000 |
+| 포트폴리오 · 관심목록 | 1 · 3 | 10 · 25 | 무제한 |
+| 가격 이력 | 1년 | 5년 | 무제한 |
+| 포함 좌석 | 1 | 1 | 2 |
+| 딥 리서치 + 에이전트 팀 | — | ✓ | ✓ |
+| 브로커 계좌 연동 | — | ✓ | ✓ |
+| 실시간 브로커 거래 + 알고 배포 | — | — | ✓ |
-**리눅스(우분투/데비안):**
+월 단위 결제 · 연간 약정 없음 · 최소 좌석 수 없음 · **분기 결제 시 15% 할인**. 연간 **사용자당 1,188~3,588달러**로, 블룸버그 단말 한 좌석의 약 **27,000달러**와 비교됩니다 — [전체 비교 보기](https://fincept.in/comparison).
-```bash
-sudo apt install -y \
- qt6-base-dev qt6-charts-dev qt6-tools-dev \
- libqt6sql6-sqlite libqt6websockets6-dev \
- libgl1-mesa-dev libglu1-mesa-dev
-```
+**대학 및 학술 기관:** 단일 번들 — **Exclusive Pro 5좌석을 월 699달러**(정가 1,495달러). [[email protected]](mailto:[email protected])으로 문의하세요.
-**맥OS:**
+이 세 가지 요금제와 학술 번들이 전체 가격표입니다. 개별 협상형 엔터프라이즈 가격은 없으며, 따로 구매하는 상용 라이선스도 없습니다.
-```bash
-brew install qt
-```
+[**Enterprise 계정 만들기**](https://fincept.in/enterprise/signup) · [**데모 예약**](https://calendly.com/nikultilak/fincept-terminal-demo) · [매뉴얼 읽기](https://fincept.in/manual)
-#### 짓다
+---
-```bash
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal/fincept-qt
+## 오픈소스 에디션 설치
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+**Windows x64**, **Linux x64**(`.run` / `.deb` / `.rpm`), **macOS(애플 실리콘)** 설치 파일은 [릴리스 페이지](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest)에 있습니다.
-# Windows (from Developer Command Prompt for VS 2022)
-cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/Qt/6.x.x/msvc2022_64"
-cmake --build build --config Release --parallel
-```
+**소스에서 빌드** — Linux/macOS: `git clone … && ./setup.sh`. Windows, 수동 빌드, 고정된 툴체인(**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**), 문제 해결은 **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)** 를 참고하세요. 버전은 고정되어 있으며 그보다 높거나 낮은 버전은 지원되지 않습니다.
-#### 달리다
+> Enterprise 빌드를 찾으시나요? Windows, macOS, Linux용 서명된 설치 파일이 Enterprise 로그인 뒤에 준비되어 있습니다 — [여기서 받으세요](https://fincept.in/enterprise).
-```bash
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal.exe # Windows
-```
+---
-</details>
+## 오픈 빌드에 포함된 것
-* * *
+| | |
+|---|---|
+| **멀티에셋 분석** | DCF, 포트폴리오 최적화, VaR/샤프, 파생상품 가격 산정, 채권, 대체투자 — 내장 Python 기반 |
+| **QuantLib 스위트** | 18개 퀀트 모듈 — 가격 산정, 리스크, 확률과정, 변동성, 채권 |
+| **AI 에이전트** | 트레이더/투자자, 경제, 지정학 프레임워크에 걸친 37개 에이전트. 키는 직접 준비(OpenAI, Anthropic, Gemini, Groq, DeepSeek, OpenRouter, Ollama) |
+| **100개 이상 데이터 커넥터** | DBnomics, FRED, IMF, 세계은행, AkShare, Polygon, Kraken, Yahoo Finance, 정부 API |
+| **트레이딩** | 암호화폐·주식 피드, 모의 매매 엔진, 16개 브로커 연동 |
+| **자동화** | 비주얼 노드 에디터, MCP 도구 연동, AI Quant Lab(ML, 팩터 발굴, 강화학습) |
+| **글로벌 인텔리전스** | 해상 물류 추적, 지정학 분석, 관계 매핑 |
-## 우리를 차별화하는 요소
+네이티브 C++20 · Qt6 · 내장 Python 3.11 · 단일 바이너리 · Node.js도 브라우저 런타임도 없음.
-**핀셉트 터미널**전통적인 소프트웨어의 제한을 거부하는 사람들을 위해 구축된 오픈 소스 금융 플랫폼입니다. 우리는 경쟁합니다**분석 깊이**그리고**데이터 접근성**— 내부자 정보나 독점 피드가 아닙니다.
+---
-최근 빌드에서는 선택 사항도 지원합니다.**아다노스 시장 심리**연결성**데이터 소스 → 대체 데이터**. 구성된 경우 Equity Research는 Reddit, X, 금융 뉴스 및 Polymarket 전반에 걸쳐 소스 간 소매 정서 스냅샷을 표면화할 수 있습니다. 활성 Adanos 연결이 없으면 기능은 휴면 상태로 유지되며 앱의 나머지 부분은 이전과 동일하게 작동합니다.
+## 이 저장소의 유지보수 방식
-- **기본 성능**— Qt6이 포함된 C++20, 전자/웹 오버헤드 없음
-- **단일 바이너리**— Node.js 없음, 브라우저 런타임 없음, JavaScript 번들러 없음
-- **완전한 바이사이드 애널리스트 툴킷**— 주식, 포트폴리오, 파생상품, 채권, 기업금융, 대체투자
-- **100개 이상의 데이터 커넥터**— Yahoo Finance에서 정부 데이터베이스까지
-- **무료 및 오픈 소스**(AGPL-3.0) 상용 라이센스 사용 가능
+이 저장소는 **계속 공개되며 삭제되지 않습니다**. 이미 릴리스된 것은 그대로 남습니다.
-* * *
+이제 상시 개발이 아니라 **월 1회 릴리스**로 운영됩니다. 팀의 일상 작업이 Enterprise에 있기 때문입니다. 이슈와 풀 리퀘스트는 계속 검토되며, 수정 사항은 월간 주기로 반영됩니다. 보안 제보는 [[email protected]](mailto:[email protected])으로 보내주세요.
-## 로드맵
+---
-| 타임라인 | 중요한 단계 |
-| ------------- | -------------------------------------- |
-| **2026년 1분기** | 실시간 스트리밍, 고급 백테스팅, 브로커 통합 |
-| **구토 2026** | 옵션 전략 빌더, 다중 포트폴리오 관리, 50개 이상의 AI 에이전트 |
-| **KZ 2026** | 프로그래밍 방식 API, ML 학습 UI, 기관 기능 |
-| **미래** | 모바일 컴패니언, 클라우드 동기화, 커뮤니티 마켓플레이스 |
+## 기여하기
-* * *
+새로운 데이터 커넥터, AI 에이전트, 분석 모듈, C++ 화면, 문서 모두 환영합니다.
-## 기여
+[기여 가이드](../CONTRIBUTING.md) · [C++ 가이드](../CPP_CONTRIBUTOR_GUIDE.md) · [Python 가이드](../PYTHON_CONTRIBUTOR_GUIDE.md) · [아키텍처](../ARCHITECTURE.md) · [버그 신고](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [기능 제안](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-우리는 재무 분석의 미래를 함께 만들어가고 있습니다.
+---
-**기여하다:**새로운 데이터 커넥터, AI 에이전트, 분석 모듈, C++ 화면, 문서
+## Fincept의 다른 제품
-- [기여 가이드](docs/CONTRIBUTING.md)
-- [C++ 기여 가이드](fincept-qt/CONTRIBUTING.md)
-- [Python 기여자 가이드](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [버그 신고](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [기능 요청](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+- **[Fincept Data API](https://docs.fincept.in)** — 500개 이상 REST 엔드포인트, 423,000개 이상 종목, 2,000개 이상 소스. 모든 계정에 무료 등급 포함.
+- **[Quantcept](https://quantcept.io)** — 오픈소스 AI 기반 커맨드라인 금융 터미널(Apache-2.0).
-* * *
+---
-## 대학 및 교육자용
+## 라이선스
-**전문가 수준의 재무 분석을 교실에 도입하세요.**
+**AGPL-3.0-or-later** — 전문은 [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)에 있습니다.
-- **$799/월**20개 계정용
-- Fincept 데이터 및 API에 대한 전체 액세스
-- 금융, 경제, 데이터 과학 과정에 적합
-- 주식·포트폴리오·파생상품·채권·경제학 분석 내장
+개인 사용, 학습, 학술 연구에는 무료입니다. AGPL-3.0은 **관대한 라이선스가 아니라 강한 카피레프트**입니다. 수정한 빌드를 배포하거나 다른 사람이 접근하는 서비스로 운영하면, 변경 사항을 동일한 라이선스로 공개해야 합니다. 대부분의 법무팀에게는 이 한 줄에서 논의가 끝납니다. 그래서 기업들은 독점 라이선스이며 관리할 카피레프트 의무가 없는 **[Enterprise](https://fincept.in/enterprise)** 를 선택합니다. 배포하지 않는 개인 사용에는 아무 의무도 없습니다.
-**관심 있는?**이메일**[[email protected]](mailto:[email protected])**귀하의 기관 이름으로.
+Fincept는 이 저장소에 대해 **더 이상 별도의 상용 또는 학술 라이선스를 판매하지 않습니다**. 상업적·기관·대학 용도는 위에 공개된 가격의 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** 가 담당합니다.
-[대학 라이센스 세부정보](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+**상표.** "Fincept", "Fincept Terminal" 및 Fincept 로고는 Fincept Corporation의 상표입니다. 포크, 파생물, 리브랜딩 제품, 상용 제품에서 사용하려면 사전 서면 허가가 필요합니다.
-* * *
+문의: [[email protected]](mailto:[email protected]) · [이용약관](https://fincept.in/terms) · [개인정보처리방침](https://fincept.in/privacy)
-## 특허
+© 2025–2026 Fincept Corporation. All rights reserved.
-**이중 라이센스: AGPL-3.0(오픈 소스) + 상업용**
-
-### 오픈 소스(AGPL-3.0)
-
-- 개인적, 교육적, 비상업적 용도로는 무료입니다.
-- 네트워크 서비스로 배포 또는 사용 시 공유 수정 필요
-- 전체 소스 코드 투명성
-
-### 상업용 라이센스
-
-- 업무용으로 사용하거나 Fincept 데이터/API에 상업적으로 액세스하는 데 필요합니다.
-- 연락하다:**[[email protected]](mailto:[email protected])**
-- 세부:[상용 라이센스 가이드](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-### 상표
-
-"Fincept Terminal" 및 "Fincept"는 Fincept Corporation의 상표입니다.
-
-© 2025-2026 핀셉트 코퍼레이션. 모든 권리 보유.
-
-* * *
+---
<div align="center">
-### **당신의 생각이 유일한 한계입니다. 데이터는 그렇지 않습니다.**
-
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
+### **한계는 당신의 사고뿐입니다. 데이터가 아니라.**
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+⭐ **스타** · 🔄 **공유** · 🤝 **기여**
-⭐**별**· 🔄**공유하다**· 🤝**기여하다**
+<sub>영문 원본: <a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.zh-CN.md b/docs/translations/README.zh-CN.md
index b07ae8980..91563400d 100644
--- a/docs/translations/README.zh-CN.md
+++ b/docs/translations/README.zh-CN.md
@@ -1,284 +1,192 @@
-# 金融终端
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+### **唯一的上限是你的思考,而不是数据。**
-### **你的思维是唯一的限制。数据不是。**
+面向机构级金融分析、AI 自动化与无限数据接入的前沿金融智能平台。
-最先进的金融情报平台,具有机构级金融分析、人工智能自动化和无限数据连接。
+[📥 下载](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 价格](https://fincept.in/pricing) · [📖 手册](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-[📥 下载](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 文档](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 讨论](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 Discord](https://discord.gg/ae87a8ygbN)·[🤝 合作伙伴](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
-
-## 关于
-
-**Fincept终端vch**是一个纯原生 C++20 桌面应用程序。它使用**Qt6**用于 UI 和渲染,嵌入式**Python**用于分析,并在单个本机二进制文件中提供彭博终端级的性能。
-
-* * *
-
-## 特征
-
-| **特征** | **描述** |
-| ----------------- | -------------------------------------------------------------------------------------------------------------- |
-| 📊**CFA 级别分析** | DCF 模型、投资组合优化、风险指标(VaR、夏普比率)、通过嵌入式 Python 进行衍生品定价 |
-| 🤖**AI 智能体** | 20 多个投资者角色(巴菲特、达里奥、格雷厄姆)、对冲基金策略、**本地大语言模型 (LLM) 支持**、多供应商(OpenAI、Anthropic、Gemini、Groq、DeepSeek、MiniMax、OpenRouter、Ollama) |
-| 🌐**100 多个数据连接器** | DBnomics、Polygon、Kraken、雅虎财经、FRED、IMF、世界银行、AkShare、政府 API,以及可选的替代数据叠加(例如用于股票研究的 Adanos 市场情绪数据) |
-| 📈**实时交易** | 加密货币(Kraken/HyperLiquid WebSocket)、股票、算法交易、模拟交易引擎 (Paper Trading) |
-| 🔬**量化库套件** | 18 个定量分析模块 —— 定价、风险、随机过程、波动率、固定收益 |
-| 🚢**全球情报** | 海上追踪、地缘政治分析、关系映射、卫星数据 |
-| 🎨**可视化工作流程** | 用于自动化管线、MCP 工具集成的节点编辑器 |
-| 🧠**人工智能量化实验室** | 机器学习模型、因子发现、高频交易、强化学习交易
-
-* * *
-
-## 安装
-
-### 选项 1 — 下载预构建的二进制文件(推荐)
-
-预构建的二进制文件可在[发布页面](https://github.com/Fincept-Corporation/FinceptTerminal/releases)下载。不需要构建工具 —— 只需解压并运行。
-
-| 平台 | 下载文件 | 运行方式 |
-| --------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **Windows x64** | `FinceptTerminal-Windows-x64.zip` | 解压 → 运行 `FinceptTerminal.exe` |
-| **Windows ARM64** | `FinceptTerminal-Windows-arm64.zip` | 解压 → 运行 `FinceptTerminal.exe` |
-| **Linux x64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x` → `./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS (Apple 芯片)** | `FinceptTerminal-macOS-arm64.tar.gz` | 解压 → 运行 `./FinceptTerminal` |
-| **macOS (Intel)** | `FinceptTerminal-macOS-x64.tar.gz` | 解压 → 运行 `./FinceptTerminal` |
-| **macOS (通用)** | `FinceptTerminal-macOS-universal.tar.gz` | 解压 → 运行 `./FinceptTerminal` |
-
-* * *
-
-### 选项 2 — 快速启动(一键构建)
-
-克隆并运行安装脚本 —— 它会安装所有依赖项并自动构建应用程序:
-
-```bash
-# Linux / macOS
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-```
-
-```bat
-# Windows — 请从 Visual Studio 2022 的 Developer Command Prompt 运行
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal
-setup.bat
-```
-
-该脚本将自动处理:编译器检查、CMake、Qt6、Python 环境配置、构建和启动。
-
-* * *
-
-### 选项 3 — Docker
-
-```bash
-# 拉取并运行
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
-
-# 或从源代码构建
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
-
-> **注意: Docker 主要适用于 Linux。macOS 和 Windows 需要额外的 XServer 配置。
-
-* * *
-
-### 选项 4 — 从源代码构建(手动)
-
-> **版本已锁定**(Qt 6.7.2、CMake 3.27.7、MSVC 19.38 / GCC 12.3 / Apple Clang 15.0、Python 3.11.9)。为避免翻译出现偏差,请遵循官方英文说明:
+> [!IMPORTANT]
+> **Fincept Terminal 提供两个版本。**
>
-> 👉 **[README.md (English) — Build from Source](../../README.md#option-4--build-from-source-manual)**
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — 面向基金、家族办公室和研究部门的私有闭源版本。41 个模块、专有数据集、多智能体研究、实时券商路由、私有数据室、SSO 与 SLA,**每用户每月 99 美元**起。团队的日常开发都在这一版本上;如果你靠终端赚钱,就该用它。
>
-> 使用 CMake 预设快速启动:
-> ```bash
-> ./setup.sh # Linux / macOS — 自动化安装
-> setup.bat # Windows(VS 2022 Developer Cmd)
+> 📖 **本仓库** — 基于 AGPL-3.0 的免费开源版本,面向学习、个人使用与学术研究。仓库将持续公开、不会删除,并保持**每月一次发布**。
>
-> # 或采用手动方式:
-> cd FinceptTerminal/fincept-qt
-> cmake --preset linux-release && cmake --build --preset linux-release
-> cmake --preset macos-release && cmake --build --preset macos-release
-> cmake --preset win-release && cmake --build --preset win-release
-> ```
+> [**你需要哪一个? →**](#应该选择哪个版本) · [对比](https://fincept.in/comparison) · [价格](https://fincept.in/pricing)
-<details>
-<summary>原始说明(已过时 — 保留供参考)</summary>
+---
-#### 先决条件
+## 关于
-| 工具 | 版本 | 视窗 | Linux | macOS |
-| ---------- | ----- | -------------------------------------------------------- | --------------------- | ---------------------------------- |
-| **git** | 最新版 | `winget install Git.Git` | `apt install git` | `brew install git` |
-| **CMake** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
-| **C++编译器** | C++20 | MSVC 2022 ([Visual Studio](https://visualstudio.microsoft.com/)) | `apt install g++` | Xcode CLT:`xcode-select --install` |
-| **Qt6** | 6.5+ | 见下文 | 见下文 | 见下文 |
-| **Python** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+**Fincept Terminal** 是一款用于金融研究的原生 C++20 桌面终端 —— Qt6 界面、内嵌 Python 3.11 分析引擎、单一二进制文件,不依赖 Electron。
-#### 安装Qt6
+它在**同一数据内核上提供两个版本**:
-**视窗:**
+| | **开源版** — 本仓库 | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **适用对象** | 学习、个人使用、学术研究 | 基金、家族办公室、研究部门 |
+| **价格** | 免费 · AGPL-3.0 | **每用户每月 99 美元**起 |
+| **发布节奏** | 每月一次更新 | 持续更新 |
-```powershell
-# 通过 Qt 在线安装程序 (推荐 — 包含 windeployqt)
-# 从 [https://www.qt.io/download-qt-installer](https://www.qt.io/download-qt-installer) 下载
-# 选择: Qt 6.x > MSVC 2022 64-bit
+---
-# 或通过 winget 安装
-winget install Qt.QtCreator
-```
+## 应该选择哪个版本
-**Linux(Ubuntu/Debian):**
+| 如果你是…… | 选择 | 原因 |
+|---|---|---|
+| 学生、爱好者或自学者 | **开源版** | 真正免费,并且会一直免费 |
+| 学术研究人员 | **开源版** | 学术用途免费 —— 需要统一管理席位的高校请看下方学术套餐 |
+| 基金、家族办公室、自营交易台、银行或金融科技公司 | **Enterprise** | 不适用 AGPL 传染性条款,并获得专有数据、实时路由、SSO 与 SLA |
+| 以此为职业、靠它赚钱的人 | **Enterprise** | 实际成本更低,而且是唯一在每日开发中的版本 |
-```bash
-sudo apt install -y \
- qt6-base-dev qt6-charts-dev qt6-tools-dev \
- libqt6sql6-sqlite libqt6websockets6-dev \
- libgl1-mesa-dev libglu1-mesa-dev
-```
+> **实话实说。** 开源版是真材实料,不是阉割版演示 —— 但它跑在免费公开数据源上,用的是**你的** API 密钥和**你的** LLM 密钥,每一次 AI 调用都按 token 计入你的账单,没有上限。社区 issue 尽力处理,不承诺响应时间。如果终端是你的谋生工具,Enterprise 才是更便宜也更稳妥的席位。
-**苹果系统:**
+[**了解 Enterprise →**](https://fincept.in/enterprise) · [完整对比](https://fincept.in/comparison) · [价格](https://fincept.in/pricing) · [常见问题](https://fincept.in/faq)
-```bash
-brew install qt
-```
+---
-#### 构建
+## 开源版与 Enterprise 对比
-```bash
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal/fincept-qt
+| | 开源版 | **Enterprise** |
+|---|---|---|
+| **许可证** | AGPL-3.0 —— 强传染性。一旦分发或托管,就必须公开你的修改 | 专有许可 —— 无需处理任何 copyleft 义务 |
+| **成本** | 免费 —— 数据与 LLM 账单自付 | 每用户每月 99 / 199 / 299 美元,全部包含 |
+| **模块** | 核心终端 | **6 个业务台、41 个模块** |
+| **数据** | 免费公开数据源,有速率限制,需自备密钥 | 私有与专有数据集 —— 历史更长、刷新更快 |
+| **价格历史** | 取决于免费额度 | 1 年 / 5 年 / 无限 · 支持**时点数据**,回测更可信 |
+| **AI 预算** | 自备 LLM 密钥,按 token 自付 | 每月含 400 / 2,000 / 5,000 积分 |
+| **AI 研究** | 基础行情助手 | 会**规划并分派任务**的多智能体研究 · Agent Studio · 最多 53 个智能体 · 6 种团队模式 |
+| **私有数据室** | — | 你的文件与模型仅由你自己的智能体读取 —— 不与他人混用,也不用于训练 |
+| **交易** | 模拟交易 + 自备密钥的券商接入 | **实时券商路由 + 实时算法部署** |
+| **量化** | 社区回测 | Quant Lab、Alpha Arena、波动率分析、时点回测 |
+| **安全与合规** | — | SSO/SAML、审计日志、基于角色的访问控制、数据隔离 |
+| **支持** | GitHub issue,尽力而为,不承诺响应 | 有 SLA 保障的优先处理 |
+| **文档** | 本仓库 | [**700 页手册**](https://fincept.in/manual) —— 41 篇指南、472 个章节 |
+| **平台** | Windows、macOS、Linux + 托管网页终端 | Windows 10/11、macOS 13+(Apple 芯片)、Linux |
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+Enterprise 使用**独立账号** —— 免费 Fincept 账号无法登录,且在绑定订阅之前应用会保持锁定。[创建 Enterprise 账号 →](https://fincept.in/enterprise/signup)
-# Windows (请从 VS 2022 Developer Command Prompt 运行)
-cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/Qt/6.x.x/msvc2022_64"
-cmake --build build --config Release --parallel
-```
+---
-#### 运行
+## Enterprise —— 六大业务台,41 个模块
-```bash
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal.exe # Windows
-```
+| 业务台 | 功能 |
+|---|---|
+| **Agentic Research** · 6 | 智能体规划工作、分派给专职智能体,读取实时数据与你的数据室,返回带来源的研究笔记 |
+| **Quant Lab & Backtesting** · 4 | 信号研究、时点回测、波动率曲面 |
+| **Deep Fundamental Research** · 8 | 股票分析、估值、衍生品、并购分析 |
+| **Markets & Execution** · 7 | 股票、加密货币与预测市场实时交易,券商路由,算法部署 |
+| **Macro & Global Intelligence** · 7 | 统计数据、政府数据、地缘政治、航运航线 |
+| **你的专属工作区** · 9 | 仪表盘、电子表格、笔记、文件、代码、报告生成器 |
-</details>
+[查看产品 →](https://fincept.in/products)
-* * *
+### 价格
-## 是什么让我们与众不同
+| | **Exclusive** | **Exclusive+** ★ 最受欢迎 | **Exclusive Pro** |
+|---|---|---|---|
+| | **99 美元**/用户/月 | **199 美元**/用户/月 | **299 美元**/用户/月 |
+| AI 积分 / 月 | 400 | 2,000 | 5,000 |
+| 投资组合 · 自选列表 | 1 · 3 | 10 · 25 | 无限 |
+| 价格历史 | 1 年 | 5 年 | 无限 |
+| 包含席位 | 1 | 1 | 2 |
+| 深度研究 + 智能体团队 | — | ✓ | ✓ |
+| 券商账户绑定 | — | ✓ | ✓ |
+| 实时券商交易 + 算法部署 | — | — | ✓ |
+按月付费 · 无年度绑定 · 无最低席位数 · **按季付费享 8.5 折**。折合**每用户每年 1,188–3,588 美元**,而一个彭博终端席位约为 **27,000 美元** —— [查看完整对比](https://fincept.in/comparison)。
-**金融终端** 是一个为拒绝受限于传统软件框架的使用者所打造的开源金融平台。我们竞争的核心在于**分析的深度**与**数据的可及性** —— 而非依赖内幕消息或封闭的独家数据源。
+**高校与学术机构:** 统一套餐 —— **5 个 Exclusive Pro 席位每月 699 美元**(标价 1,495 美元)。请联系 [[email protected]](mailto:[email protected])。
-最新版本还支持在 **数据源 → 替代数据** 中,连接可选的 **Adanos 市场情绪** 数据。配置完成后,股票研究界面将能显示 Reddit、X (Twitter)、财经新闻和 Polymarket 等跨数据源的散户情绪快照。若未启用 Adanos 连接,此功能将保持休眠状态,且应用程序的其他逻辑与以往完全相同。
+这三档方案加上学术套餐就是全部价格表。没有定制或议价的企业报价,也不再单独出售商业许可证。
+[**创建 Enterprise 账号**](https://fincept.in/enterprise/signup) · [**预约演示**](https://calendly.com/nikultilak/fincept-terminal-demo) · [阅读手册](https://fincept.in/manual)
+---
-- **原生性能**— 采用 C++20 与 Qt6 开发,没有 Electron 或网页浏览器的性能开销
-- **单一二进制**— 没有 Node.js,没有浏览器运行时,没有 JavaScript 打包工具
-- **CFA级别分析**— 通过内嵌的 Python 模块,完整涵盖 CFA 课程级别的分析能力
-- **100 多个数据连接器**— 从雅虎财经到政府数据库
-- **免费和开源**(AGPL-3.0) 并提供商业许可选项
+## 安装开源版
-* * *
+**Windows x64**、**Linux x64**(`.run` / `.deb` / `.rpm`)与 **macOS(Apple 芯片)**的安装包见 [Releases 页面](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest)。
-## 路线图
+**从源码构建** —— Linux/macOS:`git clone … && ./setup.sh`。Windows、手动构建、锁定的工具链(**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**)与故障排查见 **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)**。版本已锁定,更新或更旧的版本均不受支持。
-| 时间轴 | 里程碑 |
-| -------------- | --------------------------- |
-| **2026 年第一季度** | 实时流媒体报价、高级回测系统、券商 API 集成 |
-| **2026 年第二季度** | 期权策略构建器、多重投资组合管理、50+ AI 智能体 |
-| **2026 年第三季度** | 编程式 API、机器学习训练 UI、机构级功能 |
-| **未来** | 移动伴侣、云同步、社区市场 |
+> 在找 Enterprise 版本?它有面向 Windows、macOS 与 Linux 的独立签名安装包,需通过 Enterprise 账号登录获取 —— [在此获取](https://fincept.in/enterprise)。
-* * *
+---
-## 贡献
+## 开源版包含什么
-我们正在共同建设财务分析的未来。
+| | |
+|---|---|
+| **多资产分析** | DCF、组合优化、VaR/夏普比率、衍生品定价、固定收益、另类资产 —— 通过内嵌 Python 实现 |
+| **QuantLib 套件** | 18 个量化模块 —— 定价、风险、随机过程、波动率、固定收益 |
+| **AI 智能体** | 覆盖交易员/投资人、经济与地缘政治框架的 37 个智能体;需自备密钥(OpenAI、Anthropic、Gemini、Groq、DeepSeek、OpenRouter、Ollama) |
+| **100+ 数据连接器** | DBnomics、FRED、IMF、世界银行、AkShare、Polygon、Kraken、Yahoo Finance、政府 API |
+| **交易** | 加密货币与股票行情、模拟交易引擎、16 家券商接入 |
+| **自动化** | 可视化节点编辑器、MCP 工具集成、AI Quant Lab(机器学习、因子挖掘、强化学习) |
+| **全球情报** | 海运追踪、地缘政治分析、关系图谱 |
-**欢迎贡献:** 新的数据连接器、AI 智能体、分析模块、C++ 界面设计、官方文档撰写。
+原生 C++20 · Qt6 · 内嵌 Python 3.11 · 单一二进制 · 无 Node.js、无浏览器运行时。
+---
-- [贡献指南](docs/CONTRIBUTING.md)
-- [C++ 贡献指南](fincept-qt/CONTRIBUTING.md)
-- [Python 贡献者指南](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [报告bug](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [请求新功能](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+## 本仓库的维护方式
-* * *
+本仓库**将持续公开,不会被删除**。已经发布的内容会一直保留。
-## 面向大学与教育工作者
+现在改为**每月发布一次**,而非持续开发,因为团队的日常工作在 Enterprise 上。Issue 与 Pull Request 仍会审阅,修复按月度周期发布。安全问题请报告至 [[email protected]](mailto:[email protected])。
-**将专业级的财务分析系统带入您的课堂中**
+---
-- **$799/月**20 个帐户
-- 完全访问 Fincept 数据和 API
-- 非常适合金融、经济学和数据科学课程
-- 内置股票、投资组合、衍生品、固定收益和经济学分析
+## 参与贡献
-**感兴趣吗?** 请附上您的机构名称,发送电子邮件至**[[email protected]]。
-[大学许可详细信息](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+欢迎提交新的数据连接器、AI 智能体、分析模块、C++ 界面与文档。
-* * *
+[贡献指南](../CONTRIBUTING.md) · [C++ 指南](../CPP_CONTRIBUTOR_GUIDE.md) · [Python 指南](../PYTHON_CONTRIBUTOR_GUIDE.md) · [架构说明](../ARCHITECTURE.md) · [报告缺陷](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [提出需求](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-## 许可证
+---
-**双重许可模式:AGPL-3.0(开源)+ 商业许可**
+## Fincept 的其他产品
-### 开源许可 (AGPL-3.0)
+- **[Fincept Data API](https://docs.fincept.in)** —— 500 多个 REST 接口、423,000 多个标的、2,000 多个数据源。任何账号均含免费额度。
+- **[Quantcept](https://quantcept.io)** —— 开源的 AI 驱动命令行金融终端(Apache-2.0)。
-- 免费供个人、教育和非商业用途
-- 分发或用作网络服务时需要共享修改
-- 源代码完全透明
+---
-### 商业许可
+## 许可证
-- 若用于商业用途或需要商业级访问 Fincept 数据/API 时必备
-- 联系方式:**[[email protected]](mailto:[email protected])**
-- 细节:[商业许可指南](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+**AGPL-3.0-or-later** —— 全文见 [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)。
-### 商标声明
+个人使用、学习与学术研究免费。AGPL-3.0 是**强传染性许可证,而非宽松许可证**:如果你分发修改过的版本,或将其作为他人可访问的服务运行,就必须以相同许可证公开你的修改。对大多数法务团队而言,讨论到这一条就结束了 —— 这也是企业选择 **[Enterprise](https://fincept.in/enterprise)** 的原因:它是专有软件,没有任何 copyleft 义务需要处理。不涉及分发的个人使用则没有任何义务。
-“Fincept Terminal”和“Fincept”是Fincept Corporation 的商标。
+对于本仓库,Fincept **不再出售单独的商业或学术许可证**。商业、机构与高校需求由 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** 按上述公开价格提供。
-© 2025-2026 Fincept Corporation. 保留所有权利。
+**商标。** “Fincept”、“Fincept Terminal” 及 Fincept 标识均为 Fincept Corporation 的商标。在任何分叉、衍生、改名或商业产品中使用,均须事先获得书面许可。
-* * *
+咨询:[[email protected]](mailto:[email protected]) · [服务条款](https://fincept.in/terms) · [隐私政策](https://fincept.in/privacy)
-<div align="center">
+© 2025–2026 Fincept Corporation. 保留所有权利。
-### **你的思维是唯一的限制。数据不是。**
+---
<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+### **唯一的上限是你的思考,而不是数据。**
+
+⭐ **点星** · 🔄 **分享** · 🤝 **贡献**
-⭐**支持**· 🔄**分享**· 🤝**贡献**
+<sub>英文原版:<a href="../../README.md">README.md</a></sub>
</div>
diff --git a/docs/translations/README.zh-TW.md b/docs/translations/README.zh-TW.md
index a33e0fb89..d0db4f0c1 100644
--- a/docs/translations/README.zh-TW.md
+++ b/docs/translations/README.zh-TW.md
@@ -1,284 +1,192 @@
-# 金融終端機 (Fincept Terminal)
+# Fincept Terminal
<div align="center">
-[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)[![Hits](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal.svg?label=Visits)](https://hits.sh/github.com/Fincept-Corporation/FinceptTerminal/)
+[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-C06524)](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus)](https://isocpp.org/)
+[![Qt6](https://img.shields.io/badge/Qt-6-41CD52?logo=qt&logoColor=white)](https://www.qt.io/)
+[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white)](https://www.python.org/)
-[![Twitter](https://img.shields.io/badge/-Twitter-1DA1F2?style=flat-square&logo=twitter&logoColor=white)](https://twitter.com/intent/tweet?text=Check%20out%20FinceptTerminal&url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![LinkedIn](https://img.shields.io/badge/-LinkedIn-0077B5?style=flat-square&logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Facebook](https://img.shields.io/badge/-Facebook-1877F2?style=flat-square&logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/Fincept-Corporation/FinceptTerminal/)[![Reddit](https://img.shields.io/badge/-Reddit-FF4500?style=flat-square&logo=reddit&logoColor=white)](https://www.reddit.com/submit?url=https%3A//github.com/Fincept-Corporation/FinceptTerminal/&title=FinceptTerminal)[![WhatsApp](https://img.shields.io/badge/-WhatsApp-25D366?style=flat-square&logo=whatsapp&logoColor=white)](https://api.whatsapp.com/send?text=Check%20out%20FinceptTerminal%3A%20https%3A//github.com/Fincept-Corporation/FinceptTerminal/)
+### **唯一的上限是你的思考,而不是資料。**
-### **你的思維是唯一的限制。數據不是。**
+面向機構級金融分析、AI 自動化與無限資料連接的前沿金融智慧平台。
-最先進的金融情報平台,具備 CFA 級別分析、人工智慧自動化,以及無限的數據連接能力。
+[📥 下載](https://github.com/Fincept-Corporation/FinceptTerminal/releases) · [🏢 Enterprise](https://fincept.in/enterprise) · [💳 價格](https://fincept.in/pricing) · [📖 手冊](https://fincept.in/manual) · [💬 Discord](https://discord.gg/ae87a8ygbN)
-[📥 下載](https://github.com/Fincept-Corporation/FinceptTerminal/releases)·[📚 官方文件](https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs)·[💬 討論區](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)·[💬 Discord](https://discord.gg/ae87a8ygbN)·[🤝 合作夥伴](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/Dashboard.png)
+![Fincept Terminal](https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/images/FinceptBanner.png)
</div>
-* * *
-
-## 關於
-
-**Fincept Terminal v4** 是一個純原生的 C++20 桌面應用程式。它採用 **Qt6** 負責使用者介面與圖表渲染,並嵌入 **Python** 作為分析引擎,在單一原生執行檔中,提供媲美專業金融終端機級別的強大效能。
-
-* * *
-
-## 核心特色
-
-| **功能** | **描述** |
-| ----------------- | -------------------------------------------------------------------------------------------------------------- |
-| 📊**CFA 級別分析** | DCF 模型、投資組合最佳化 (Portfolio Optimization)、風險指標(VaR、夏普比率)、透過嵌入式 Python 進行衍生性金融商品定價 |
-| 🤖**AI 代理** | 20 多種投資者角色(巴菲特、達里歐、葛拉漢)、避險基金策略、**本地大型語言模型 (LLM) 支援**、多模型供應商(OpenAI、Anthropic、Gemini、Groq、DeepSeek、MiniMax、OpenRouter、Ollama) |
-| 🌐**100+ 數據連接器** | DBnomics、Polygon、Kraken、Yahoo 財經、FRED、IMF、世界銀行、AkShare、政府 API,以及可選的替代數據疊加(例如用於股票研究的 Adanos 市場情緒數據) |
-| 📈**實盤交易** | 加密貨幣(Kraken/HyperLiquid WebSocket)、股票、演算法交易、模擬交易引擎 (Paper Trading) |
-| 🔬**量化函式庫套件** | 18 個量化分析模組 —— 定價、風險、隨機微積分 (Stochastic)、波動率、固定收益 |
-| 🚢**全球情報** | 海上船舶追蹤、地緣政治分析、關聯性映射、衛星數據 |
-| 🎨**視覺化工作流程** | 支援自動化管線 (Pipeline) 與 MCP 工具整合的節點編輯器 (Node Editor) |
-| 🧠**AI 量化實驗室** | 機器學習模型、因子發掘 (Factor Discovery)、高頻交易 (HFT)、強化學習交易 |
-
-* * *
-
-* * *
-
-## 安裝
-
-### 選項 1 — 下載預先建置的二進位檔(推薦)
-
-您可以在 [發佈頁面 (Releases)](https://github.com/Fincept-Corporation/FinceptTerminal/releases) 下載預先建置的二進位檔。不需要安裝任何建置工具 — 只需解壓縮並執行即可。
-
-| 平台 | 下載檔案 | 執行方式 |
-| --------------- | ---------------------------------------- | ---------------------------------------------------- |
-| **Windows x64** | `FinceptTerminal-Windows-x64.zip` | 解壓縮 → 執行 `FinceptTerminal.exe` |
-| **Windows ARM64** | `FinceptTerminal-Windows-arm64.zip` | 解壓縮 → 執行 `FinceptTerminal.exe` |
-| **Linux x64** | `FinceptTerminal-Linux-x86_64.AppImage` | `chmod +x` → `./FinceptTerminal-Linux-x86_64.AppImage` |
-| **macOS (Apple 晶片)** | `FinceptTerminal-macOS-arm64.tar.gz` | 解壓縮 → 執行 `./FinceptTerminal` |
-| **macOS (Intel)** | `FinceptTerminal-macOS-x64.tar.gz` | 解壓縮 → 執行 `./FinceptTerminal` |
-| **macOS (通用)** | `FinceptTerminal-macOS-universal.tar.gz` | 解壓縮 → 執行 `./FinceptTerminal` |
-
-* * *
-
-### 選項 2 — 快速啟動(一鍵建置)
-
-複製 (Clone) 專案並執行安裝腳本 — 它會自動安裝所有相依套件 (Dependencies) 並建置應用程式:
-
-```bash
-# Linux / macOS
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal
-chmod +x setup.sh && ./setup.sh
-
-
-```bat
-# Windows — 請從 VS 2022 的開發人員命令提示字元 (Developer Command Prompt) 執行
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal
-setup.bat
-```
+> [!IMPORTANT]
+> **Fincept Terminal 提供兩種版本。**
+>
+> 🏢 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** — 為基金、家族辦公室與研究團隊打造的私有閉源版本。41 個模組、專有資料集、多代理研究、即時券商路由、私有資料室、SSO 與 SLA,**每位使用者每月 99 美元**起。團隊的日常開發都在這個版本上;若終端機是你的收入來源,就該用它。
+>
+> 📖 **本儲存庫** — 採用 AGPL-3.0 的免費開源版本,適合學習、個人使用與學術研究。儲存庫會持續公開、不會刪除,並維持**每月一次發布**。
+>
+> [**你需要哪一個? →**](#應該選擇哪個版本) · [比較](https://fincept.in/comparison) · [價格](https://fincept.in/pricing)
-該腳本會自動處理:編譯器檢查、CMake、Qt6、Python 環境設定、建置與啟動。
+---
-* * *
+## 關於
-### 選項 3 — Docker
+**Fincept Terminal** 是一款用於金融研究的原生 C++20 桌面終端機 —— Qt6 介面、內嵌 Python 3.11 分析引擎、單一執行檔,不依賴 Electron。
-```bash
-# Pull and run
-docker pull ghcr.io/fincept-corporation/fincept-terminal:latest
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \
- ghcr.io/fincept-corporation/fincept-terminal:latest
+它在**同一套資料核心上提供兩個版本**:
-# Or build from source
-git clone https://github.com/Fincept-Corporation/FinceptTerminal.git
-cd FinceptTerminal
-docker build -t fincept-terminal .
-docker run --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix fincept-terminal
-```
+| | **開源版** — 本儲存庫 | **Enterprise** — [fincept.in/enterprise](https://fincept.in/enterprise) |
+|---|---|---|
+| **適用對象** | 學習、個人使用、學術研究 | 基金、家族辦公室、研究團隊 |
+| **價格** | 免費 · AGPL-3.0 | **每位使用者每月 99 美元**起 |
+| **發布節奏** | 每月一次更新 | 持續更新 |
-> **注意:** Docker 映像檔主要適用於 Linux 環境。macOS 和 Windows 若要使用 Docker 執行 GUI,需要進行額外的 XServer 設定。。
+---
-* * *
+## 應該選擇哪個版本
-### 選項 4 — 從原始碼建置 (手動)
+| 如果你是…… | 選擇 | 原因 |
+|---|---|---|
+| 學生、愛好者或自學者 | **開源版** | 真正免費,而且會一直免費 |
+| 學術研究人員 | **開源版** | 學術用途免費 —— 需要統一管理席次的大專院校請見下方學術方案 |
+| 基金、家族辦公室、自營交易台、銀行或金融科技公司 | **Enterprise** | 不適用 AGPL 的傳染性條款,並可取得專有資料、即時路由、SSO 與 SLA |
+| 以此為職業、靠它賺錢的人 | **Enterprise** | 實際成本更低,而且是唯一每日持續開發的版本 |
-> **版本已鎖定**(Qt 6.7.2、CMake 3.27.7、MSVC 19.38 / GCC 12.3 / Apple Clang 15.0、Python 3.11.9)。為避免翻譯文件與實際程式碼產生落差,請優先遵循官方英文說明:
->
-> 👉 **[README.md (English) — Build from Source](../../README.md#option-4--build-from-source-manual)**
->
-> 使用 CMake 預設配置 (Presets) 快速啟動:
-> ```bash
-> ./setup.sh # Linux / macOS — 自動化安裝
-> setup.bat # Windows(於 VS 2022 開發人員命令提示字元執行)
->
-> # 或採用手動方式:
-> cd FinceptTerminal/fincept-qt
-> cmake --preset linux-release && cmake --build --preset linux-release
-> cmake --preset macos-release && cmake --build --preset macos-release
-> cmake --preset win-release && cmake --build --preset win-release
-> ```
+> **老實說。** 開源版是真材實料,不是閹割版的展示品 —— 但它跑在免費公開資料來源上,用的是**你的** API 金鑰與**你的** LLM 金鑰,每一次 AI 呼叫都按 token 計入你的帳單,沒有上限。社群 issue 會盡力處理,但不承諾回覆時間。若終端機是你的謀生工具,Enterprise 才是更便宜也更穩妥的席次。
-<details>
-<summary>原始說明(已過時 — 保留供參考)</summary>
+[**了解 Enterprise →**](https://fincept.in/enterprise) · [完整比較](https://fincept.in/comparison) · [價格](https://fincept.in/pricing) · [常見問題](https://fincept.in/faq)
-#### 先決條件 (Prerequisites)
+---
-| 工具 | 版本 | Windows | Linux | macOS |
-| ---------- | ----- | -------------------------------------------------------- | --------------------- | ---------------------------------- |
-| **git** | 最新版 | `winget install Git.Git` | `apt install git` | `brew install git` |
-| **CMake** | 3.20+ | `winget install Kitware.CMake` | `apt install cmake` | `brew install cmake` |
-| **C++ 編譯器** | C++20 | MSVC 2022 ([Visual Studio](https://visualstudio.microsoft.com/)) | `apt install g++` | Xcode CLT:`xcode-select --install` |
-| **Qt6** | 6.5+ | 見下文 | 見下文 | 見下文 |
-| **Python** | 3.11+ | [python.org](https://www.python.org/downloads/) | `apt install python3` | `brew install python` |
+## 開源版與 Enterprise 比較
-#### 安裝 Qt6
+| | 開源版 | **Enterprise** |
+|---|---|---|
+| **授權條款** | AGPL-3.0 —— 強傳染性。一旦散布或託管,就必須公開你的修改 | 專有授權 —— 無需處理任何 copyleft 義務 |
+| **成本** | 免費 —— 資料與 LLM 帳單自付 | 每位使用者每月 99 / 199 / 299 美元,全部包含 |
+| **模組** | 核心終端機 | **6 個業務台、41 個模組** |
+| **資料** | 免費公開資料來源,有流量限制,需自備金鑰 | 私有與專有資料集 —— 歷史更長、更新更快 |
+| **價格歷史** | 取決於免費額度 | 1 年 / 5 年 / 無限 · 提供**時點資料**,回測更可信 |
+| **AI 預算** | 自備 LLM 金鑰,按 token 自付 | 每月含 400 / 2,000 / 5,000 點數 |
+| **AI 研究** | 基礎行情助理 | 會**規劃並分派任務**的多代理研究 · Agent Studio · 最多 53 個代理 · 6 種團隊模式 |
+| **私有資料室** | — | 你的文件與模型僅由你自己的代理讀取 —— 不與他人混用,也不用於訓練 |
+| **交易** | 模擬交易 + 自備金鑰的券商串接 | **即時券商路由 + 即時演算法部署** |
+| **量化** | 社群回測 | Quant Lab、Alpha Arena、波動率分析、時點回測 |
+| **資安與法遵** | — | SSO/SAML、稽核紀錄、角色權限控管、資料隔離 |
+| **支援** | GitHub issue,盡力而為,不承諾回覆 | 有 SLA 保障的優先處理 |
+| **文件** | 本儲存庫 | [**700 頁手冊**](https://fincept.in/manual) —— 41 篇指南、472 個章節 |
+| **平台** | Windows、macOS、Linux + 託管網頁終端機 | Windows 10/11、macOS 13+(Apple 晶片)、Linux |
-**Windows:**
+Enterprise 使用**獨立帳號** —— 免費 Fincept 帳號無法登入,且在綁定訂閱之前應用程式會保持鎖定。[建立 Enterprise 帳號 →](https://fincept.in/enterprise/signup)
-```powershell
-# 透過 Qt 線上安裝程式 (推薦 — 包含 windeployqt)
-# 從 [https://www.qt.io/download-qt-installer](https://www.qt.io/download-qt-installer) 下載
-# 選擇: Qt 6.x > MSVC 2022 64-bit
+---
-# 或透過 winget 安裝
-winget install Qt.QtCreator
-```
+## Enterprise —— 六大業務台,41 個模組
-**Linux(Ubuntu/Debian):**
+| 業務台 | 功能 |
+|---|---|
+| **Agentic Research** · 6 | 代理規劃工作、分派給專職代理,讀取即時資料與你的資料室,回傳附來源的研究筆記 |
+| **Quant Lab & Backtesting** · 4 | 訊號研究、時點回測、波動率曲面 |
+| **Deep Fundamental Research** · 8 | 股票分析、估值、衍生性商品、併購分析 |
+| **Markets & Execution** · 7 | 股票、加密貨幣與預測市場即時交易,券商路由,演算法部署 |
+| **Macro & Global Intelligence** · 7 | 統計資料、政府資料、地緣政治、航運航線 |
+| **你的專屬工作區** · 9 | 儀表板、試算表、筆記、檔案、程式碼、報告產生器 |
-```bash
-sudo apt install -y \
- qt6-base-dev qt6-charts-dev qt6-tools-dev \
- libqt6sql6-sqlite libqt6websockets6-dev \
- libgl1-mesa-dev libglu1-mesa-dev
-```
+[瀏覽產品 →](https://fincept.in/products)
-**macOS:**
+### 價格
-```bash
-brew install qt
-```
+| | **Exclusive** | **Exclusive+** ★ 最受歡迎 | **Exclusive Pro** |
+|---|---|---|---|
+| | **99 美元**/使用者/月 | **199 美元**/使用者/月 | **299 美元**/使用者/月 |
+| AI 點數 / 月 | 400 | 2,000 | 5,000 |
+| 投資組合 · 自選清單 | 1 · 3 | 10 · 25 | 無限 |
+| 價格歷史 | 1 年 | 5 年 | 無限 |
+| 內含席次 | 1 | 1 | 2 |
+| 深度研究 + 代理團隊 | — | ✓ | ✓ |
+| 券商帳戶綁定 | — | ✓ | ✓ |
+| 即時券商交易 + 演算法部署 | — | — | ✓ |
-#### 建置 (Build)
+按月計費 · 無年度綁約 · 無最低席次 · **按季付款享 85 折**。折合**每位使用者每年 1,188–3,588 美元**,而一個彭博終端機席次約為 **27,000 美元** —— [查看完整比較](https://fincept.in/comparison)。
-```bash
-git clone [https://github.com/Fincept-Corporation/FinceptTerminal.git](https://github.com/Fincept-Corporation/FinceptTerminal.git)
-cd FinceptTerminal/fincept-qt
+**大專院校與學術機構:** 單一方案 —— **5 個 Exclusive Pro 席次每月 699 美元**(原價 1,495 美元)。請來信 [[email protected]](mailto:[email protected])。
-# Linux / macOS
-cmake -B build -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+這三種方案加上學術方案就是完整價目表。沒有客製或議價的企業報價,也不再另外販售商業授權。
-# Windows (請從 VS 2022 開發人員命令提示字元執行)
-cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/Qt/6.x.x/msvc2022_64"
-cmake --build build --config Release --parallel
-```
+[**建立 Enterprise 帳號**](https://fincept.in/enterprise/signup) · [**預約導覽**](https://calendly.com/nikultilak/fincept-terminal-demo) · [閱讀手冊](https://fincept.in/manual)
-#### 執行 (Run)
+---
-```bash
-./build/FinceptTerminal # Linux / macOS
-.\build\Release\FinceptTerminal.exe # Windows
-```
+## 安裝開源版
-</details>
+**Windows x64**、**Linux x64**(`.run` / `.deb` / `.rpm`)與 **macOS(Apple 晶片)**的安裝檔請見 [Releases 頁面](https://github.com/Fincept-Corporation/FinceptTerminal/releases/latest)。
-* * *
+**從原始碼建置** —— Linux/macOS:`git clone … && ./setup.sh`。Windows、手動建置、鎖定的工具鏈(**CMake 3.27.7 · Ninja 1.11.1 · Qt 6.8.3 · Python 3.11.9**)與疑難排解請見 **[docs/GETTING_STARTED.md](../GETTING_STARTED.md)**。版本已鎖定,更新或更舊的版本皆不支援。
-## 是什麼讓我們與眾不同
+> 在找 Enterprise 版本嗎?它有專屬的簽章安裝檔,支援 Windows、macOS 與 Linux,需以 Enterprise 帳號登入取得 —— [由此取得](https://fincept.in/enterprise)。
-**金融終端機 (Fincept Terminal)**是一個為拒絕受限於傳統軟體框架的使用者所打造的開源金融平台。我們競爭的優勢在於**分析的深度**與**數據的可及性** —— 而非依賴內線消息或封閉的獨家數據源。
+---
-最新版本更支援在**資料源 → 替代數據**中,連接可選的**Adanos 市場情緒**數據。設定完成後,股票研究介面將能顯示 Reddit、X (Twitter)、財經新聞和 Polymarket 等多個來源的散戶情緒快照。若未啟用 Adanos 連接,此功能將保持休眠狀態,且應用程式的其他運作邏輯與以往完全相同
+## 開源版包含哪些功能
+| | |
+|---|---|
+| **多資產分析** | DCF、投資組合最佳化、VaR/夏普值、衍生性商品定價、固定收益、另類資產 —— 透過內嵌 Python 實作 |
+| **QuantLib 套件** | 18 個量化模組 —— 定價、風險、隨機過程、波動率、固定收益 |
+| **AI 代理** | 涵蓋交易員/投資人、經濟與地緣政治框架的 37 個代理;需自備金鑰(OpenAI、Anthropic、Gemini、Groq、DeepSeek、OpenRouter、Ollama) |
+| **100+ 資料連接器** | DBnomics、FRED、IMF、世界銀行、AkShare、Polygon、Kraken、Yahoo Finance、政府 API |
+| **交易** | 加密貨幣與股票行情、模擬交易引擎、16 家券商串接 |
+| **自動化** | 視覺化節點編輯器、MCP 工具整合、AI Quant Lab(機器學習、因子挖掘、強化學習) |
+| **全球情報** | 海運追蹤、地緣政治分析、關係圖譜 |
-- **原生效能** — 採用 C++20 與 Qt6 開發,沒有 Electron 或網頁瀏覽器的效能負擔
-- **單一執行檔** — 不需要 Node.js、瀏覽器執行環境或 JavaScript 打包工具
-- **CFA 級別分析** — 透過內建的 Python 模組,完整涵蓋 CFA 課程級別的分析能力
-- **100+ 數據連接器** — 從 Yahoo 財經到各國政府資料庫
-- **免費且開源** (AGPL-3.0),並提供商業授權選項
+原生 C++20 · Qt6 · 內嵌 Python 3.11 · 單一執行檔 · 不需 Node.js、不需瀏覽器執行環境。
-* * *
+---
-## 產品開發路線圖
+## 本儲存庫的維護方式
-| 時間軸 | 里程碑 |
-| -------------- | --------------------------- |
-| **2026 年第一季** | 即時串流報價、進階回測系統、券商 API 整合 |
-| **2026 年第二季** | 選擇權策略建構器、多重投資組合管理、50+ AI 智能體 |
-| **2026 年第三季** | 程式化 API、機器學習訓練介面、機構級功能 |
-| **未來展望** | 移动端 App、雲端同步、社群市場 |
+本儲存庫**會持續公開,不會被刪除**。已經發布的內容都會保留。
-* * *
+現在改為**每月發布一次**,而非持續開發,因為團隊的日常工作在 Enterprise 上。Issue 與 Pull Request 仍會審閱,修正會依月度週期釋出。資安問題請回報至 [[email protected]](mailto:[email protected])。
-## 貢獻
+---
-我們正在共同建構財務分析的未來。
+## 參與貢獻
-**歡迎貢獻**: 新的數據連接器、AI 智能體、分析模組、C++ 介面設計、官方文件撰寫。
+歡迎提交新的資料連接器、AI 代理、分析模組、C++ 畫面與文件。
-- [貢獻指南](docs/CONTRIBUTING.md)
-- [C++ 貢獻指南](fincept-qt/CONTRIBUTING.md)
-- [Python 貢獻者指南](docs/PYTHON_CONTRIBUTOR_GUIDE.md)
-- [回報bug](https://github.com/Fincept-Corporation/FinceptTerminal/issues)
-- [許願新功能](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
+[貢獻指南](../CONTRIBUTING.md) · [C++ 指南](../CPP_CONTRIBUTOR_GUIDE.md) · [Python 指南](../PYTHON_CONTRIBUTOR_GUIDE.md) · [架構說明](../ARCHITECTURE.md) · [回報錯誤](https://github.com/Fincept-Corporation/FinceptTerminal/issues) · [提出需求](https://github.com/Fincept-Corporation/FinceptTerminal/discussions)
-* * *
+---
-## 針對大學與教育工作者
+## Fincept 的其他產品
-**將專業級的財務分析系統帶入您的課堂中。**
+- **[Fincept Data API](https://docs.fincept.in)** —— 500 多個 REST 端點、423,000 多檔標的、2,000 多個資料來源。任何帳號皆含免費額度。
+- **[Quantcept](https://quantcept.io)** —— 開源的 AI 驅動命令列金融終端機(Apache-2.0)。
-- $799/月 涵蓋 20 個使用者帳號
-- 完全存取 Fincept 數據庫與 API
-- 非常適合財務、經濟學與資料科學等課程
-- 內建 CFA 課程分析
-
-
-**有興趣嗎?** 請附上您的機構名稱,發送電子郵件至 [email protected]。
-[大學授權詳細資訊](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
-
-* * *
+---
## 授權條款
-**雙重授權模式:AGPL-3.0(開源)+ 商業授權**
-
-### 開源授權 (AGPL-3.0)
-
-- 供個人、教育及非商業用途免費使用
-- 若進行散佈或作為網路服務 (Web Service) 提供時,必須開源您的修改內容
-- 原始碼完全透明
+**AGPL-3.0-or-later** —— 全文見 [LICENSE](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE)。
-### 商業授權
+個人使用、學習與學術研究免費。AGPL-3.0 是**強傳染性授權,而非寬鬆授權**:若你散布修改過的版本,或將其作為他人可存取的服務執行,就必須以相同授權公開你的修改。對多數法務團隊而言,討論到這一條就結束了 —— 這也是企業選擇 **[Enterprise](https://fincept.in/enterprise)** 的原因:它是專有軟體,沒有任何 copyleft 義務需要處理。不涉及散布的個人使用則沒有任何義務。
-- 若用於商業用途或需要商業級存取 Fincept 數據/API 時必備
-- 聯絡方式:**[[email protected]](mailto:[email protected])**
-- 詳細資訊:[商業授權指南](https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md)
+對於本儲存庫,Fincept **不再販售單獨的商業或學術授權**。商業、機構與大專院校需求由 **[Fincept Terminal Enterprise](https://fincept.in/enterprise)** 依上述公開價格提供。
-### 商標聲明
+**商標。** 「Fincept」、「Fincept Terminal」及 Fincept 標誌均為 Fincept Corporation 的商標。在任何分支、衍生、改名或商業產品中使用,皆須事先取得書面許可。
-「Fincept Terminal」與「Fincept」為 Fincept Corporation 之註冊商標。
+洽詢:[[email protected]](mailto:[email protected]) · [服務條款](https://fincept.in/terms) · [隱私權政策](https://fincept.in/privacy)
-© 2025-2026 Fincept Corporation. 保留所有權利。
+© 2025–2026 Fincept Corporation. 保留一切權利。
-* * *
+---
<div align="center">
-### **你的思維是唯一的限制。數據不是。**
+### **唯一的上限是你的思考,而不是資料。**
-<div align="center">
-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />
- </picture>
-</a>
-</div>
+⭐ **加星** · 🔄 **分享** · 🤝 **貢獻**
-[![Email](https://img.shields.io/badge/[email protected])](mailto:[email protected])
+<sub>英文原版:<a href="../../README.md">README.md</a></sub>
-⭐ Star 支持 · 🔄 Fork 分享 · 🤝 參與貢獻
-
-</div>
\ No newline at end of file
+</div>
diff --git a/fincept-qt/.clang-tidy b/fincept-qt/.clang-tidy
index 56dd2d8fc..0231b7ec5 100644
--- a/fincept-qt/.clang-tidy
+++ b/fincept-qt/.clang-tidy
@@ -35,7 +35,11 @@ Checks: >
concurrency-*
# Treat warnings as errors in CI (set via --warnings-as-errors in CI workflow)
-WarningsAsErrors: ''
+# Narrow, high-signal gate rather than the whole check list. The PR workflow also
+# passes --warnings-as-errors explicitly; keeping them in sync means a local
+# `clang-tidy` run fails on the same things CI does, instead of the file claiming
+# a strictness CI never enforced (this was '' while the comment implied gating).
+WarningsAsErrors: 'bugprone-*,concurrency-*,performance-move-const-arg'
CheckOptions:
# Naming: snake_case functions/variables, PascalCase types
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 3f746d39d..94072e161 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.3.0 LANGUAGES C CXX)
+project(FinceptTerminal VERSION 4.4.0 LANGUAGES C CXX)
# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.
if(WIN32)
@@ -354,14 +354,15 @@ add_compile_definitions(NOMINMAX WIN32_LEAN_AND_MEAN)
# -DFINCEPT_BUILD_TESTS=ON to compile the Qt Test executables under
# fincept-qt/tests/. Run via `ctest` in the build directory.
#
-# STATUS: fincept-qt/tests/ does NOT exist yet — there is no Qt Test target in
-# the repo (no `#include <QTest>` anywhere). Turning this option on currently
-# warns and builds nothing; see the guarded add_subdirectory near the end of
-# this file. Today's automated coverage is the headless `--selftest-*` flags on
+# STATUS: fincept-qt/tests/ now exists — Qt Test suites for tst_broker_modify_fields,
+# tst_result and tst_order_validator. Each target compiles ONLY the sources it
+# needs (see tests/README.md); the app is deliberately NOT split into an OBJECT
+# library, because a main-source-list restructure re-batches the unity build and
+# can break CI in ways that never reproduce on the unity-OFF win-dev preset.
+# These complement — they do not replace — the headless `--selftest-*` flags on
# the main binary (DockLayout, ToolSelfTest, PaperTrading, PortfolioReplication,
# PortfolioMonitor, UniverseScan, FnoAlgo, Arena, Feeds), which CI runs in
-# .github/workflows/build-cpp.yml. Adding a real unit-test tree here is tracked
-# in AUDIT_2026-07-25.md §E.
+# .github/workflows/build-cpp.yml. Original tracking item: AUDIT_2026-07-25.md §E.
option(FINCEPT_BUILD_TESTS "Build the Fincept Terminal test suite" OFF)
# ── Alpha Arena live-mode geofencing ─────────────────────────────────────────
@@ -1026,6 +1027,7 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp
src/storage/sqlite/migrations/v049_order_baskets.cpp
src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
+ src/storage/sqlite/migrations/v051_drop_duplicate_indexes.cpp
# Historical OHLCV data store (Historify, Phase 3 §13)
src/storage/HistoricalDataStore.cpp
@@ -1484,6 +1486,7 @@ set(UI_SOURCES
src/ui/widgets/ConfettiOverlay.cpp
src/ui/widgets/SpeedSparkline.cpp
src/ui/widgets/LanguageSwitcher.cpp
+ src/ui/widgets/EnterprisePromo.cpp
src/ui/tables/DataTable.cpp
# Selftest for the header-only LiveTableModel/LiveTableDelegate. Also the
# only TU that includes them, so it is their compile check — a header with
@@ -2549,6 +2552,11 @@ set_source_files_properties(
src/storage/sqlite/migrations/v047_algo_multileg_trades.cpp
src/storage/sqlite/migrations/v048_instruments_exchange_unique.cpp
src/storage/sqlite/migrations/v050_alpha_arena_rewrite.cpp
+ # v051: excluded from unity too. Not because it collides (its helper is
+ # deliberately named sql_v051), but because a file that JOINS a unity batch
+ # re-batches every source after it — which can collide two files that were
+ # previously fine, and only on the unity-ON release/CI presets.
+ src/storage/sqlite/migrations/v051_drop_duplicate_indexes.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
@@ -4222,6 +4230,13 @@ endif()
# clear message instead, so turning the option on is diagnostic rather than fatal.
if(FINCEPT_BUILD_TESTS)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt")
+ # enable_testing() MUST be called from the top-level directory. Calling
+ # it only inside tests/ writes a CTestTestfile.cmake under build/tests/
+ # but none at the build root, so `ctest --test-dir build` fails with
+ # "Cannot find file: .../CTestTestfile.cmake" even though the test
+ # targets built fine. Scoped inside the option so a normal build still
+ # generates no CTest machinery at all.
+ enable_testing()
add_subdirectory(tests)
else()
message(WARNING
diff --git a/fincept-qt/agg.txt b/fincept-qt/agg.txt
deleted file mode 100644
index e11b5666c..000000000
--- a/fincept-qt/agg.txt
+++ /dev/null
@@ -1,456 +0,0 @@
-========== Handlers includes (top 40) ==========
-1: // src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
-2: //
-3: // User-action handlers: account switch / symbol selection / mode toggle,
-4: // token-expiry recovery, accounts dialog, order submit / cancel / modify,
-5: // order-book click, refresh_candles.
-6: //
-7: // Part of the partial-class split of EquityTradingScreen.cpp.
-8:
-9: #include "screens/equity_trading/EquityTradingScreen.h"
-10:
-11: #include "core/logging/Logger.h"
-12: #include "core/session/ScreenStateManager.h"
-13: #include "core/symbol/SymbolContext.h"
-14: #include "core/symbol/SymbolDragSource.h"
-15: #include "screens/equity_trading/AccountManagementDialog.h"
-16: #include "screens/equity_trading/BroadcastOrderDialog.h"
-17: #include "screens/equity_trading/EquityBottomPanel.h"
-18: #include "screens/equity_trading/EquityChart.h"
-19: #include "screens/equity_trading/EquityOrderBook.h"
-20: #include "screens/equity_trading/EquityOrderEntry.h"
-21: #include "screens/equity_trading/EquityTickerBar.h"
-22: #include "screens/equity_trading/EquityWatchlist.h"
-23: #include "services/portfolio/PortfolioService.h"
-24: #include "storage/repositories/SettingsRepository.h"
-25: #include "trading/AccountManager.h"
-26: #include "trading/ActionCenter.h"
-27: #include "trading/BrokerRegistry.h"
-28: #include "trading/DataStreamManager.h"
-29: #include "trading/OrderMatcher.h"
-30: #include "trading/PaperTrading.h"
-31: #include "ui/theme/StyleSheets.h"
-32: #include "ui/theme/Theme.h"
-33:
-34: #include <QApplication>
-35: #include <QCheckBox>
-36: #include <QComboBox>
-37: #include <QCompleter>
-38: #include <QDate>
-39: #include <QDateTime>
-40: #include <QDialog>
-
-========== Handlers: on_account_changed + credentials_saved (260-360) ==========
-260: auto* dlg = new AccountManagementDialog(this);
-261:
-262: connect(dlg, &AccountManagementDialog::account_added, this, [this](const QString& account_id) {
-263: Q_UNUSED(account_id);
-264: update_account_menu();
-265: // Don't auto-focus a freshly-added account: it has no credentials yet,
-266: // so on_account_changed() would spawn ~11 QtConcurrent::run fetches that
-267: // all bail at the empty-api_key check. On macOS that thread-storm trips
-268: // pthread_create inside QThreadPool and crashes the main thread (see
-269: // crash report 2026-05-08-123609.ips). Defer focus to credentials_saved.
-270: });
-271:
-272: connect(dlg, &AccountManagementDialog::account_removed, this, [this](const QString& account_id) {
-273: DataStreamManager::instance().stop_stream(account_id);
-274: update_account_menu();
-275: // If removed the focused account, switch to next available
-276: if (account_id == focused_account_id_) {
-277: auto accounts = AccountManager::instance().active_accounts();
-278: if (!accounts.isEmpty())
-279: on_account_changed(accounts.first().account_id);
-280: else
-281: focused_account_id_.clear();
-282: }
-283: update_connection_status();
-284: });
-285:
-286: connect(dlg, &AccountManagementDialog::credentials_saved, this, [this](const QString& account_id) {
-287: token_expired_shown_.store(false);
-288: // First account ever connected: focus it now (account_added intentionally
-289: // does not auto-focus — see comment there). on_account_changed() does its
-290: // own start_stream() + symbol/watchlist setup, so we're done after that.
-291: if (focused_account_id_.isEmpty()) {
-292: on_account_changed(account_id);
-293: AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
-294: update_connection_status();
-295: return;
-296: }
-297: // Start/restart the stream with new credentials
-298: DataStreamManager::instance().start_stream(account_id);
-299: auto* stream = DataStreamManager::instance().stream_for(account_id);
-300: if (stream && account_id == focused_account_id_) {
-301: stream->set_selected_symbol(selected_symbol_, selected_exchange_);
-302: stream->subscribe_symbols(watchlist_symbols_);
-303: }
-304: AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
-305: update_connection_status();
-306: });
-307:
-308: dlg->exec();
-309: dlg->deleteLater();
-310: }
-311:
-312: // ============================================================================
-313: // Order Handling
-314: // ============================================================================
-315:
-316: void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
-317: if (focused_account_id_.isEmpty()) {
-318: order_entry_->show_order_status("No account selected — add one via ACCOUNTS", false);
-319: return;
-320: }
-321:
-322: auto account = AccountManager::instance().get_account(focused_account_id_);
-323:
-324: if (account.trading_mode == "paper") {
-325: const QString portfolio_id = account.paper_portfolio_id;
-326: if (portfolio_id.isEmpty()) {
-327: order_entry_->show_order_status("No paper portfolio for this account", false);
-328: return;
-329: }
-330:
-331: LOG_INFO(TAG, QString("Paper order: %1 %2 x%3 account=%4")
-332: .arg(order.side == OrderSide::Buy ? "BUY" : "SELL")
-333: .arg(order.symbol)
-334: .arg(order.quantity)
-335: .arg(account.display_name));
-336:
-337: const QString side = order.side == OrderSide::Buy ? "buy" : "sell";
-338: const QString type = order_type_str(order.order_type);
-339: std::optional<double> price_opt;
-340: if (order.order_type == OrderType::Limit || order.order_type == OrderType::StopLossLimit) {
-341: price_opt = order.price;
-342: } else if (order.order_type == OrderType::Market) {
-343: const double ref = current_price_ > 0 ? current_price_ : (order.price > 0 ? order.price : 0.0);
-344: if (ref > 0)
-345: price_opt = ref;
-346: }
-347: std::optional<double> stop_opt;
-348: if (order.stop_price > 0)
-349: stop_opt = order.stop_price;
-350:
-351: if (order.order_type == OrderType::Market && !price_opt) {
-352: order_entry_->show_order_status("Price not available yet — wait for quotes to load", false);
-353: return;
-354: }
-355:
-356: try {
-357: auto pt_order = pt_place_order(portfolio_id, order.symbol, side, type, order.quantity, price_opt, stop_opt);
-358:
-359: if (order.order_type == OrderType::Market) {
-360: double fill_price = current_price_ > 0 ? current_price_ : (order.price > 0 ? order.price : 0.0);
-
-========== on_account_changed definition location ==========
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:73:void EquityTradingScreen::on_account_changed(const QString& account_id) {
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:266: // so on_account_changed() would spawn ~11 QtConcurrent::run fetches that
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:279: on_account_changed(accounts.first().account_id);
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:289: // does not auto-focus — see comment there). on_account_changed() does its
-src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:292: on_account_changed(account_id);
-src/screens/equity_trading/EquityTradingScreen.cpp:109: on_account_changed(acct);
-src/screens/equity_trading/EquityTradingScreen.cpp:350: on_account_changed(accounts.first().account_id);
-src/screens/equity_trading/EquityTradingScreen.cpp:494: on_account_changed(id);
-src/screens/equity_trading/EquityTradingScreen.cpp:568: on_account_changed(acct);
-src/screens/equity_trading/EquityTradingScreen.h:59: void on_account_changed(const QString& account_id);
-
-========== EquityTradingScreen.h (FULL) ==========
-1: #pragma once
-2: // Equity Trading Screen — multi-account coordinator.
-3: // Supports multiple broker accounts simultaneously via DataStreamManager.
-4: // Each account has its own data stream (WS/polling), portfolio, and credentials.
-5:
-6: #include "core/symbol/IGroupLinked.h"
-7: #include "screens/common/IStatefulScreen.h"
-8: #include "screens/equity_trading/EquityTypes.h"
-9: #include "trading/BrokerAccount.h"
-10: #include "trading/TradingTypes.h"
-11:
-12: #include <QHash>
-13: #include <QHideEvent>
-14: #include <QLabel>
-15: #include <QLineEdit>
-16: #include <QMenu>
-17: #include <QPushButton>
-18: #include <QShowEvent>
-19: #include <QTimer>
-20: #include <QWidget>
-21:
-22: #include <atomic>
-23:
-24: namespace fincept::screens::equity {
-25: class EquityTickerBar;
-26: class EquityWatchlist;
-27: class EquityChart;
-28: class EquityOrderEntry;
-29: class EquityOrderBook;
-30: class EquityBottomPanel;
-31: } // namespace fincept::screens::equity
-32:
-33: namespace fincept::screens {
-34:
-35: class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefulScreen {
-36: Q_OBJECT
-37: Q_INTERFACES(fincept::IGroupLinked)
-38: public:
-39: explicit EquityTradingScreen(QWidget* parent = nullptr);
-40: ~EquityTradingScreen();
-41:
-42: // IGroupLinked — see WatchlistScreen for the propagation contract.
-43: void set_group(SymbolGroup g) override { link_group_ = g; }
-44: SymbolGroup group() const override { return link_group_; }
-45: void on_group_symbol_changed(const SymbolRef& ref) override;
-46: SymbolRef current_symbol() const override;
-47:
-48: // IStatefulScreen
-49: QVariantMap save_state() const override;
-50: void restore_state(const QVariantMap& state) override;
-51: QString state_key() const override { return QStringLiteral("equity_trading"); }
-52:
-53: protected:
-54: void showEvent(QShowEvent* event) override;
-55: void hideEvent(QHideEvent* event) override;
-56:
-57: private slots:
-58: // Multi-account slots
-59: void on_account_changed(const QString& account_id);
-60: void on_symbol_selected(const QString& symbol);
-61: void on_mode_toggled();
-62: void on_accounts_clicked(); // opens AccountManagementDialog
-63: void handle_token_expired(const QString& account_id);
-64: void on_order_submitted(const trading::UnifiedOrder& order);
-65: void on_cancel_order(const QString& order_id);
-66: void on_ob_price_clicked(double price);
-67: void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
-68:
-69: void refresh_candles();
-70: void update_clock();
-71:
-72: // DataStreamManager signal handlers (on-demand / one-shot — kept as legacy signals)
-73: void on_stream_candles_fetched(const QString& account_id, const QVector<trading::BrokerCandle>& candles);
-74: void on_stream_orderbook_fetched(const QString& account_id,
-75: const QVector<QPair<double, double>>& bids,
-76: const QVector<QPair<double, double>>& asks,
-77: double spread, double spread_pct,
-78: const QVector<int>& bid_orders,
-79: const QVector<int>& ask_orders);
-80: void on_stream_time_sales_fetched(const QString& account_id, const QVector<trading::BrokerTrade>& trades);
-81: void on_stream_latest_trade_fetched(const QString& account_id, const trading::BrokerTrade& trade);
-82: void on_stream_calendar_fetched(const QString& account_id, const QVector<trading::MarketCalendarDay>& days);
-83: void on_stream_clock_fetched(const QString& account_id, const trading::MarketClock& clock);
-84:
-85: private:
-86: void setup_ui();
-87: void setup_timers();
-88: void connect_data_stream_signals();
-89: void init_focused_account();
-90: void switch_symbol(const QString& symbol);
-91: void update_account_menu();
-92: void update_connection_status();
-93: void async_modify_order(const QString& order_id, double qty, double price);
-94:
-95: // DataHub subscription helpers (D4 migration)
-96: void hub_subscribe_streaming();
-97: void hub_unsubscribe_all();
-98: void hub_subscribe_quotes();
-99: QString broker_id_for_focused() const;
-100:
-101: // ── Command bar widgets ──
-102: QPushButton* account_btn_ = nullptr; // shows focused account name
-103: QMenu* account_menu_ = nullptr; // lists all active accounts
-104: QLineEdit* symbol_input_ = nullptr;
-105: QPushButton* mode_btn_ = nullptr;
-106: QPushButton* accounts_btn_ = nullptr; // opens AccountManagementDialog
-107: QLabel* exchange_label_ = nullptr;
-108: QLabel* clock_label_ = nullptr;
-109: QLabel* conn_label_ = nullptr; // aggregate connection status
-110:
-111: // ── Sub-widgets ──
-112: equity::EquityTickerBar* ticker_bar_ = nullptr;
-113: equity::EquityWatchlist* watchlist_ = nullptr;
-114: equity::EquityChart* chart_ = nullptr;
-115: equity::EquityOrderEntry* order_entry_ = nullptr;
-116: equity::EquityOrderBook* orderbook_ = nullptr;
-117: equity::EquityBottomPanel* bottom_panel_ = nullptr;
-118:
-119: // ── Timers (only UI-local timers remain; data timers are in AccountDataStream) ──
-120: QTimer* clock_timer_ = nullptr;
-121: QTimer* market_clock_timer_ = nullptr;
-122:
-123: // ── Multi-account state ──
-124: QString focused_account_id_; // the account targeted by order entry + chart
-125: QString selected_symbol_ = "RELIANCE";
-126: QString selected_exchange_ = "NSE";
-127:
-128: // Paper trading (derived from focused account)
-129: int fill_cb_id_ = -1; // OrderMatcher fill callback
-130:
-131: // Async guards
-132: std::atomic<bool> token_expired_shown_{false};
-133:
-134: QStringList watchlist_symbols_;
-135: double current_price_ = 0.0; // last known LTP for selected symbol
-136:
-137: bool initialized_ = false;
-138: bool hub_active_ = false;
-139: QHash<QString, trading::BrokerQuote> watchlist_quote_cache_;
-140:
-141: // Symbol group link — SymbolGroup::None when unlinked.
-142: SymbolGroup link_group_ = SymbolGroup::None;
-143: };
-144:
-145: } // namespace fincept::screens
-
-========== EquityTradingScreen.cpp constructor + connects (1-120) ==========
-1: // Equity Trading Screen — multi-account coordinator.
-2: //
-3: // Core: ctor/dtor, show/hide events, setup_ui, setup_timers, update_clock,
-4: // connect_data_stream_signals, init_focused_account, update_account_menu,
-5: // update_connection_status, on_group_symbol_changed, current_symbol. Split
-6: // concerns:
-7: // - EquityTradingScreen_Streams.cpp — on_stream_* slots from DataStreamManager
-8: // - EquityTradingScreen_Handlers.cpp — user-action handlers
-9: // - EquityTradingScreen_Holdings.cpp — broker→portfolio holdings import
-10: #include "screens/equity_trading/EquityTradingScreen.h"
-11:
-12: #include "core/logging/Logger.h"
-13: #include "core/session/ScreenStateManager.h"
-14: #include "core/symbol/SymbolContext.h"
-15: #include "core/symbol/SymbolDragSource.h"
-16:
-17: #include <QApplication>
-18: #include <QMouseEvent>
-19: #include "screens/equity_trading/AccountManagementDialog.h"
-20: #include "screens/equity_trading/BroadcastOrderDialog.h"
-21: #include "screens/equity_trading/EquityBottomPanel.h"
-22: #include "screens/equity_trading/EquityChart.h"
-23: #include "screens/equity_trading/EquityOrderBook.h"
-24: #include "screens/equity_trading/EquityOrderEntry.h"
-25: #include "screens/equity_trading/EquityTickerBar.h"
-26: #include "screens/equity_trading/EquityWatchlist.h"
-27: #include "services/portfolio/PortfolioService.h"
-28: #include "storage/repositories/SettingsRepository.h"
-29: #include "trading/AccountManager.h"
-30: #include "trading/BrokerRegistry.h"
-31: #include "trading/DataStreamManager.h"
-32: #include "trading/OrderMatcher.h"
-33: #include "trading/PaperTrading.h"
-34: #include "trading/UnifiedTrading.h"
-35: #include "ui/theme/StyleSheets.h"
-36: #include "ui/theme/Theme.h"
-37:
-38: #include <QCheckBox>
-39: #include <QComboBox>
-40: #include <QCompleter>
-41: #include <QDate>
-42: #include <QDateTime>
-43: #include <QDialog>
-44: #include <QDialogButtonBox>
-45: #include <QFormLayout>
-46: #include <QHBoxLayout>
-47: #include <QHash>
-48: #include <QHeaderView>
-49: #include <QJsonArray>
-50: #include <QJsonDocument>
-51: #include <QJsonObject>
-52: #include <QLineEdit>
-53: #include <QMessageBox>
-54: #include <QPointer>
-55: #include <QPushButton>
-56: #include <QRadioButton>
-57: #include <QScrollBar>
-58: #include <QSplitter>
-59: #include <QStringListModel>
-60: #include <QTableWidget>
-61: #include <QVBoxLayout>
-62:
-63: #include <memory>
-64:
-65: #include <QtConcurrent/QtConcurrent>
-66:
-67:
-68: namespace fincept::screens {
-69:
-70: using namespace fincept::trading;
-71: using namespace fincept::screens::equity;
-72:
-73: static const QString TAG = "EquityTrading";
-74:
-75: EquityTradingScreen::EquityTradingScreen(QWidget* parent) : QWidget(parent) {
-76: watchlist_symbols_ = DEFAULT_WATCHLIST;
-77: setup_ui();
-78: setup_timers();
-79: connect_data_stream_signals();
-80:
-81: // Accept symbol drops anywhere on the screen — route through the
-82: // existing selection path so sub-panels resync and the linked group is
-83: // published to.
-84: symbol_dnd::installDropFilter(this, [this](const SymbolRef& ref, SymbolGroup) {
-85: if (ref.is_valid())
-86: on_symbol_selected(ref.symbol);
-87: });
-88: }
-89:
-90: EquityTradingScreen::~EquityTradingScreen() {
-91: if (fill_cb_id_ >= 0)
-92: OrderMatcher::instance().remove_fill_callback(fill_cb_id_);
-93: }
-94:
-95: // ============================================================================
-96: // Visibility — start/stop data streams (P3)
-97: // ============================================================================
-98:
-99: void EquityTradingScreen::showEvent(QShowEvent* event) {
-100: QWidget::showEvent(event);
-101:
-102: // Restore persisted session state on first show
-103: if (!initialized_) {
-104: const auto s = ScreenStateManager::instance().load_direct("equity_trading");
-105: if (!s.isEmpty()) {
-106: const QString acct = s.value("focused_account_id").toString();
-107: const QString sym = s.value("selected_symbol", selected_symbol_).toString();
-108: if (!acct.isEmpty() && acct != focused_account_id_ && AccountManager::instance().has_account(acct))
-109: on_account_changed(acct);
-110: if (sym != selected_symbol_)
-111: on_symbol_selected(sym);
-112: }
-113: }
-114:
-115: // Start all active account data streams
-116: DataStreamManager::instance().start_all_active();
-117: DataStreamManager::instance().resume_all();
-118:
-119: // Hub subscriptions for streaming data (D4)
-120: hub_subscribe_streaming();
-
-========== how market data refreshed: grep methods ==========
-109: on_account_changed(acct);
-323: stream->fetch_candles(selected_symbol_, tf);
-341: stream->fetch_clock();
-350: on_account_changed(accounts.first().account_id);
-370: connect(&dsm, &DataStreamManager::candles_fetched,
-371: this, &EquityTradingScreen::on_stream_candles_fetched);
-372: connect(&dsm, &DataStreamManager::orderbook_fetched,
-373: this, &EquityTradingScreen::on_stream_orderbook_fetched);
-374: connect(&dsm, &DataStreamManager::time_sales_fetched,
-375: this, &EquityTradingScreen::on_stream_time_sales_fetched);
-376: connect(&dsm, &DataStreamManager::latest_trade_fetched,
-377: this, &EquityTradingScreen::on_stream_latest_trade_fetched);
-378: connect(&dsm, &DataStreamManager::calendar_fetched,
-379: this, &EquityTradingScreen::on_stream_calendar_fetched);
-380: connect(&dsm, &DataStreamManager::clock_fetched,
-381: this, &EquityTradingScreen::on_stream_clock_fetched);
-403: auto* broker = BrokerRegistry::instance().get(account.broker_id);
-407: order_entry_->set_broker_id(account.broker_id);
-408: watchlist_->set_broker_id(account.broker_id);
-440: LOG_WARN(TAG, "Exception refreshing paper portfolio on fill");
-464: stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
-465: stream->fetch_orderbook(selected_symbol_);
-466: stream->fetch_time_sales(selected_symbol_);
-467: stream->fetch_calendar();
-468: stream->fetch_clock();
-490: auto* broker = BrokerRegistry::instance().get(acct.broker_id);
-491: const QString broker_name = broker ? broker->profile().display_name : acct.broker_id;
-494: on_account_changed(id);
-568: on_account_changed(acct);
diff --git a/fincept-qt/case_1816.json b/fincept-qt/case_1816.json
deleted file mode 100644
index cc2289708..000000000
--- a/fincept-qt/case_1816.json
+++ /dev/null
@@ -1,4478 +0,0 @@
-{
- "header": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"courtId\":\"CT16\",\"caseNumber\":\"1816-CV21655\",\"caseDesc\":\"TOMAS C POPSON V P.O. FORVEST ET AL\",\"courtDesc\":\"16th Judicial Circuit\",\"location\":\"Jackson - Kansas City\",\"filingDate\":\"08/16/2018\",\"formattedFilingDate\":\"08/16/2018\",\"predCode\":\"ZG\",\"protectionOrder\":false,\"caseType\":\"CC Pers Injury-Other\",\"caseSecurity\":\"1\",\"caseTypeCode\":\"TF\",\"vineCode\":\"347\",\"fileLocn\":\"E-CASE\",\"locnCode\":\"B2\",\"courtCode\":\"16\",\"vineDisplay\":\"N\",\"vineID\":\"1816CV21655\",\"caseDispositionDetail\":{\"dispositionDescription\":\"Dismiss by Ct w/ Prejudice\",\"docketFilingDate\":\"06/12/2019\",\"formattedDocketFilingDate\":\"06/12/2019\",\"docketTime\":\"23:55:19\",\"isLastSentenceSIS\":\"N\"},\"caseChargeList\":[],\"judgeDetails\":{\"lastName\":\"FAHNESTOCK\",\"firstName\":\"JOEL\",\"middleInitials\":\"P\",\"formattedName\":\"FAHNESTOCK, JOEL P\"},\"dispositionJudgeDetails\":{\"lastName\":\"FAHNESTOCK\",\"firstName\":\"JOEL\",\"middleInitials\":\"P\",\"partyTypeCode\":\"JUDG\",\"partyLcatCode\":\"J\",\"formattedName\":\"FAHNESTOCK, JOEL P\"},\"circuitCaseNo\":[],\"courtType\":\"C\",\"disposed\":true,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":false,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false,\"dismissed\":\"T\",\"fileId\":\"(E-CASE)\",\"isTrafficOrCriminal\":\"n\"}",
- "parsed": {
- "courtId": "CT16",
- "caseNumber": "1816-CV21655",
- "caseDesc": "TOMAS C POPSON V P.O. FORVEST ET AL",
- "courtDesc": "16th Judicial Circuit",
- "location": "Jackson - Kansas City",
- "filingDate": "08/16/2018",
- "formattedFilingDate": "08/16/2018",
- "predCode": "ZG",
- "protectionOrder": false,
- "caseType": "CC Pers Injury-Other",
- "caseSecurity": "1",
- "caseTypeCode": "TF",
- "vineCode": "347",
- "fileLocn": "E-CASE",
- "locnCode": "B2",
- "courtCode": "16",
- "vineDisplay": "N",
- "vineID": "1816CV21655",
- "caseDispositionDetail": {
- "dispositionDescription": "Dismiss by Ct w/ Prejudice",
- "docketFilingDate": "06/12/2019",
- "formattedDocketFilingDate": "06/12/2019",
- "docketTime": "23:55:19",
- "isLastSentenceSIS": "N"
- },
- "caseChargeList": [],
- "judgeDetails": {
- "lastName": "FAHNESTOCK",
- "firstName": "JOEL",
- "middleInitials": "P",
- "formattedName": "FAHNESTOCK, JOEL P"
- },
- "dispositionJudgeDetails": {
- "lastName": "FAHNESTOCK",
- "firstName": "JOEL",
- "middleInitials": "P",
- "partyTypeCode": "JUDG",
- "partyLcatCode": "J",
- "formattedName": "FAHNESTOCK, JOEL P"
- },
- "circuitCaseNo": [],
- "courtType": "C",
- "disposed": true,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": false,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false,
- "dismissed": "T",
- "fileId": "(E-CASE)",
- "isTrafficOrCriminal": "n"
- }
- },
- "party": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"caseNumber\":\"1816-CV21655\",\"protectionOrder\":false,\"locnCode\":\"B2\",\"courtCode\":\"16\",\"partyDetailsList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Plaintiff Acting Pro Se\",\"descCode\":\"PLTP\",\"startDate\":\"08/16/2018\",\"formattedPartyAddress\":\"401 INDIANA AVE\\nKANSAS CITY, MO 64124\",\"formattedPartyName\":\"POPSON, TOMAS C\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":2,\"sortSeq\":3},{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":9,\"attorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":3,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Attorney for Defendant\",\"descCode\":\"ADFT\",\"startDate\":\"03/11/2019\",\"formattedPartyAddress\":\"ASSIST ATTY GENERAL\\nMO ATTY GENERALS OFFICE\\n615 E 13TH ST STE 401\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"PETERS, DIANE\",\"formattedTelePhone\":\"\",\"partyType\":\"attorney\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":9,\"sortSeq\":9}],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"08/16/2018\",\"formattedPartyAddress\":\"1125 LOCUST\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"FORVEST, P.O.\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":3,\"sortSeq\":4},{\"addrAtyp\":\"MA\",\"addrSeqNo\":2,\"assoc\":9,\"attorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":3,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Attorney for Defendant\",\"descCode\":\"ADFT\",\"startDate\":\"03/11/2019\",\"formattedPartyAddress\":\"ASSIST ATTY GENERAL\\nMO ATTY GENERALS OFFICE\\n615 E 13TH ST STE 401\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"PETERS, DIANE\",\"formattedTelePhone\":\"\",\"partyType\":\"attorney\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":9,\"sortSeq\":9}],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"08/16/2018\",\"formattedPartyAddress\":\"2640 PROSPECT AVENUE\\nKANSAS CITY, MO 64127\",\"formattedPartyName\":\"ANDERSON, P.O.\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":4,\"sortSeq\":4},{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"08/16/2018\",\"formattedPartyAddress\":\"1125 LOCUST STREET\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"ET ALL\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":5,\"sortSeq\":4},{\"addrAtyp\":\"MA\",\"addrSeqNo\":2,\"assoc\":9,\"attorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":3,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Attorney for Defendant\",\"descCode\":\"ADFT\",\"startDate\":\"03/11/2019\",\"formattedPartyAddress\":\"ASSIST ATTY GENERAL\\nMO ATTY GENERALS OFFICE\\n615 E 13TH ST STE 401\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"PETERS, DIANE\",\"formattedTelePhone\":\"\",\"partyType\":\"attorney\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":9,\"sortSeq\":9}],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"01/10/2019\",\"formattedPartyAddress\":\"JENNY ATTERBURY-GEN COUNSEL\\n1125 LOCUST ST\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"CITY OF KANSAS CITY MO POLICE DEPARTMENT\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":7,\"sortSeq\":4},{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"01/10/2019\",\"endDate\":\"05/01/2019\",\"endReason\":\"Party Dismissed\",\"formattedPartyAddress\":\"CHIEF OF KANSAS CITY MO POLICE\\nDEPARTMENT\\n1125 LOCUST\\nKANSAS CITY, MO 64106\",\"formattedPartyName\":\"SMITH, RICHARD\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":8,\"sortSeq\":4},{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"04/05/2019\",\"formattedPartyAddress\":\"2640 PROSPECT AVE\\nKANSAS CITY, MO 64127\",\"formattedPartyName\":\"FORVEST, JUSTIN\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":10,\"sortSeq\":4},{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Defendant\",\"descCode\":\"DFT\",\"startDate\":\"04/05/2019\",\"endDate\":\"05/01/2019\",\"endReason\":\"Party Dismissed\",\"formattedPartyAddress\":\"2640 PROSPECT AVE\\nKANSAS CITY, MO 64127\",\"formattedPartyName\":\"ANDERSON, NATHAN\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZG\",\"prosecutingAtty\":false,\"ptySeqNo\":11,\"sortSeq\":4}],\"disposed\":false,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":false,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false}",
- "parsed": {
- "caseNumber": "1816-CV21655",
- "protectionOrder": false,
- "locnCode": "B2",
- "courtCode": "16",
- "partyDetailsList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Plaintiff Acting Pro Se",
- "descCode": "PLTP",
- "startDate": "08/16/2018",
- "formattedPartyAddress": "401 INDIANA AVE\nKANSAS CITY, MO 64124",
- "formattedPartyName": "POPSON, TOMAS C",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 2,
- "sortSeq": 3
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 9,
- "attorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 3,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Attorney for Defendant",
- "descCode": "ADFT",
- "startDate": "03/11/2019",
- "formattedPartyAddress": "ASSIST ATTY GENERAL\nMO ATTY GENERALS OFFICE\n615 E 13TH ST STE 401\nKANSAS CITY, MO 64106",
- "formattedPartyName": "PETERS, DIANE",
- "formattedTelePhone": "",
- "partyType": "attorney",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 9,
- "sortSeq": 9
- }
- ],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "08/16/2018",
- "formattedPartyAddress": "1125 LOCUST\nKANSAS CITY, MO 64106",
- "formattedPartyName": "FORVEST, P.O.",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 3,
- "sortSeq": 4
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 2,
- "assoc": 9,
- "attorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 3,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Attorney for Defendant",
- "descCode": "ADFT",
- "startDate": "03/11/2019",
- "formattedPartyAddress": "ASSIST ATTY GENERAL\nMO ATTY GENERALS OFFICE\n615 E 13TH ST STE 401\nKANSAS CITY, MO 64106",
- "formattedPartyName": "PETERS, DIANE",
- "formattedTelePhone": "",
- "partyType": "attorney",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 9,
- "sortSeq": 9
- }
- ],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "08/16/2018",
- "formattedPartyAddress": "2640 PROSPECT AVENUE\nKANSAS CITY, MO 64127",
- "formattedPartyName": "ANDERSON, P.O.",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 4,
- "sortSeq": 4
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "08/16/2018",
- "formattedPartyAddress": "1125 LOCUST STREET\nKANSAS CITY, MO 64106",
- "formattedPartyName": "ET ALL",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 5,
- "sortSeq": 4
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 2,
- "assoc": 9,
- "attorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 3,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Attorney for Defendant",
- "descCode": "ADFT",
- "startDate": "03/11/2019",
- "formattedPartyAddress": "ASSIST ATTY GENERAL\nMO ATTY GENERALS OFFICE\n615 E 13TH ST STE 401\nKANSAS CITY, MO 64106",
- "formattedPartyName": "PETERS, DIANE",
- "formattedTelePhone": "",
- "partyType": "attorney",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 9,
- "sortSeq": 9
- }
- ],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "01/10/2019",
- "formattedPartyAddress": "JENNY ATTERBURY-GEN COUNSEL\n1125 LOCUST ST\nKANSAS CITY, MO 64106",
- "formattedPartyName": "CITY OF KANSAS CITY MO POLICE DEPARTMENT",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 7,
- "sortSeq": 4
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "01/10/2019",
- "endDate": "05/01/2019",
- "endReason": "Party Dismissed",
- "formattedPartyAddress": "CHIEF OF KANSAS CITY MO POLICE\nDEPARTMENT\n1125 LOCUST\nKANSAS CITY, MO 64106",
- "formattedPartyName": "SMITH, RICHARD",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 8,
- "sortSeq": 4
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "04/05/2019",
- "formattedPartyAddress": "2640 PROSPECT AVE\nKANSAS CITY, MO 64127",
- "formattedPartyName": "FORVEST, JUSTIN",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 10,
- "sortSeq": 4
- },
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Defendant",
- "descCode": "DFT",
- "startDate": "04/05/2019",
- "endDate": "05/01/2019",
- "endReason": "Party Dismissed",
- "formattedPartyAddress": "2640 PROSPECT AVE\nKANSAS CITY, MO 64127",
- "formattedPartyName": "ANDERSON, NATHAN",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZG",
- "prosecutingAtty": false,
- "ptySeqNo": 11,
- "sortSeq": 4
- }
- ],
- "disposed": false,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": false,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false
- }
- },
- "docket": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"caseNumber\":\"1816-CV21655\",\"protectionOrder\":false,\"locnCode\":\"B2\",\"courtCode\":\"16\",\"docketTabModelList\":[{\"whichone\":128,\"filingDate\":\"08/26/2019\",\"docketDesc\":\"Request for Records Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":130,\"filingPartyFullName\":\"\",\"docketCode\":\"FRREC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":127,\"filingDate\":\"08/19/2019\",\"docketDesc\":\"Certificate of Service\",\"sequenceNumber\":129,\"docketText\":\"Nunc Pro Tunc Order and Judgment of Dismissal mailed to Plaintiff.\",\"filingPartyFullName\":\"\",\"docketCode\":\"CSERV\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":126,\"filingDate\":\"08/19/2019\",\"docketDesc\":\"Nunc Pro Tunc Order\",\"predCode\":\"ZORD\",\"sequenceNumber\":127,\"docketText\":\"Nunc Pro Tunc Order and Judgment of Dismissal\",\"filingPartyFullName\":\"\",\"docketCode\":\"ONUNC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":125,\"filingDate\":\"08/19/2019\",\"docketDesc\":\"Mandate from MO Ct of Appeals\",\"predCode\":\"ZFILE\",\"sequenceNumber\":126,\"docketText\":\"APPEAL DISMISSED\",\"filingPartyFullName\":\"\",\"docketCode\":\"FMACA\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":124,\"filingDate\":\"08/02/2019\",\"docketDesc\":\"Certification Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":125,\"docketText\":\"Record of Nonappearance - Depo\",\"filingPartyFullName\":\"\",\"docketCode\":\"FCERT\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":123,\"filingDate\":\"07/24/2019\",\"docketDesc\":\"Order\",\"predCode\":\"ZORD\",\"sequenceNumber\":124,\"docketText\":\"MISSOURI COURT OF APPEALS ORDER STATING APPEAL IS DISMISSED\",\"filingPartyFullName\":\"\",\"docketCode\":\"ORDER\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":122,\"filingDate\":\"07/11/2019\",\"docketDesc\":\"Motion Denied\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":123,\"filingPartyFullName\":\"\",\"docketCode\":\"MDENY\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/21/2019\",\"associatedDescription\":\"Motion to Reconsider\",\"associatedText\":\"Pltf\\u0027s Motion for Reconsideration Order of Dismissal with Prejudice with Suggestions In Support Thereof\",\"assocDockSeq\":123,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":117,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":121,\"filingDate\":\"07/11/2019\",\"docketDesc\":\"Order - Denied\",\"predCode\":\"ZORD\",\"sequenceNumber\":122,\"docketText\":\"Order Denying Motion to Reconsider\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODENY\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":120,\"filingDate\":\"06/26/2019\",\"docketDesc\":\"Ackn Notice of Appeal Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":121,\"filingPartyFullName\":\"\",\"docketCode\":\"FNOAP\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":119,\"filingDate\":\"06/25/2019\",\"docketDesc\":\"Certificate of Mailing\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":120,\"docketText\":\"Notice of Appeal to Western District sent by email to Western District Court of Appeals and the following: Attorney Diane F Peters by email and Tomas C Popson by regular mail.\",\"filingPartyFullName\":\"\",\"docketCode\":\"CMAIL\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":118,\"filingDate\":\"06/24/2019\",\"docketDesc\":\"Request for Records Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":119,\"filingPartyFullName\":\"\",\"docketCode\":\"FRREC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":117,\"filingDate\":\"06/21/2019\",\"docketDesc\":\"Notice of Appeal Filed\",\"sequenceNumber\":118,\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"NAPPE\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":116,\"filingDate\":\"06/21/2019\",\"docketDesc\":\"Motion to Reconsider\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":117,\"docketText\":\"Pltf\\u0027s Motion for Reconsideration Order of Dismissal with Prejudice with Suggestions In Support Thereof\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MRCON\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"07/11/2019\",\"associatedDescription\":\"Motion Denied\",\"assocDockSeq\":123,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":117,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":115,\"filingDate\":\"06/12/2019\",\"docketDesc\":\"Dismiss by Ct w/ Prejudice\",\"predCode\":\"ZDTRL\",\"sequenceNumber\":116,\"filingPartyFullName\":\"\",\"docketCode\":\"DDCTP\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":114,\"filingDate\":\"06/12/2019\",\"docketDesc\":\"Hearing/Trial Cancelled\",\"predCode\":\"ZHEHE\",\"sequenceNumber\":115,\"filingPartyFullName\":\"\",\"docketCode\":\"HRCAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"04/12/2019\",\"associatedDescription\":\"Hearing Continued/Rescheduled\",\"associatedText\":\"Continued due to jury trial in Division.\",\"assocDockSeq\":115,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":64,\"assocDocketCode\":\"ZHEHE\",\"document\":[]},{\"associatedDate\":\"04/22/2019\",\"associatedDescription\":\"Case Mgmt Conf Scheduled\",\"assocDockSeq\":115,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":68,\"assocDocketCode\":\"ZHESC\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"07/22/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":115,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"R\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":113,\"filingDate\":\"06/12/2019\",\"docketDesc\":\"Motion no Longer an Issue\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":114,\"docketText\":\"Case Dismissed\",\"filingPartyFullName\":\"\",\"docketCode\":\"MNLAI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/06/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Contempt to Major Gregory Volker and/or Sanctions Defendants for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":81,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/09/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Contempt to Major Bosworth and/or Sanctions Dfts for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":83,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/21/2019\",\"associatedDescription\":\"Motion to Quash\",\"associatedText\":\"Motion for Protective Order and to Quash Depositions of Chief Richard Smith and Deputy Chief David Bosworth and Suggestions in Support.\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":99,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/22/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Motion for Missouri Attorney General Erick Shcmitt to Appointed Special Counsel to Represent Defendants in Above Case with Affidavit In Support In Support Thereof\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":101,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/28/2019\",\"associatedDescription\":\"Motion to Stay\",\"associatedText\":\"Motion to Stay Discovery and Suggestions in Support.\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":108,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/31/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Contempt to Police Officer Justin Forrest for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-21-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Justin Forrest on 5-30-2019\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":109,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/31/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Contempt to Police Officer Anderson for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Anderson on 5-30-2019\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":110,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/31/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Contempt to Police Chief Richard Smith for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Chief Richard Smith on 5-30-2019\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":111,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/31/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Contempt to Deputy Chief David Bosworth for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Deputy Chief David Bosworth on 5-30-2019\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":112,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":112,\"filingDate\":\"06/12/2019\",\"docketDesc\":\"Order of Dismissal\",\"predCode\":\"ZORD\",\"sequenceNumber\":113,\"docketText\":\"Order Dismissing Case\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODISM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":111,\"filingDate\":\"06/12/2019\",\"docketDesc\":\"Judgment Entered\",\"predCode\":\"ZJUDG\",\"sequenceNumber\":128,\"filingPartyFullName\":\"\",\"docketCode\":\"JUDEN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":110,\"filingDate\":\"05/31/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":112,\"docketText\":\"Pltf\\u0027s Motion for Contempt to Deputy Chief David Bosworth for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Deputy Chief David Bosworth on 5-30-2019\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":112,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":109,\"filingDate\":\"05/31/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":111,\"docketText\":\"Pltf\\u0027s Motion for Contempt to Police Chief Richard Smith for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Chief Richard Smith on 5-30-2019\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":111,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":108,\"filingDate\":\"05/31/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":110,\"docketText\":\"Pltf\\u0027s Motion for Contempt to Police Officer Anderson for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Anderson on 5-30-2019\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":110,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":107,\"filingDate\":\"05/31/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":109,\"docketText\":\"Pltf\\u0027s Motion for Contempt to Police Officer Justin Forrest for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-21-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Justin Forrest on 5-30-2019\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":109,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":106,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Motion Denied\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":107,\"filingPartyFullName\":\"\",\"docketCode\":\"MDENY\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/09/2019\",\"associatedDescription\":\"Motion to Reconsider\",\"associatedText\":\"Pltf\\u0027s Motion for Reconsideration Order of Dismissal as to Dfts Richard Smith and PO Nathon Anderson with Suggestions In Support Thereof\",\"assocDockSeq\":107,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":82,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/10/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion for Equitable Relief from Order for Estoppel by Laches with Suggestions In Support Thereof\",\"assocDockSeq\":107,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":85,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"05/14/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Pltf\\u0027s Motion In Matter of Dismissal for Estoppel by Laches Officer Justin Forrest\\u0027s Defendant for Judgement on Pleadings and Suggestions In Support\",\"assocDockSeq\":107,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":88,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":105,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Motion Granted/Sustained\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":106,\"filingPartyFullName\":\"\",\"docketCode\":\"MGRAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/03/2019\",\"associatedDescription\":\"Motion Filed\",\"associatedText\":\"Defendant Officer Justin Forrests Motion for Judgment on the Pleadings and Suggestions in Support.\",\"assocDockSeq\":106,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":79,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":104,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Order - Denied\",\"predCode\":\"ZORD\",\"sequenceNumber\":105,\"docketText\":\"Order Denying Plaintiff\\u0027s Motion in Matter of Dismissal for Estoppel by Laches\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODENY\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":103,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Order - Denied\",\"predCode\":\"ZORD\",\"sequenceNumber\":104,\"docketText\":\"Order Denying Plaintiff\\u0027s Motion for Equitable Relief\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODENY\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":102,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Order - Denied\",\"predCode\":\"ZORD\",\"sequenceNumber\":103,\"docketText\":\"Order Denying Plaintiff\\u0027s Motion to Reconsider\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODENY\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":101,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Order of Dismissal\",\"predCode\":\"ZORD\",\"sequenceNumber\":102,\"docketText\":\"Order Granting Defendant Forrest\\u0027s Motion for Judgment on the Pleadings\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODISM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":100,\"filingDate\":\"05/28/2019\",\"docketDesc\":\"Motion to Stay\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":108,\"docketText\":\"Motion to Stay Discovery and Suggestions in Support.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"MSTAY\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":108,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"JUSTIN FORVEST\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":99,\"filingDate\":\"05/22/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":101,\"docketText\":\"Motion for Missouri Attorney General Erick Shcmitt to Appointed Special Counsel to Represent Defendants in Above Case with Affidavit In Support In Support Thereof\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":101,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":98,\"filingDate\":\"05/22/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":100,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":97,\"filingDate\":\"05/21/2019\",\"docketDesc\":\"Motion to Quash\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":99,\"docketText\":\"Motion for Protective Order and to Quash Depositions of Chief Richard Smith and Deputy Chief David Bosworth and Suggestions in Support.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"MQUAS\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":99,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":96,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":98,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":95,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":97,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":94,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":96,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":93,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Notice to Take Deposition\",\"sequenceNumber\":95,\"docketText\":\"Notice to Take Videotaped Deposition Upon Oral Examination of Colonel Bosworth\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"NTADE\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":92,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Notice to Take Deposition\",\"sequenceNumber\":94,\"docketText\":\"Notice to Take Videotaped Deposition Upon Oral Examination of P.O. Forrest Duces Tecum\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"NTADE\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":91,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Notice to Take Deposition\",\"sequenceNumber\":93,\"docketText\":\"Notice to Take Videotaped Deposition Upon Oral Examination of P.O. Anderson Duces Tecum\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"NTADE\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":90,\"filingDate\":\"05/20/2019\",\"docketDesc\":\"Notice to Take Deposition\",\"sequenceNumber\":92,\"docketText\":\"Notice to Take Videotaped Deposition Upon Oral Examination of Colonel Richard Smith-Police Chief\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"NTADE\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":89,\"filingDate\":\"05/15/2019\",\"docketDesc\":\"Suggestions in Opposition\",\"predCode\":\"ZFILE\",\"sequenceNumber\":91,\"docketText\":\"Defendants Opposition to Plaintiffs Motion for Equitable Relief.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"FSUGO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":88,\"filingDate\":\"05/14/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":90,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":87,\"filingDate\":\"05/14/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":89,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":86,\"filingDate\":\"05/14/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":88,\"docketText\":\"Pltf\\u0027s Motion In Matter of Dismissal for Estoppel by Laches Officer Justin Forrest\\u0027s Defendant for Judgement on Pleadings and Suggestions In Support\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/28/2019\",\"associatedDescription\":\"Motion Denied\",\"assocDockSeq\":107,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":88,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":85,\"filingDate\":\"05/13/2019\",\"docketDesc\":\"Suggestions in Opposition\",\"predCode\":\"ZFILE\",\"sequenceNumber\":86,\"docketText\":\"Defendants Opposition to Plaintiffs Motion for Reconsideration.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"FSUGO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST, P.O. ANDERSON, ET ALL, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":84,\"filingDate\":\"05/13/2019\",\"docketDesc\":\"Reply\",\"predCode\":\"ZFILE\",\"sequenceNumber\":87,\"docketText\":\"Defendant Forrests Reply in Support of his Motion for Judgment on the Pleadings.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"FRPLY\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":83,\"filingDate\":\"05/10/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":85,\"docketText\":\"Pltf\\u0027s Motion for Equitable Relief from Order for Estoppel by Laches with Suggestions In Support Thereof\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/28/2019\",\"associatedDescription\":\"Motion Denied\",\"assocDockSeq\":107,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":85,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":82,\"filingDate\":\"05/09/2019\",\"docketDesc\":\"Filing:\",\"predCode\":\"ZFILE\",\"sequenceNumber\":84,\"docketText\":\"Pltf Submissions In Opposition to Officer Justin Forrest\\u0027s Dft for Judgment On Pleadings and Suggestions In Support\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"FFILN\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":81,\"filingDate\":\"05/09/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":83,\"docketText\":\"Pltf\\u0027s Motion for Contempt to Major Bosworth and/or Sanctions Dfts for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":83,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":80,\"filingDate\":\"05/09/2019\",\"docketDesc\":\"Motion to Reconsider\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":82,\"docketText\":\"Pltf\\u0027s Motion for Reconsideration Order of Dismissal as to Dfts Richard Smith and PO Nathon Anderson with Suggestions In Support Thereof\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MRCON\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/28/2019\",\"associatedDescription\":\"Motion Denied\",\"assocDockSeq\":107,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":82,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":79,\"filingDate\":\"05/06/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":81,\"docketText\":\"Pltf\\u0027s Motion for Contempt to Major Gregory Volker and/or Sanctions Defendants for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"associatedText\":\"Case Dismissed\",\"assocDockSeq\":114,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":81,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":78,\"filingDate\":\"05/06/2019\",\"docketDesc\":\"Supplemental Filing\",\"predCode\":\"ZFILE\",\"sequenceNumber\":80,\"docketText\":\"First Supplemental Verified Petition for Damages\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"FSUPP\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":77,\"filingDate\":\"05/03/2019\",\"docketDesc\":\"Motion Filed\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":79,\"docketText\":\"Defendant Officer Justin Forrests Motion for Judgment on the Pleadings and Suggestions in Support.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"MOTIO\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/28/2019\",\"associatedDescription\":\"Motion Granted/Sustained\",\"assocDockSeq\":106,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":79,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST, P.O. ANDERSON, ET ALL, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":76,\"filingDate\":\"05/03/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":78,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":75,\"filingDate\":\"05/03/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":77,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":74,\"filingDate\":\"05/02/2019\",\"docketDesc\":\"Motion Granted/Sustained\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":75,\"filingPartyFullName\":\"\",\"docketCode\":\"MGRAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":73,\"filingDate\":\"05/02/2019\",\"docketDesc\":\"Order\",\"predCode\":\"ZORD\",\"sequenceNumber\":74,\"filingPartyFullName\":\"\",\"docketCode\":\"ORDER\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":72,\"filingDate\":\"05/01/2019\",\"docketDesc\":\"Order of Dismissal\",\"predCode\":\"ZORD\",\"sequenceNumber\":73,\"docketText\":\"As to Defendants Smith and Anderson\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODISM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":71,\"filingDate\":\"05/01/2019\",\"docketDesc\":\"Motion no Longer an Issue\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":72,\"filingPartyFullName\":\"\",\"docketCode\":\"MNLAI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"03/27/2019\",\"associatedDescription\":\"Motion to Dismiss\",\"associatedText\":\"Defendant KCPDs Motion to Dismiss and Suggestions in Support.\",\"assocDockSeq\":72,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":57,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":70,\"filingDate\":\"05/01/2019\",\"docketDesc\":\"Motion Granted/Sustained\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":71,\"filingPartyFullName\":\"\",\"docketCode\":\"MGRAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"03/27/2019\",\"associatedDescription\":\"Motion to Dismiss\",\"associatedText\":\"Defendants Chief Richard Smith and Officer Andersons Motion to Dismiss and Suggestions in Support.\",\"assocDockSeq\":71,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":58,\"assocDocketCode\":\"ZMTRK\",\"document\":[]},{\"associatedDate\":\"04/10/2019\",\"associatedDescription\":\"Motion to Dismiss\",\"associatedText\":\"Defendant KCMO Police Departments Motion to Dismiss and Suggestions in Support.\",\"assocDockSeq\":71,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":62,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":69,\"filingDate\":\"05/01/2019\",\"docketDesc\":\"Order of Dismissal\",\"predCode\":\"ZORD\",\"sequenceNumber\":70,\"docketText\":\"As to Defendant KCMO Police Dept.\",\"filingPartyFullName\":\"\",\"docketCode\":\"ODISM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":68,\"filingDate\":\"05/01/2019\",\"docketDesc\":\"Return Service - Other\",\"predCode\":\"ZSUSU\",\"sequenceNumber\":76,\"docketText\":\"Document ID - 19-SMCM-13; Served To - SMITH, RICHARD; Server - ; Served Date - 01-MAY-19; Served Time - 10:04:00; Service Type - Other; Reason Description - Other; Service Text - PARTY DISMISSED\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSOTH\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":67,\"filingDate\":\"04/30/2019\",\"docketDesc\":\"Motion Withdrawn\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":69,\"docketText\":\"Pltf\\u0027s Motion Request to Withdraw Second Amended Verified Petition for Damages\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MWTHD\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":66,\"filingDate\":\"04/22/2019\",\"docketDesc\":\"Case Mgmt Conf Scheduled\",\"predCode\":\"ZHESC\",\"sequenceNumber\":68,\"filingPartyFullName\":\"\",\"docketCode\":\"SCMC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Hearing/Trial Cancelled\",\"assocDockSeq\":115,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":68,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"07/22/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":68,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"C\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":65,\"filingDate\":\"04/22/2019\",\"docketDesc\":\"Case Management Ordered\",\"predCode\":\"ZORD\",\"sequenceNumber\":67,\"filingPartyFullName\":\"\",\"docketCode\":\"OCMAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":64,\"filingDate\":\"04/22/2019\",\"docketDesc\":\"Case Mgmt Conf Held\",\"predCode\":\"ZHEHE\",\"sequenceNumber\":66,\"filingPartyFullName\":\"\",\"docketCode\":\"HRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"02/10/2019\",\"associatedDescription\":\"Hearing Continued/Rescheduled\",\"assocDockSeq\":66,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":29,\"assocDocketCode\":\"ZHEHE\",\"document\":[]},{\"associatedDate\":\"04/12/2019\",\"associatedDescription\":\"Case Mgmt Conf Scheduled\",\"assocDockSeq\":66,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":65,\"assocDocketCode\":\"ZHESC\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"04/22/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":66,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"R\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":63,\"filingDate\":\"04/12/2019\",\"docketDesc\":\"Case Mgmt Conf Scheduled\",\"predCode\":\"ZHESC\",\"sequenceNumber\":65,\"filingPartyFullName\":\"\",\"docketCode\":\"SCMC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"04/22/2019\",\"associatedDescription\":\"Case Mgmt Conf Held\",\"assocDockSeq\":66,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":65,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"04/22/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":65,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"C\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":62,\"filingDate\":\"04/12/2019\",\"docketDesc\":\"Hearing Continued/Rescheduled\",\"predCode\":\"ZHEHE\",\"sequenceNumber\":64,\"docketText\":\"Continued due to jury trial in Division.\",\"filingPartyFullName\":\"\",\"docketCode\":\"HRCN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"02/10/2019\",\"associatedDescription\":\"Case Mgmt Conf Scheduled\",\"assocDockSeq\":64,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":30,\"assocDocketCode\":\"ZHESC\",\"document\":[]},{\"associatedDate\":\"06/12/2019\",\"associatedDescription\":\"Hearing/Trial Cancelled\",\"assocDockSeq\":115,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":64,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"04/15/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":64,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"R\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":61,\"filingDate\":\"04/10/2019\",\"docketDesc\":\"Motion to Dismiss\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":62,\"docketText\":\"Defendant KCMO Police Departments Motion to Dismiss and Suggestions in Support.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"MDISM\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/01/2019\",\"associatedDescription\":\"Motion Granted/Sustained\",\"assocDockSeq\":71,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":62,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"CITY OF KANSAS CITY MO POLICE DEPARTMENT\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":60,\"filingDate\":\"04/10/2019\",\"docketDesc\":\"Answer Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":63,\"docketText\":\"Defendants Chief Smith, and Officers Forrest and Andersons Answer to Plaintiffs Second Amended Petition.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"FANSW\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"RICHARD SMITH, JUSTIN FORVEST, NATHAN ANDERSON\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":59,\"filingDate\":\"04/08/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":61,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":58,\"filingDate\":\"04/05/2019\",\"docketDesc\":\"Amended Motion/Petition Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":60,\"docketText\":\"Second Amended Verified Petition for Damages\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"FAMMF\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":57,\"filingDate\":\"03/28/2019\",\"docketDesc\":\"Answer Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":59,\"docketText\":\"Defendant Officer Justin Forrests Answer and Affirmative Defenses.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"FANSW\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":56,\"filingDate\":\"03/27/2019\",\"docketDesc\":\"Motion to Dismiss\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":58,\"docketText\":\"Defendants Chief Richard Smith and Officer Andersons Motion to Dismiss and Suggestions in Support.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"MDISM\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/01/2019\",\"associatedDescription\":\"Motion Granted/Sustained\",\"assocDockSeq\":71,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":58,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. ANDERSON, RICHARD SMITH\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":55,\"filingDate\":\"03/27/2019\",\"docketDesc\":\"Motion to Dismiss\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":57,\"docketText\":\"Defendant KCPDs Motion to Dismiss and Suggestions in Support.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"MDISM\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"05/01/2019\",\"associatedDescription\":\"Motion no Longer an Issue\",\"assocDockSeq\":72,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":57,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"CITY OF KANSAS CITY MO POLICE DEPARTMENT\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":54,\"filingDate\":\"03/25/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":56,\"docketText\":\"Major Bosworth\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":53,\"filingDate\":\"03/25/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":55,\"docketText\":\"Major Gregory Volker\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":52,\"filingDate\":\"03/21/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":54,\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":51,\"filingDate\":\"03/19/2019\",\"docketDesc\":\"Proposed Order Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":52,\"docketText\":\"proposed Order sustaining Pltf\\u0027s Motion Request for Dft\\u0027s Designated Attorney of Record Diane Peters to Prodice Real Physical Address not A P.O. Box on the Court\\u0027s Record\",\"filingPartyFullName\":\"\",\"docketCode\":\"FPORD\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":50,\"filingDate\":\"03/19/2019\",\"docketDesc\":\"Request Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":51,\"docketText\":\"Pltf\\u0027s Motion Request for Dft\\u0027s Designated Attorney of Record Diane Peters to Prodice Real Physical Address not A P.O. Box on the Court\\u0027s Record\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"FREQ\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":49,\"filingDate\":\"03/19/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":50,\"docketText\":\"Pltf\\u0027s Notice for Designation and/or Appointment of A Lead Counsel of Record\",\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":48,\"filingDate\":\"03/15/2019\",\"docketDesc\":\"Subpoena Served\",\"predCode\":\"ZSSUC\",\"sequenceNumber\":53,\"filingPartyFullName\":\"\",\"docketCode\":\"SSSUB\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":47,\"filingDate\":\"03/11/2019\",\"docketDesc\":\"Entry of Appearance Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":49,\"docketText\":\"Entry of Appearance and Designation of Lead Counsel.\",\"filingPartyTypeCode\":\"ADFT\",\"filingPartyLastName\":\"PETERS\",\"filingPartyFirstName\":\"DIANE\",\"filingPartyFullName\":\"DIANE PETERS\",\"docketCode\":\"FENAP\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Attorney for Defendant\",\"displaySortSeq\":\"9\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT, RICHARD SMITH\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":46,\"filingDate\":\"03/05/2019\",\"docketDesc\":\"Retn Serv-Reg/Cert Mail Succs\",\"predCode\":\"ZSUSU\",\"sequenceNumber\":48,\"docketText\":\"Document ID - 19-SMCM-43; Served To - SMITH, RICHARD; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSCRM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":45,\"filingDate\":\"03/05/2019\",\"docketDesc\":\"Retn Serv-Reg/Cert Mail Succs\",\"predCode\":\"ZSUSU\",\"sequenceNumber\":47,\"docketText\":\"Document ID - 19-SMCM-42; Served To - CITY OF KANSAS CITY MO POLICE DEPARTMENT; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSCRM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":44,\"filingDate\":\"03/05/2019\",\"docketDesc\":\"Retn Serv-Reg/Cert Mail Succs\",\"predCode\":\"ZSUSU\",\"sequenceNumber\":46,\"docketText\":\"Document ID - 19-SMCM-41; Served To - ANDERSON, P.O.; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSCRM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":43,\"filingDate\":\"03/05/2019\",\"docketDesc\":\"Retn Serv-Reg/Cert Mail Succs\",\"predCode\":\"ZSUSU\",\"sequenceNumber\":45,\"docketText\":\"Document ID - 19-SMCM-40; Served To - FORVEST, P.O.; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSCRM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":42,\"filingDate\":\"02/25/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":44,\"docketText\":\"Document ID: 19-SMCM-43, for SMITH, RICHARD. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":41,\"filingDate\":\"02/25/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":43,\"docketText\":\"Document ID: 19-SMCM-42, for CITY OF KANSAS CITY MO POLICE DEPARTMENT. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":40,\"filingDate\":\"02/25/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":42,\"docketText\":\"Document ID: 19-SMCM-41, for ANDERSON, P.O.. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":39,\"filingDate\":\"02/25/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":41,\"docketText\":\"Document ID: 19-SMCM-40, for FORVEST, P.O.. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":38,\"filingDate\":\"02/10/2019\",\"docketDesc\":\"Case Mgmt Conf Scheduled\",\"predCode\":\"ZHESC\",\"sequenceNumber\":30,\"filingPartyFullName\":\"\",\"docketCode\":\"SCMC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"04/12/2019\",\"associatedDescription\":\"Hearing Continued/Rescheduled\",\"associatedText\":\"Continued due to jury trial in Division.\",\"assocDockSeq\":64,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":30,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"04/15/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":30,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"C\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":37,\"filingDate\":\"02/10/2019\",\"docketDesc\":\"Hearing Continued/Rescheduled\",\"predCode\":\"ZHEHE\",\"sequenceNumber\":29,\"filingPartyFullName\":\"\",\"docketCode\":\"HRCN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"01/07/2019\",\"associatedDescription\":\"Case Mgmt Conf Scheduled\",\"assocDockSeq\":29,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":17,\"assocDocketCode\":\"ZHESC\",\"document\":[]},{\"associatedDate\":\"04/22/2019\",\"associatedDescription\":\"Case Mgmt Conf Held\",\"assocDockSeq\":66,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":29,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"02/11/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":29,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"R\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":36,\"filingDate\":\"01/29/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":28,\"docketText\":\"Document ID: 19-SMCM-13, for SMITH, RICHARD. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":35,\"filingDate\":\"01/29/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":27,\"docketText\":\"Document ID: 19-SMCM-12, for CITY OF KANSAS CITY MO POLICE DEPARTMENT. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":34,\"filingDate\":\"01/29/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":26,\"docketText\":\"Document ID: 19-SMCM-11, for FORVEST, P.O.. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":33,\"filingDate\":\"01/29/2019\",\"docketDesc\":\"Summons Issued-Reg/Cert Mail\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":25,\"docketText\":\"Document ID: 19-SMCC-1034, for ANDERSON, P.O.. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIRCM\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":32,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":40,\"docketText\":\"Notice and Ackowledgement Form 4-B for Defendant; PO Anderson\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":31,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":39,\"docketText\":\"Notice and Ackowledgement Form 4-B for Defendant; Colonel Smith\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":30,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":38,\"docketText\":\"Notice and Ackowledgement Form 4-B for Defendant; PO Forvest\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":29,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":37,\"docketText\":\"Notice and Ackowledgement Form 4-B for Defendant; City of Kansas City, MO\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":28,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":36,\"docketText\":\"Notice and Ackowledgement Form 4-C for Defendant; PO Anderson\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":27,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":35,\"docketText\":\"Notice and Ackowledgement Form 4-C for Defendant; Colonel Smith\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":26,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":34,\"docketText\":\"Notice and Ackowledgement Form 4-C for Defendant; PO Forvest\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":25,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Notice\",\"sequenceNumber\":33,\"docketText\":\"Notice and Ackowledgement Form 4-C for Defendant; City of Kansas City, MO\",\"filingPartyFullName\":\"\",\"docketCode\":\"NOTIC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":24,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Amended Motion/Petition Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":32,\"docketText\":\"First Amended Verified Petition for Damages\",\"filingPartyFullName\":\"\",\"docketCode\":\"FAMMF\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":23,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Alias Summons Requested\",\"sequenceNumber\":31,\"docketText\":\"For All Defenants\",\"filingPartyFullName\":\"\",\"docketCode\":\"SRASI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":22,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Alias Summons Requested\",\"sequenceNumber\":22,\"docketText\":\"P.O. FORVEST\",\"filingPartyFullName\":\"\",\"docketCode\":\"SRASI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":21,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Alias Summons Requested\",\"sequenceNumber\":21,\"docketText\":\"P.O. ANDERSON\",\"filingPartyFullName\":\"\",\"docketCode\":\"SRASI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":20,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Alias Summons Requested\",\"sequenceNumber\":20,\"docketText\":\"CITY OF KANSAS CITY\",\"filingPartyFullName\":\"\",\"docketCode\":\"SRASI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":19,\"filingDate\":\"01/10/2019\",\"docketDesc\":\"Alias Summons Requested\",\"sequenceNumber\":19,\"docketText\":\"COL RICHARD SMITH CHIEF OF KCPD\",\"filingPartyFullName\":\"\",\"docketCode\":\"SRASI\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":18,\"filingDate\":\"01/07/2019\",\"docketDesc\":\"Case Mgmt Conf Scheduled\",\"predCode\":\"ZHESC\",\"sequenceNumber\":17,\"filingPartyFullName\":\"\",\"docketCode\":\"SCMC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"02/10/2019\",\"associatedDescription\":\"Hearing Continued/Rescheduled\",\"assocDockSeq\":29,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":17,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"02/11/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"9:00 AM\",\"associatedName\":\"JOEL P FAHNESTOCK\",\"assocFilingPartyLastName\":\"FAHNESTOCK\",\"assocFilingPartyFirstName\":\"JOEL\",\"assocFilingPartyMidInitial\":\"P\",\"assocDockSeq\":17,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"C\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":17,\"filingDate\":\"01/07/2019\",\"docketDesc\":\"Order to Transfer\",\"predCode\":\"ZORD\",\"sequenceNumber\":15,\"docketText\":\"Order Reassigning Case to Division 9\",\"filingPartyFullName\":\"\",\"docketCode\":\"OTRNF\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":16,\"filingDate\":\"01/07/2019\",\"docketDesc\":\"Hearing/Trial Cancelled\",\"predCode\":\"ZHEHE\",\"sequenceNumber\":14,\"filingPartyFullName\":\"\",\"docketCode\":\"HRCAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"08/24/2018\",\"associatedDescription\":\"Case Mgmt Conf Scheduled\",\"assocDockSeq\":14,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":4,\"assocDocketCode\":\"ZHESC\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"01/14/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"8:15 AM\",\"associatedName\":\"BRYAN E ROUND\",\"assocFilingPartyLastName\":\"ROUND\",\"assocFilingPartyFirstName\":\"BRYAN\",\"assocFilingPartyMidInitial\":\"E\",\"assocDockSeq\":14,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"R\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":15,\"filingDate\":\"01/07/2019\",\"docketDesc\":\"Ord Transfer P/Judge for Assn\",\"predCode\":\"ZORD\",\"sequenceNumber\":13,\"filingPartyFullName\":\"\",\"docketCode\":\"OTPJA\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":14,\"filingDate\":\"01/07/2019\",\"docketDesc\":\"Motion Granted/Sustained\",\"predCode\":\"ZMOUT\",\"sequenceNumber\":18,\"filingPartyFullName\":\"\",\"docketCode\":\"MGRAN\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"12/28/2018\",\"associatedDescription\":\"Motion for Change of Judge\",\"assocDockSeq\":18,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":11,\"assocDocketCode\":\"ZMTRK\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":13,\"filingDate\":\"01/07/2019\",\"docketDesc\":\"Judge Assigned\",\"predCode\":\"ZFILE\",\"sequenceNumber\":16,\"filingPartyFullName\":\"\",\"docketCode\":\"FJUDG\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":12,\"filingDate\":\"12/28/2018\",\"docketDesc\":\"Proposed Order Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":12,\"docketText\":\"Requestor\\u0027s Motion for Change of Judge is sustained.\",\"filingPartyFullName\":\"\",\"docketCode\":\"FPORD\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":11,\"filingDate\":\"12/28/2018\",\"docketDesc\":\"Motion for Change of Judge\",\"predCode\":\"ZMTRK\",\"sequenceNumber\":11,\"filingPartyTypeCode\":\"PLTP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"C\",\"filingPartyFullName\":\"TOMAS C POPSON\",\"docketCode\":\"MCHJU\",\"dtypPredCode\":\"ZG\",\"eventDesc\":\"Plaintiff Acting Pro Se\",\"displaySortSeq\":\"3\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"01/07/2019\",\"associatedDescription\":\"Motion Granted/Sustained\",\"assocDockSeq\":18,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":11,\"assocDocketCode\":\"ZMOUT\",\"document\":[]}],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":10,\"filingDate\":\"09/04/2018\",\"docketDesc\":\"Summons Returned Non-Est\",\"predCode\":\"ZSUNS\",\"sequenceNumber\":10,\"docketText\":\"Document ID - 18-SMCC-8734; Served To - ANDERSON, P.O.; Server - SIMS, EUGENE; Served Date - 31-AUG-18; Served Time - 23:59:00; Service Type - Civil Process Server; Reason Description - Insufficient Service Info\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSNON\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":9,\"filingDate\":\"09/04/2018\",\"docketDesc\":\"Summons Returned Non-Est\",\"predCode\":\"ZSUNS\",\"sequenceNumber\":9,\"docketText\":\"Document ID - 18-SMCC-8733; Served To - FORVEST, P.O.; Server - SIMS, EUGENE; Served Date - 31-AUG-18; Served Time - 23:59:00; Service Type - Civil Process Server; Reason Description - Insufficient Service Info\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSNON\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":8,\"filingDate\":\"09/04/2018\",\"docketDesc\":\"Summons Returned Non-Est\",\"predCode\":\"ZSUNS\",\"sequenceNumber\":8,\"docketText\":\"Document ID - 18-SMCC-8736; Served To - ET ALL; Server - SIMS, EUGENE; Served Date - 31-AUG-18; Served Time - 23:59:00; Service Type - Civil Process Server; Reason Description - Unable to Serve; Service Text - CAN\\u0027T ACCEPT SERVICE FOR ALL EMPLOYEES.\",\"filingPartyFullName\":\"\",\"docketCode\":\"SSNON\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":7,\"filingDate\":\"08/24/2018\",\"docketDesc\":\"Summons Issued-Circuit\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":7,\"docketText\":\"Document ID: 18-SMCC-8736, for ET ALL. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIPCC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":6,\"filingDate\":\"08/24/2018\",\"docketDesc\":\"Summons Issued-Circuit\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":6,\"docketText\":\"Document ID: 18-SMCC-8734, for ANDERSON, P.O.. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIPCC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":5,\"filingDate\":\"08/24/2018\",\"docketDesc\":\"Summons Issued-Circuit\",\"predCode\":\"ZSUIS\",\"sequenceNumber\":5,\"docketText\":\"Document ID: 18-SMCC-8733, for FORVEST, P.O.. \",\"filingPartyFullName\":\"\",\"docketCode\":\"SIPCC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":4,\"filingDate\":\"08/24/2018\",\"docketDesc\":\"Case Mgmt Conf Scheduled\",\"predCode\":\"ZHESC\",\"sequenceNumber\":4,\"filingPartyFullName\":\"\",\"docketCode\":\"SCMC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[{\"associatedDate\":\"01/07/2019\",\"associatedDescription\":\"Hearing/Trial Cancelled\",\"assocDockSeq\":14,\"documentId\":0,\"viewDoc\":\"N\",\"confInd\":\"N\",\"mainDockSeq\":4,\"assocDocketCode\":\"ZHEHE\",\"document\":[]}],\"associatedDocketScheduledInfo\":[{\"associatedDate\":\"01/14/2019\",\"associatedDescription\":\"Case Management Conference\",\"associatedText\":\"Jackson - Kansas City\",\"associatedTime\":\"8:15 AM\",\"associatedName\":\"BRYAN E ROUND\",\"assocFilingPartyLastName\":\"ROUND\",\"assocFilingPartyFirstName\":\"BRYAN\",\"assocFilingPartyMidInitial\":\"E\",\"assocDockSeq\":4,\"documentId\":0,\"mainDockSeq\":0,\"assocDtypPredCode\":\"C\"}],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":3,\"filingDate\":\"08/16/2018\",\"docketDesc\":\"Confid Filing Info Sheet Filed\",\"predCode\":\"ZFILE\",\"sequenceNumber\":3,\"filingPartyFullName\":\"\",\"docketCode\":\"FINSH\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":2,\"filingDate\":\"08/16/2018\",\"docketDesc\":\"Pet Filed in Circuit Ct\",\"predCode\":\"ZFICA\",\"sequenceNumber\":2,\"filingPartyFullName\":\"\",\"docketCode\":\"APTCC\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":1,\"filingDate\":\"08/16/2018\",\"docketDesc\":\"Judge Assigned\",\"predCode\":\"ZFILE\",\"sequenceNumber\":1,\"filingPartyFullName\":\"\",\"docketCode\":\"FJUDG\",\"dtypPredCode\":\"ZG\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false}],\"courtType\":\"C\",\"disposed\":false,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":true,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false}",
- "parsed": {
- "caseNumber": "1816-CV21655",
- "protectionOrder": false,
- "locnCode": "B2",
- "courtCode": "16",
- "docketTabModelList": [
- {
- "whichone": 128,
- "filingDate": "08/26/2019",
- "docketDesc": "Request for Records Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 130,
- "filingPartyFullName": "",
- "docketCode": "FRREC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 127,
- "filingDate": "08/19/2019",
- "docketDesc": "Certificate of Service",
- "sequenceNumber": 129,
- "docketText": "Nunc Pro Tunc Order and Judgment of Dismissal mailed to Plaintiff.",
- "filingPartyFullName": "",
- "docketCode": "CSERV",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 126,
- "filingDate": "08/19/2019",
- "docketDesc": "Nunc Pro Tunc Order",
- "predCode": "ZORD",
- "sequenceNumber": 127,
- "docketText": "Nunc Pro Tunc Order and Judgment of Dismissal",
- "filingPartyFullName": "",
- "docketCode": "ONUNC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 125,
- "filingDate": "08/19/2019",
- "docketDesc": "Mandate from MO Ct of Appeals",
- "predCode": "ZFILE",
- "sequenceNumber": 126,
- "docketText": "APPEAL DISMISSED",
- "filingPartyFullName": "",
- "docketCode": "FMACA",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 124,
- "filingDate": "08/02/2019",
- "docketDesc": "Certification Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 125,
- "docketText": "Record of Nonappearance - Depo",
- "filingPartyFullName": "",
- "docketCode": "FCERT",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 123,
- "filingDate": "07/24/2019",
- "docketDesc": "Order",
- "predCode": "ZORD",
- "sequenceNumber": 124,
- "docketText": "MISSOURI COURT OF APPEALS ORDER STATING APPEAL IS DISMISSED",
- "filingPartyFullName": "",
- "docketCode": "ORDER",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 122,
- "filingDate": "07/11/2019",
- "docketDesc": "Motion Denied",
- "predCode": "ZMOUT",
- "sequenceNumber": 123,
- "filingPartyFullName": "",
- "docketCode": "MDENY",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/21/2019",
- "associatedDescription": "Motion to Reconsider",
- "associatedText": "Pltf's Motion for Reconsideration Order of Dismissal with Prejudice with Suggestions In Support Thereof",
- "assocDockSeq": 123,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 117,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 121,
- "filingDate": "07/11/2019",
- "docketDesc": "Order - Denied",
- "predCode": "ZORD",
- "sequenceNumber": 122,
- "docketText": "Order Denying Motion to Reconsider",
- "filingPartyFullName": "",
- "docketCode": "ODENY",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 120,
- "filingDate": "06/26/2019",
- "docketDesc": "Ackn Notice of Appeal Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 121,
- "filingPartyFullName": "",
- "docketCode": "FNOAP",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 119,
- "filingDate": "06/25/2019",
- "docketDesc": "Certificate of Mailing",
- "predCode": "ZSUIS",
- "sequenceNumber": 120,
- "docketText": "Notice of Appeal to Western District sent by email to Western District Court of Appeals and the following: Attorney Diane F Peters by email and Tomas C Popson by regular mail.",
- "filingPartyFullName": "",
- "docketCode": "CMAIL",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 118,
- "filingDate": "06/24/2019",
- "docketDesc": "Request for Records Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 119,
- "filingPartyFullName": "",
- "docketCode": "FRREC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 117,
- "filingDate": "06/21/2019",
- "docketDesc": "Notice of Appeal Filed",
- "sequenceNumber": 118,
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "NAPPE",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 116,
- "filingDate": "06/21/2019",
- "docketDesc": "Motion to Reconsider",
- "predCode": "ZMTRK",
- "sequenceNumber": 117,
- "docketText": "Pltf's Motion for Reconsideration Order of Dismissal with Prejudice with Suggestions In Support Thereof",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MRCON",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "07/11/2019",
- "associatedDescription": "Motion Denied",
- "assocDockSeq": 123,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 117,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 115,
- "filingDate": "06/12/2019",
- "docketDesc": "Dismiss by Ct w/ Prejudice",
- "predCode": "ZDTRL",
- "sequenceNumber": 116,
- "filingPartyFullName": "",
- "docketCode": "DDCTP",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 114,
- "filingDate": "06/12/2019",
- "docketDesc": "Hearing/Trial Cancelled",
- "predCode": "ZHEHE",
- "sequenceNumber": 115,
- "filingPartyFullName": "",
- "docketCode": "HRCAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "04/12/2019",
- "associatedDescription": "Hearing Continued/Rescheduled",
- "associatedText": "Continued due to jury trial in Division.",
- "assocDockSeq": 115,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 64,
- "assocDocketCode": "ZHEHE",
- "document": []
- },
- {
- "associatedDate": "04/22/2019",
- "associatedDescription": "Case Mgmt Conf Scheduled",
- "assocDockSeq": 115,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 68,
- "assocDocketCode": "ZHESC",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "07/22/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 115,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "R"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 113,
- "filingDate": "06/12/2019",
- "docketDesc": "Motion no Longer an Issue",
- "predCode": "ZMOUT",
- "sequenceNumber": 114,
- "docketText": "Case Dismissed",
- "filingPartyFullName": "",
- "docketCode": "MNLAI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/06/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Contempt to Major Gregory Volker and/or Sanctions Defendants for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 81,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/09/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Contempt to Major Bosworth and/or Sanctions Dfts for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 83,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/21/2019",
- "associatedDescription": "Motion to Quash",
- "associatedText": "Motion for Protective Order and to Quash Depositions of Chief Richard Smith and Deputy Chief David Bosworth and Suggestions in Support.",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 99,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/22/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Motion for Missouri Attorney General Erick Shcmitt to Appointed Special Counsel to Represent Defendants in Above Case with Affidavit In Support In Support Thereof",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 101,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/28/2019",
- "associatedDescription": "Motion to Stay",
- "associatedText": "Motion to Stay Discovery and Suggestions in Support.",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 108,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/31/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Contempt to Police Officer Justin Forrest for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-21-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Justin Forrest on 5-30-2019",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 109,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/31/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Contempt to Police Officer Anderson for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Anderson on 5-30-2019",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 110,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/31/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Contempt to Police Chief Richard Smith for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Chief Richard Smith on 5-30-2019",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 111,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/31/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Contempt to Deputy Chief David Bosworth for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Deputy Chief David Bosworth on 5-30-2019",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 112,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 112,
- "filingDate": "06/12/2019",
- "docketDesc": "Order of Dismissal",
- "predCode": "ZORD",
- "sequenceNumber": 113,
- "docketText": "Order Dismissing Case",
- "filingPartyFullName": "",
- "docketCode": "ODISM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 111,
- "filingDate": "06/12/2019",
- "docketDesc": "Judgment Entered",
- "predCode": "ZJUDG",
- "sequenceNumber": 128,
- "filingPartyFullName": "",
- "docketCode": "JUDEN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 110,
- "filingDate": "05/31/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 112,
- "docketText": "Pltf's Motion for Contempt to Deputy Chief David Bosworth for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Deputy Chief David Bosworth on 5-30-2019",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 112,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 109,
- "filingDate": "05/31/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 111,
- "docketText": "Pltf's Motion for Contempt to Police Chief Richard Smith for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Chief Richard Smith on 5-30-2019",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 111,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 108,
- "filingDate": "05/31/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 110,
- "docketText": "Pltf's Motion for Contempt to Police Officer Anderson for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-20-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Anderson on 5-30-2019",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 110,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 107,
- "filingDate": "05/31/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 109,
- "docketText": "Pltf's Motion for Contempt to Police Officer Justin Forrest for Falure to Comply with Court Order on Subpoena Duces Tecum Issued, Surve and File on 5-21-2019 and/or Sanctions to Diane Frances Peters MoBar: 54784 for Sabotage the Deposition upon Oral Examination of Police Officer Justin Forrest on 5-30-2019",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 109,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 106,
- "filingDate": "05/28/2019",
- "docketDesc": "Motion Denied",
- "predCode": "ZMOUT",
- "sequenceNumber": 107,
- "filingPartyFullName": "",
- "docketCode": "MDENY",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/09/2019",
- "associatedDescription": "Motion to Reconsider",
- "associatedText": "Pltf's Motion for Reconsideration Order of Dismissal as to Dfts Richard Smith and PO Nathon Anderson with Suggestions In Support Thereof",
- "assocDockSeq": 107,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 82,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/10/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion for Equitable Relief from Order for Estoppel by Laches with Suggestions In Support Thereof",
- "assocDockSeq": 107,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 85,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "05/14/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Pltf's Motion In Matter of Dismissal for Estoppel by Laches Officer Justin Forrest's Defendant for Judgement on Pleadings and Suggestions In Support",
- "assocDockSeq": 107,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 88,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 105,
- "filingDate": "05/28/2019",
- "docketDesc": "Motion Granted/Sustained",
- "predCode": "ZMOUT",
- "sequenceNumber": 106,
- "filingPartyFullName": "",
- "docketCode": "MGRAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/03/2019",
- "associatedDescription": "Motion Filed",
- "associatedText": "Defendant Officer Justin Forrests Motion for Judgment on the Pleadings and Suggestions in Support.",
- "assocDockSeq": 106,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 79,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 104,
- "filingDate": "05/28/2019",
- "docketDesc": "Order - Denied",
- "predCode": "ZORD",
- "sequenceNumber": 105,
- "docketText": "Order Denying Plaintiff's Motion in Matter of Dismissal for Estoppel by Laches",
- "filingPartyFullName": "",
- "docketCode": "ODENY",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 103,
- "filingDate": "05/28/2019",
- "docketDesc": "Order - Denied",
- "predCode": "ZORD",
- "sequenceNumber": 104,
- "docketText": "Order Denying Plaintiff's Motion for Equitable Relief",
- "filingPartyFullName": "",
- "docketCode": "ODENY",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 102,
- "filingDate": "05/28/2019",
- "docketDesc": "Order - Denied",
- "predCode": "ZORD",
- "sequenceNumber": 103,
- "docketText": "Order Denying Plaintiff's Motion to Reconsider",
- "filingPartyFullName": "",
- "docketCode": "ODENY",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 101,
- "filingDate": "05/28/2019",
- "docketDesc": "Order of Dismissal",
- "predCode": "ZORD",
- "sequenceNumber": 102,
- "docketText": "Order Granting Defendant Forrest's Motion for Judgment on the Pleadings",
- "filingPartyFullName": "",
- "docketCode": "ODISM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 100,
- "filingDate": "05/28/2019",
- "docketDesc": "Motion to Stay",
- "predCode": "ZMTRK",
- "sequenceNumber": 108,
- "docketText": "Motion to Stay Discovery and Suggestions in Support.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "MSTAY",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 108,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "JUSTIN FORVEST",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 99,
- "filingDate": "05/22/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 101,
- "docketText": "Motion for Missouri Attorney General Erick Shcmitt to Appointed Special Counsel to Represent Defendants in Above Case with Affidavit In Support In Support Thereof",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 101,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 98,
- "filingDate": "05/22/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 100,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 97,
- "filingDate": "05/21/2019",
- "docketDesc": "Motion to Quash",
- "predCode": "ZMTRK",
- "sequenceNumber": 99,
- "docketText": "Motion for Protective Order and to Quash Depositions of Chief Richard Smith and Deputy Chief David Bosworth and Suggestions in Support.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "MQUAS",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 99,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 96,
- "filingDate": "05/20/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 98,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 95,
- "filingDate": "05/20/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 97,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 94,
- "filingDate": "05/20/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 96,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 93,
- "filingDate": "05/20/2019",
- "docketDesc": "Notice to Take Deposition",
- "sequenceNumber": 95,
- "docketText": "Notice to Take Videotaped Deposition Upon Oral Examination of Colonel Bosworth",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "NTADE",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 92,
- "filingDate": "05/20/2019",
- "docketDesc": "Notice to Take Deposition",
- "sequenceNumber": 94,
- "docketText": "Notice to Take Videotaped Deposition Upon Oral Examination of P.O. Forrest Duces Tecum",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "NTADE",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 91,
- "filingDate": "05/20/2019",
- "docketDesc": "Notice to Take Deposition",
- "sequenceNumber": 93,
- "docketText": "Notice to Take Videotaped Deposition Upon Oral Examination of P.O. Anderson Duces Tecum",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "NTADE",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 90,
- "filingDate": "05/20/2019",
- "docketDesc": "Notice to Take Deposition",
- "sequenceNumber": 92,
- "docketText": "Notice to Take Videotaped Deposition Upon Oral Examination of Colonel Richard Smith-Police Chief",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "NTADE",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 89,
- "filingDate": "05/15/2019",
- "docketDesc": "Suggestions in Opposition",
- "predCode": "ZFILE",
- "sequenceNumber": 91,
- "docketText": "Defendants Opposition to Plaintiffs Motion for Equitable Relief.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "FSUGO",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 88,
- "filingDate": "05/14/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 90,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 87,
- "filingDate": "05/14/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 89,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 86,
- "filingDate": "05/14/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 88,
- "docketText": "Pltf's Motion In Matter of Dismissal for Estoppel by Laches Officer Justin Forrest's Defendant for Judgement on Pleadings and Suggestions In Support",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/28/2019",
- "associatedDescription": "Motion Denied",
- "assocDockSeq": 107,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 88,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 85,
- "filingDate": "05/13/2019",
- "docketDesc": "Suggestions in Opposition",
- "predCode": "ZFILE",
- "sequenceNumber": 86,
- "docketText": "Defendants Opposition to Plaintiffs Motion for Reconsideration.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "FSUGO",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST, P.O. ANDERSON, ET ALL, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 84,
- "filingDate": "05/13/2019",
- "docketDesc": "Reply",
- "predCode": "ZFILE",
- "sequenceNumber": 87,
- "docketText": "Defendant Forrests Reply in Support of his Motion for Judgment on the Pleadings.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "FRPLY",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 83,
- "filingDate": "05/10/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 85,
- "docketText": "Pltf's Motion for Equitable Relief from Order for Estoppel by Laches with Suggestions In Support Thereof",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/28/2019",
- "associatedDescription": "Motion Denied",
- "assocDockSeq": 107,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 85,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 82,
- "filingDate": "05/09/2019",
- "docketDesc": "Filing:",
- "predCode": "ZFILE",
- "sequenceNumber": 84,
- "docketText": "Pltf Submissions In Opposition to Officer Justin Forrest's Dft for Judgment On Pleadings and Suggestions In Support",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "FFILN",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 81,
- "filingDate": "05/09/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 83,
- "docketText": "Pltf's Motion for Contempt to Major Bosworth and/or Sanctions Dfts for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 83,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 80,
- "filingDate": "05/09/2019",
- "docketDesc": "Motion to Reconsider",
- "predCode": "ZMTRK",
- "sequenceNumber": 82,
- "docketText": "Pltf's Motion for Reconsideration Order of Dismissal as to Dfts Richard Smith and PO Nathon Anderson with Suggestions In Support Thereof",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MRCON",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/28/2019",
- "associatedDescription": "Motion Denied",
- "assocDockSeq": 107,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 82,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 79,
- "filingDate": "05/06/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 81,
- "docketText": "Pltf's Motion for Contempt to Major Gregory Volker and/or Sanctions Defendants for Failure to Comply with Court Order on Subpoena Duces Tecum Issued on 3-23-2019",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "associatedText": "Case Dismissed",
- "assocDockSeq": 114,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 81,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 78,
- "filingDate": "05/06/2019",
- "docketDesc": "Supplemental Filing",
- "predCode": "ZFILE",
- "sequenceNumber": 80,
- "docketText": "First Supplemental Verified Petition for Damages",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "FSUPP",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 77,
- "filingDate": "05/03/2019",
- "docketDesc": "Motion Filed",
- "predCode": "ZMTRK",
- "sequenceNumber": 79,
- "docketText": "Defendant Officer Justin Forrests Motion for Judgment on the Pleadings and Suggestions in Support.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "MOTIO",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/28/2019",
- "associatedDescription": "Motion Granted/Sustained",
- "assocDockSeq": 106,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 79,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST, P.O. ANDERSON, ET ALL, CITY OF KANSAS CITY MO POLICE DEPARTMENT, JUSTIN FORVEST",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 76,
- "filingDate": "05/03/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 78,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 75,
- "filingDate": "05/03/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 77,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 74,
- "filingDate": "05/02/2019",
- "docketDesc": "Motion Granted/Sustained",
- "predCode": "ZMOUT",
- "sequenceNumber": 75,
- "filingPartyFullName": "",
- "docketCode": "MGRAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 73,
- "filingDate": "05/02/2019",
- "docketDesc": "Order",
- "predCode": "ZORD",
- "sequenceNumber": 74,
- "filingPartyFullName": "",
- "docketCode": "ORDER",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 72,
- "filingDate": "05/01/2019",
- "docketDesc": "Order of Dismissal",
- "predCode": "ZORD",
- "sequenceNumber": 73,
- "docketText": "As to Defendants Smith and Anderson",
- "filingPartyFullName": "",
- "docketCode": "ODISM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 71,
- "filingDate": "05/01/2019",
- "docketDesc": "Motion no Longer an Issue",
- "predCode": "ZMOUT",
- "sequenceNumber": 72,
- "filingPartyFullName": "",
- "docketCode": "MNLAI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "03/27/2019",
- "associatedDescription": "Motion to Dismiss",
- "associatedText": "Defendant KCPDs Motion to Dismiss and Suggestions in Support.",
- "assocDockSeq": 72,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 57,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 70,
- "filingDate": "05/01/2019",
- "docketDesc": "Motion Granted/Sustained",
- "predCode": "ZMOUT",
- "sequenceNumber": 71,
- "filingPartyFullName": "",
- "docketCode": "MGRAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "03/27/2019",
- "associatedDescription": "Motion to Dismiss",
- "associatedText": "Defendants Chief Richard Smith and Officer Andersons Motion to Dismiss and Suggestions in Support.",
- "assocDockSeq": 71,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 58,
- "assocDocketCode": "ZMTRK",
- "document": []
- },
- {
- "associatedDate": "04/10/2019",
- "associatedDescription": "Motion to Dismiss",
- "associatedText": "Defendant KCMO Police Departments Motion to Dismiss and Suggestions in Support.",
- "assocDockSeq": 71,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 62,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 69,
- "filingDate": "05/01/2019",
- "docketDesc": "Order of Dismissal",
- "predCode": "ZORD",
- "sequenceNumber": 70,
- "docketText": "As to Defendant KCMO Police Dept.",
- "filingPartyFullName": "",
- "docketCode": "ODISM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 68,
- "filingDate": "05/01/2019",
- "docketDesc": "Return Service - Other",
- "predCode": "ZSUSU",
- "sequenceNumber": 76,
- "docketText": "Document ID - 19-SMCM-13; Served To - SMITH, RICHARD; Server - ; Served Date - 01-MAY-19; Served Time - 10:04:00; Service Type - Other; Reason Description - Other; Service Text - PARTY DISMISSED",
- "filingPartyFullName": "",
- "docketCode": "SSOTH",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 67,
- "filingDate": "04/30/2019",
- "docketDesc": "Motion Withdrawn",
- "predCode": "ZMOUT",
- "sequenceNumber": 69,
- "docketText": "Pltf's Motion Request to Withdraw Second Amended Verified Petition for Damages",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MWTHD",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 66,
- "filingDate": "04/22/2019",
- "docketDesc": "Case Mgmt Conf Scheduled",
- "predCode": "ZHESC",
- "sequenceNumber": 68,
- "filingPartyFullName": "",
- "docketCode": "SCMC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Hearing/Trial Cancelled",
- "assocDockSeq": 115,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 68,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "07/22/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 68,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "C"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 65,
- "filingDate": "04/22/2019",
- "docketDesc": "Case Management Ordered",
- "predCode": "ZORD",
- "sequenceNumber": 67,
- "filingPartyFullName": "",
- "docketCode": "OCMAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 64,
- "filingDate": "04/22/2019",
- "docketDesc": "Case Mgmt Conf Held",
- "predCode": "ZHEHE",
- "sequenceNumber": 66,
- "filingPartyFullName": "",
- "docketCode": "HRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "02/10/2019",
- "associatedDescription": "Hearing Continued/Rescheduled",
- "assocDockSeq": 66,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 29,
- "assocDocketCode": "ZHEHE",
- "document": []
- },
- {
- "associatedDate": "04/12/2019",
- "associatedDescription": "Case Mgmt Conf Scheduled",
- "assocDockSeq": 66,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 65,
- "assocDocketCode": "ZHESC",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "04/22/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 66,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "R"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 63,
- "filingDate": "04/12/2019",
- "docketDesc": "Case Mgmt Conf Scheduled",
- "predCode": "ZHESC",
- "sequenceNumber": 65,
- "filingPartyFullName": "",
- "docketCode": "SCMC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "04/22/2019",
- "associatedDescription": "Case Mgmt Conf Held",
- "assocDockSeq": 66,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 65,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "04/22/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 65,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "C"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 62,
- "filingDate": "04/12/2019",
- "docketDesc": "Hearing Continued/Rescheduled",
- "predCode": "ZHEHE",
- "sequenceNumber": 64,
- "docketText": "Continued due to jury trial in Division.",
- "filingPartyFullName": "",
- "docketCode": "HRCN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "02/10/2019",
- "associatedDescription": "Case Mgmt Conf Scheduled",
- "assocDockSeq": 64,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 30,
- "assocDocketCode": "ZHESC",
- "document": []
- },
- {
- "associatedDate": "06/12/2019",
- "associatedDescription": "Hearing/Trial Cancelled",
- "assocDockSeq": 115,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 64,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "04/15/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 64,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "R"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 61,
- "filingDate": "04/10/2019",
- "docketDesc": "Motion to Dismiss",
- "predCode": "ZMTRK",
- "sequenceNumber": 62,
- "docketText": "Defendant KCMO Police Departments Motion to Dismiss and Suggestions in Support.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "MDISM",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/01/2019",
- "associatedDescription": "Motion Granted/Sustained",
- "assocDockSeq": 71,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 62,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "CITY OF KANSAS CITY MO POLICE DEPARTMENT",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 60,
- "filingDate": "04/10/2019",
- "docketDesc": "Answer Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 63,
- "docketText": "Defendants Chief Smith, and Officers Forrest and Andersons Answer to Plaintiffs Second Amended Petition.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "FANSW",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "RICHARD SMITH, JUSTIN FORVEST, NATHAN ANDERSON",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 59,
- "filingDate": "04/08/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 61,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 58,
- "filingDate": "04/05/2019",
- "docketDesc": "Amended Motion/Petition Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 60,
- "docketText": "Second Amended Verified Petition for Damages",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "FAMMF",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 57,
- "filingDate": "03/28/2019",
- "docketDesc": "Answer Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 59,
- "docketText": "Defendant Officer Justin Forrests Answer and Affirmative Defenses.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "FANSW",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 56,
- "filingDate": "03/27/2019",
- "docketDesc": "Motion to Dismiss",
- "predCode": "ZMTRK",
- "sequenceNumber": 58,
- "docketText": "Defendants Chief Richard Smith and Officer Andersons Motion to Dismiss and Suggestions in Support.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "MDISM",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/01/2019",
- "associatedDescription": "Motion Granted/Sustained",
- "assocDockSeq": 71,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 58,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. ANDERSON, RICHARD SMITH",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 55,
- "filingDate": "03/27/2019",
- "docketDesc": "Motion to Dismiss",
- "predCode": "ZMTRK",
- "sequenceNumber": 57,
- "docketText": "Defendant KCPDs Motion to Dismiss and Suggestions in Support.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "MDISM",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "05/01/2019",
- "associatedDescription": "Motion no Longer an Issue",
- "assocDockSeq": 72,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 57,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "CITY OF KANSAS CITY MO POLICE DEPARTMENT",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 54,
- "filingDate": "03/25/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 56,
- "docketText": "Major Bosworth",
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 53,
- "filingDate": "03/25/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 55,
- "docketText": "Major Gregory Volker",
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 52,
- "filingDate": "03/21/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 54,
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 51,
- "filingDate": "03/19/2019",
- "docketDesc": "Proposed Order Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 52,
- "docketText": "proposed Order sustaining Pltf's Motion Request for Dft's Designated Attorney of Record Diane Peters to Prodice Real Physical Address not A P.O. Box on the Court's Record",
- "filingPartyFullName": "",
- "docketCode": "FPORD",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 50,
- "filingDate": "03/19/2019",
- "docketDesc": "Request Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 51,
- "docketText": "Pltf's Motion Request for Dft's Designated Attorney of Record Diane Peters to Prodice Real Physical Address not A P.O. Box on the Court's Record",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "FREQ",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 49,
- "filingDate": "03/19/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 50,
- "docketText": "Pltf's Notice for Designation and/or Appointment of A Lead Counsel of Record",
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 48,
- "filingDate": "03/15/2019",
- "docketDesc": "Subpoena Served",
- "predCode": "ZSSUC",
- "sequenceNumber": 53,
- "filingPartyFullName": "",
- "docketCode": "SSSUB",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 47,
- "filingDate": "03/11/2019",
- "docketDesc": "Entry of Appearance Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 49,
- "docketText": "Entry of Appearance and Designation of Lead Counsel.",
- "filingPartyTypeCode": "ADFT",
- "filingPartyLastName": "PETERS",
- "filingPartyFirstName": "DIANE",
- "filingPartyFullName": "DIANE PETERS",
- "docketCode": "FENAP",
- "dtypPredCode": "ZG",
- "eventDesc": "Attorney for Defendant",
- "displaySortSeq": "9",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "P.O. FORVEST, P.O. ANDERSON, CITY OF KANSAS CITY MO POLICE DEPARTMENT, RICHARD SMITH",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 46,
- "filingDate": "03/05/2019",
- "docketDesc": "Retn Serv-Reg/Cert Mail Succs",
- "predCode": "ZSUSU",
- "sequenceNumber": 48,
- "docketText": "Document ID - 19-SMCM-43; Served To - SMITH, RICHARD; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served",
- "filingPartyFullName": "",
- "docketCode": "SSCRM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 45,
- "filingDate": "03/05/2019",
- "docketDesc": "Retn Serv-Reg/Cert Mail Succs",
- "predCode": "ZSUSU",
- "sequenceNumber": 47,
- "docketText": "Document ID - 19-SMCM-42; Served To - CITY OF KANSAS CITY MO POLICE DEPARTMENT; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served",
- "filingPartyFullName": "",
- "docketCode": "SSCRM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 44,
- "filingDate": "03/05/2019",
- "docketDesc": "Retn Serv-Reg/Cert Mail Succs",
- "predCode": "ZSUSU",
- "sequenceNumber": 46,
- "docketText": "Document ID - 19-SMCM-41; Served To - ANDERSON, P.O.; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served",
- "filingPartyFullName": "",
- "docketCode": "SSCRM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 43,
- "filingDate": "03/05/2019",
- "docketDesc": "Retn Serv-Reg/Cert Mail Succs",
- "predCode": "ZSUSU",
- "sequenceNumber": 45,
- "docketText": "Document ID - 19-SMCM-40; Served To - FORVEST, P.O.; Server - ; Served Date - 01-MAR-19; Served Time - 00:00:00; Service Type - Certified Mail; Reason Description - Served",
- "filingPartyFullName": "",
- "docketCode": "SSCRM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 42,
- "filingDate": "02/25/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 44,
- "docketText": "Document ID: 19-SMCM-43, for SMITH, RICHARD. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 41,
- "filingDate": "02/25/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 43,
- "docketText": "Document ID: 19-SMCM-42, for CITY OF KANSAS CITY MO POLICE DEPARTMENT. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 40,
- "filingDate": "02/25/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 42,
- "docketText": "Document ID: 19-SMCM-41, for ANDERSON, P.O.. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 39,
- "filingDate": "02/25/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 41,
- "docketText": "Document ID: 19-SMCM-40, for FORVEST, P.O.. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 38,
- "filingDate": "02/10/2019",
- "docketDesc": "Case Mgmt Conf Scheduled",
- "predCode": "ZHESC",
- "sequenceNumber": 30,
- "filingPartyFullName": "",
- "docketCode": "SCMC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "04/12/2019",
- "associatedDescription": "Hearing Continued/Rescheduled",
- "associatedText": "Continued due to jury trial in Division.",
- "assocDockSeq": 64,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 30,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "04/15/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 30,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "C"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 37,
- "filingDate": "02/10/2019",
- "docketDesc": "Hearing Continued/Rescheduled",
- "predCode": "ZHEHE",
- "sequenceNumber": 29,
- "filingPartyFullName": "",
- "docketCode": "HRCN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "01/07/2019",
- "associatedDescription": "Case Mgmt Conf Scheduled",
- "assocDockSeq": 29,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 17,
- "assocDocketCode": "ZHESC",
- "document": []
- },
- {
- "associatedDate": "04/22/2019",
- "associatedDescription": "Case Mgmt Conf Held",
- "assocDockSeq": 66,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 29,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "02/11/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 29,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "R"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 36,
- "filingDate": "01/29/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 28,
- "docketText": "Document ID: 19-SMCM-13, for SMITH, RICHARD. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 35,
- "filingDate": "01/29/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 27,
- "docketText": "Document ID: 19-SMCM-12, for CITY OF KANSAS CITY MO POLICE DEPARTMENT. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 34,
- "filingDate": "01/29/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 26,
- "docketText": "Document ID: 19-SMCM-11, for FORVEST, P.O.. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 33,
- "filingDate": "01/29/2019",
- "docketDesc": "Summons Issued-Reg/Cert Mail",
- "predCode": "ZSUIS",
- "sequenceNumber": 25,
- "docketText": "Document ID: 19-SMCC-1034, for ANDERSON, P.O.. ",
- "filingPartyFullName": "",
- "docketCode": "SIRCM",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 32,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 40,
- "docketText": "Notice and Ackowledgement Form 4-B for Defendant; PO Anderson",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 31,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 39,
- "docketText": "Notice and Ackowledgement Form 4-B for Defendant; Colonel Smith",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 30,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 38,
- "docketText": "Notice and Ackowledgement Form 4-B for Defendant; PO Forvest",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 29,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 37,
- "docketText": "Notice and Ackowledgement Form 4-B for Defendant; City of Kansas City, MO",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 28,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 36,
- "docketText": "Notice and Ackowledgement Form 4-C for Defendant; PO Anderson",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 27,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 35,
- "docketText": "Notice and Ackowledgement Form 4-C for Defendant; Colonel Smith",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 26,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 34,
- "docketText": "Notice and Ackowledgement Form 4-C for Defendant; PO Forvest",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 25,
- "filingDate": "01/10/2019",
- "docketDesc": "Notice",
- "sequenceNumber": 33,
- "docketText": "Notice and Ackowledgement Form 4-C for Defendant; City of Kansas City, MO",
- "filingPartyFullName": "",
- "docketCode": "NOTIC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 24,
- "filingDate": "01/10/2019",
- "docketDesc": "Amended Motion/Petition Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 32,
- "docketText": "First Amended Verified Petition for Damages",
- "filingPartyFullName": "",
- "docketCode": "FAMMF",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 23,
- "filingDate": "01/10/2019",
- "docketDesc": "Alias Summons Requested",
- "sequenceNumber": 31,
- "docketText": "For All Defenants",
- "filingPartyFullName": "",
- "docketCode": "SRASI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 22,
- "filingDate": "01/10/2019",
- "docketDesc": "Alias Summons Requested",
- "sequenceNumber": 22,
- "docketText": "P.O. FORVEST",
- "filingPartyFullName": "",
- "docketCode": "SRASI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 21,
- "filingDate": "01/10/2019",
- "docketDesc": "Alias Summons Requested",
- "sequenceNumber": 21,
- "docketText": "P.O. ANDERSON",
- "filingPartyFullName": "",
- "docketCode": "SRASI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 20,
- "filingDate": "01/10/2019",
- "docketDesc": "Alias Summons Requested",
- "sequenceNumber": 20,
- "docketText": "CITY OF KANSAS CITY",
- "filingPartyFullName": "",
- "docketCode": "SRASI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 19,
- "filingDate": "01/10/2019",
- "docketDesc": "Alias Summons Requested",
- "sequenceNumber": 19,
- "docketText": "COL RICHARD SMITH CHIEF OF KCPD",
- "filingPartyFullName": "",
- "docketCode": "SRASI",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 18,
- "filingDate": "01/07/2019",
- "docketDesc": "Case Mgmt Conf Scheduled",
- "predCode": "ZHESC",
- "sequenceNumber": 17,
- "filingPartyFullName": "",
- "docketCode": "SCMC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "02/10/2019",
- "associatedDescription": "Hearing Continued/Rescheduled",
- "assocDockSeq": 29,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 17,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "02/11/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "9:00 AM",
- "associatedName": "JOEL P FAHNESTOCK",
- "assocFilingPartyLastName": "FAHNESTOCK",
- "assocFilingPartyFirstName": "JOEL",
- "assocFilingPartyMidInitial": "P",
- "assocDockSeq": 17,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "C"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 17,
- "filingDate": "01/07/2019",
- "docketDesc": "Order to Transfer",
- "predCode": "ZORD",
- "sequenceNumber": 15,
- "docketText": "Order Reassigning Case to Division 9",
- "filingPartyFullName": "",
- "docketCode": "OTRNF",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 16,
- "filingDate": "01/07/2019",
- "docketDesc": "Hearing/Trial Cancelled",
- "predCode": "ZHEHE",
- "sequenceNumber": 14,
- "filingPartyFullName": "",
- "docketCode": "HRCAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "08/24/2018",
- "associatedDescription": "Case Mgmt Conf Scheduled",
- "assocDockSeq": 14,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 4,
- "assocDocketCode": "ZHESC",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "01/14/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "8:15 AM",
- "associatedName": "BRYAN E ROUND",
- "assocFilingPartyLastName": "ROUND",
- "assocFilingPartyFirstName": "BRYAN",
- "assocFilingPartyMidInitial": "E",
- "assocDockSeq": 14,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "R"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 15,
- "filingDate": "01/07/2019",
- "docketDesc": "Ord Transfer P/Judge for Assn",
- "predCode": "ZORD",
- "sequenceNumber": 13,
- "filingPartyFullName": "",
- "docketCode": "OTPJA",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 14,
- "filingDate": "01/07/2019",
- "docketDesc": "Motion Granted/Sustained",
- "predCode": "ZMOUT",
- "sequenceNumber": 18,
- "filingPartyFullName": "",
- "docketCode": "MGRAN",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "12/28/2018",
- "associatedDescription": "Motion for Change of Judge",
- "assocDockSeq": 18,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 11,
- "assocDocketCode": "ZMTRK",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 13,
- "filingDate": "01/07/2019",
- "docketDesc": "Judge Assigned",
- "predCode": "ZFILE",
- "sequenceNumber": 16,
- "filingPartyFullName": "",
- "docketCode": "FJUDG",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 12,
- "filingDate": "12/28/2018",
- "docketDesc": "Proposed Order Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 12,
- "docketText": "Requestor's Motion for Change of Judge is sustained.",
- "filingPartyFullName": "",
- "docketCode": "FPORD",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 11,
- "filingDate": "12/28/2018",
- "docketDesc": "Motion for Change of Judge",
- "predCode": "ZMTRK",
- "sequenceNumber": 11,
- "filingPartyTypeCode": "PLTP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "C",
- "filingPartyFullName": "TOMAS C POPSON",
- "docketCode": "MCHJU",
- "dtypPredCode": "ZG",
- "eventDesc": "Plaintiff Acting Pro Se",
- "displaySortSeq": "3",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "01/07/2019",
- "associatedDescription": "Motion Granted/Sustained",
- "assocDockSeq": 18,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 11,
- "assocDocketCode": "ZMOUT",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 10,
- "filingDate": "09/04/2018",
- "docketDesc": "Summons Returned Non-Est",
- "predCode": "ZSUNS",
- "sequenceNumber": 10,
- "docketText": "Document ID - 18-SMCC-8734; Served To - ANDERSON, P.O.; Server - SIMS, EUGENE; Served Date - 31-AUG-18; Served Time - 23:59:00; Service Type - Civil Process Server; Reason Description - Insufficient Service Info",
- "filingPartyFullName": "",
- "docketCode": "SSNON",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 9,
- "filingDate": "09/04/2018",
- "docketDesc": "Summons Returned Non-Est",
- "predCode": "ZSUNS",
- "sequenceNumber": 9,
- "docketText": "Document ID - 18-SMCC-8733; Served To - FORVEST, P.O.; Server - SIMS, EUGENE; Served Date - 31-AUG-18; Served Time - 23:59:00; Service Type - Civil Process Server; Reason Description - Insufficient Service Info",
- "filingPartyFullName": "",
- "docketCode": "SSNON",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 8,
- "filingDate": "09/04/2018",
- "docketDesc": "Summons Returned Non-Est",
- "predCode": "ZSUNS",
- "sequenceNumber": 8,
- "docketText": "Document ID - 18-SMCC-8736; Served To - ET ALL; Server - SIMS, EUGENE; Served Date - 31-AUG-18; Served Time - 23:59:00; Service Type - Civil Process Server; Reason Description - Unable to Serve; Service Text - CAN'T ACCEPT SERVICE FOR ALL EMPLOYEES.",
- "filingPartyFullName": "",
- "docketCode": "SSNON",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 7,
- "filingDate": "08/24/2018",
- "docketDesc": "Summons Issued-Circuit",
- "predCode": "ZSUIS",
- "sequenceNumber": 7,
- "docketText": "Document ID: 18-SMCC-8736, for ET ALL. ",
- "filingPartyFullName": "",
- "docketCode": "SIPCC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 6,
- "filingDate": "08/24/2018",
- "docketDesc": "Summons Issued-Circuit",
- "predCode": "ZSUIS",
- "sequenceNumber": 6,
- "docketText": "Document ID: 18-SMCC-8734, for ANDERSON, P.O.. ",
- "filingPartyFullName": "",
- "docketCode": "SIPCC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 5,
- "filingDate": "08/24/2018",
- "docketDesc": "Summons Issued-Circuit",
- "predCode": "ZSUIS",
- "sequenceNumber": 5,
- "docketText": "Document ID: 18-SMCC-8733, for FORVEST, P.O.. ",
- "filingPartyFullName": "",
- "docketCode": "SIPCC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 4,
- "filingDate": "08/24/2018",
- "docketDesc": "Case Mgmt Conf Scheduled",
- "predCode": "ZHESC",
- "sequenceNumber": 4,
- "filingPartyFullName": "",
- "docketCode": "SCMC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [
- {
- "associatedDate": "01/07/2019",
- "associatedDescription": "Hearing/Trial Cancelled",
- "assocDockSeq": 14,
- "documentId": 0,
- "viewDoc": "N",
- "confInd": "N",
- "mainDockSeq": 4,
- "assocDocketCode": "ZHEHE",
- "document": []
- }
- ],
- "associatedDocketScheduledInfo": [
- {
- "associatedDate": "01/14/2019",
- "associatedDescription": "Case Management Conference",
- "associatedText": "Jackson - Kansas City",
- "associatedTime": "8:15 AM",
- "associatedName": "BRYAN E ROUND",
- "assocFilingPartyLastName": "ROUND",
- "assocFilingPartyFirstName": "BRYAN",
- "assocFilingPartyMidInitial": "E",
- "assocDockSeq": 4,
- "documentId": 0,
- "mainDockSeq": 0,
- "assocDtypPredCode": "C"
- }
- ],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 3,
- "filingDate": "08/16/2018",
- "docketDesc": "Confid Filing Info Sheet Filed",
- "predCode": "ZFILE",
- "sequenceNumber": 3,
- "filingPartyFullName": "",
- "docketCode": "FINSH",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 2,
- "filingDate": "08/16/2018",
- "docketDesc": "Pet Filed in Circuit Ct",
- "predCode": "ZFICA",
- "sequenceNumber": 2,
- "filingPartyFullName": "",
- "docketCode": "APTCC",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 1,
- "filingDate": "08/16/2018",
- "docketDesc": "Judge Assigned",
- "predCode": "ZFILE",
- "sequenceNumber": 1,
- "filingPartyFullName": "",
- "docketCode": "FJUDG",
- "dtypPredCode": "ZG",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- }
- ],
- "courtType": "C",
- "disposed": false,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": true,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false
- }
- },
- "charges": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "[]",
- "parsed": []
- },
- "judgment": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "[]",
- "parsed": []
- },
- "payment": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"courtId\":\"CT16\",\"caseNumber\":\"1816-CV21655\",\"protectionOrder\":false,\"locnCode\":\"B2\",\"courtCode\":\"16\",\"disposed\":true,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":false,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false,\"dismissed\":\"T\"}",
- "parsed": {
- "courtId": "CT16",
- "caseNumber": "1816-CV21655",
- "protectionOrder": false,
- "locnCode": "B2",
- "courtCode": "16",
- "disposed": true,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": false,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false,
- "dismissed": "T"
- }
- },
- "enotice": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "[{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"08/26/2019\",\"sentDateString\":\"08/26/2019 05:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"08/19/2019\",\"sentDateString\":\"08/19/2019 08:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"08/19/2019\",\"sentDateString\":\"08/19/2019 08:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"08/19/2019\",\"sentDateString\":\"08/19/2019 08:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"08/19/2019\",\"sentDateString\":\"08/19/2019 08:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"08/07/2019\",\"sentDateString\":\"08/07/2019 02:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"07/24/2019\",\"sentDateString\":\"07/24/2019 12:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"07/11/2019\",\"sentDateString\":\"07/11/2019 07:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"07/11/2019\",\"sentDateString\":\"07/11/2019 07:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/28/2019\",\"sentDateString\":\"06/28/2019 05:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/25/2019\",\"sentDateString\":\"06/25/2019 07:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/25/2019\",\"sentDateString\":\"06/25/2019 11:02 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/24/2019\",\"sentDateString\":\"06/24/2019 06:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/21/2019\",\"sentDateString\":\"06/21/2019 05:03 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/13/2019\",\"sentDateString\":\"06/13/2019 05:02 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/13/2019\",\"sentDateString\":\"06/13/2019 05:02 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/13/2019\",\"sentDateString\":\"06/13/2019 05:02 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"06/13/2019\",\"sentDateString\":\"06/13/2019 05:02 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/31/2019\",\"sentDateString\":\"05/31/2019 04:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/31/2019\",\"sentDateString\":\"05/31/2019 04:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/31/2019\",\"sentDateString\":\"05/31/2019 04:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/31/2019\",\"sentDateString\":\"05/31/2019 04:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/28/2019\",\"sentDateString\":\"05/28/2019 01:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/28/2019\",\"sentDateString\":\"05/28/2019 01:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/28/2019\",\"sentDateString\":\"05/28/2019 01:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/28/2019\",\"sentDateString\":\"05/28/2019 01:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/28/2019\",\"sentDateString\":\"05/28/2019 01:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/28/2019\",\"sentDateString\":\"05/28/2019 01:48 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/23/2019\",\"sentDateString\":\"05/23/2019 12:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/23/2019\",\"sentDateString\":\"05/23/2019 12:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/20/2019\",\"sentDateString\":\"05/20/2019 06:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/15/2019\",\"sentDateString\":\"05/15/2019 12:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/15/2019\",\"sentDateString\":\"05/15/2019 12:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/15/2019\",\"sentDateString\":\"05/15/2019 12:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/13/2019\",\"sentDateString\":\"05/13/2019 12:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/09/2019\",\"sentDateString\":\"05/09/2019 07:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/09/2019\",\"sentDateString\":\"05/09/2019 07:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/09/2019\",\"sentDateString\":\"05/09/2019 07:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/07/2019\",\"sentDateString\":\"05/07/2019 12:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/07/2019\",\"sentDateString\":\"05/07/2019 12:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/06/2019\",\"sentDateString\":\"05/06/2019 12:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/06/2019\",\"sentDateString\":\"05/06/2019 12:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/03/2019\",\"sentDateString\":\"05/03/2019 01:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/02/2019\",\"sentDateString\":\"05/02/2019 04:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/02/2019\",\"sentDateString\":\"05/02/2019 04:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/01/2019\",\"sentDateString\":\"05/01/2019 05:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/01/2019\",\"sentDateString\":\"05/01/2019 05:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/01/2019\",\"sentDateString\":\"05/01/2019 01:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/01/2019\",\"sentDateString\":\"05/01/2019 01:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"05/01/2019\",\"sentDateString\":\"05/01/2019 01:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/30/2019\",\"sentDateString\":\"04/30/2019 07:32 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/23/2019\",\"sentDateString\":\"04/23/2019 01:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/23/2019\",\"sentDateString\":\"04/23/2019 01:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/23/2019\",\"sentDateString\":\"04/23/2019 01:17 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/12/2019\",\"sentDateString\":\"04/12/2019 04:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/12/2019\",\"sentDateString\":\"04/12/2019 04:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/10/2019\",\"sentDateString\":\"04/10/2019 11:47 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"04/08/2019\",\"sentDateString\":\"04/08/2019 02:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/27/2019\",\"sentDateString\":\"03/27/2019 11:47 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/27/2019\",\"sentDateString\":\"03/27/2019 11:47 AM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/22/2019\",\"sentDateString\":\"03/22/2019 01:47 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/19/2019\",\"sentDateString\":\"03/19/2019 12:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/19/2019\",\"sentDateString\":\"03/19/2019 12:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/19/2019\",\"sentDateString\":\"03/19/2019 12:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"54784\",\"firstName\":\"Diane\",\"lastName\":\"Peters\",\"fullName\":\"Diane Peters\",\"sentDate\":\"03/19/2019\",\"sentDateString\":\"03/19/2019 12:02 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false}]",
- "parsed": [
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "08/26/2019",
- "sentDateString": "08/26/2019 05:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "08/19/2019",
- "sentDateString": "08/19/2019 08:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "08/19/2019",
- "sentDateString": "08/19/2019 08:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "08/19/2019",
- "sentDateString": "08/19/2019 08:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "08/19/2019",
- "sentDateString": "08/19/2019 08:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "08/07/2019",
- "sentDateString": "08/07/2019 02:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "07/24/2019",
- "sentDateString": "07/24/2019 12:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "07/11/2019",
- "sentDateString": "07/11/2019 07:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "07/11/2019",
- "sentDateString": "07/11/2019 07:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/28/2019",
- "sentDateString": "06/28/2019 05:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/25/2019",
- "sentDateString": "06/25/2019 07:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/25/2019",
- "sentDateString": "06/25/2019 11:02 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/24/2019",
- "sentDateString": "06/24/2019 06:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/21/2019",
- "sentDateString": "06/21/2019 05:03 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/13/2019",
- "sentDateString": "06/13/2019 05:02 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/13/2019",
- "sentDateString": "06/13/2019 05:02 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/13/2019",
- "sentDateString": "06/13/2019 05:02 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "06/13/2019",
- "sentDateString": "06/13/2019 05:02 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/31/2019",
- "sentDateString": "05/31/2019 04:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/31/2019",
- "sentDateString": "05/31/2019 04:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/31/2019",
- "sentDateString": "05/31/2019 04:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/31/2019",
- "sentDateString": "05/31/2019 04:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/28/2019",
- "sentDateString": "05/28/2019 01:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/28/2019",
- "sentDateString": "05/28/2019 01:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/28/2019",
- "sentDateString": "05/28/2019 01:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/28/2019",
- "sentDateString": "05/28/2019 01:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/28/2019",
- "sentDateString": "05/28/2019 01:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/28/2019",
- "sentDateString": "05/28/2019 01:48 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/23/2019",
- "sentDateString": "05/23/2019 12:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/23/2019",
- "sentDateString": "05/23/2019 12:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/20/2019",
- "sentDateString": "05/20/2019 06:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/15/2019",
- "sentDateString": "05/15/2019 12:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/15/2019",
- "sentDateString": "05/15/2019 12:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/15/2019",
- "sentDateString": "05/15/2019 12:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/13/2019",
- "sentDateString": "05/13/2019 12:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/09/2019",
- "sentDateString": "05/09/2019 07:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/09/2019",
- "sentDateString": "05/09/2019 07:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/09/2019",
- "sentDateString": "05/09/2019 07:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/07/2019",
- "sentDateString": "05/07/2019 12:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/07/2019",
- "sentDateString": "05/07/2019 12:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/06/2019",
- "sentDateString": "05/06/2019 12:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/06/2019",
- "sentDateString": "05/06/2019 12:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/03/2019",
- "sentDateString": "05/03/2019 01:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/02/2019",
- "sentDateString": "05/02/2019 04:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/02/2019",
- "sentDateString": "05/02/2019 04:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/01/2019",
- "sentDateString": "05/01/2019 05:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/01/2019",
- "sentDateString": "05/01/2019 05:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/01/2019",
- "sentDateString": "05/01/2019 01:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/01/2019",
- "sentDateString": "05/01/2019 01:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "05/01/2019",
- "sentDateString": "05/01/2019 01:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/30/2019",
- "sentDateString": "04/30/2019 07:32 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/23/2019",
- "sentDateString": "04/23/2019 01:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/23/2019",
- "sentDateString": "04/23/2019 01:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/23/2019",
- "sentDateString": "04/23/2019 01:17 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/12/2019",
- "sentDateString": "04/12/2019 04:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/12/2019",
- "sentDateString": "04/12/2019 04:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/10/2019",
- "sentDateString": "04/10/2019 11:47 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "04/08/2019",
- "sentDateString": "04/08/2019 02:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/27/2019",
- "sentDateString": "03/27/2019 11:47 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/27/2019",
- "sentDateString": "03/27/2019 11:47 AM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/22/2019",
- "sentDateString": "03/22/2019 01:47 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/19/2019",
- "sentDateString": "03/19/2019 12:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/19/2019",
- "sentDateString": "03/19/2019 12:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/19/2019",
- "sentDateString": "03/19/2019 12:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "54784",
- "firstName": "Diane",
- "lastName": "Peters",
- "fullName": "Diane Peters",
- "sentDate": "03/19/2019",
- "sentDateString": "03/19/2019 12:02 PM",
- "email": "[email protected]",
- "hasEnotice": false
- }
- ]
- }
-}
\ No newline at end of file
diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
index 437a0873f..06fed9795 100644
--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
@@ -71,6 +71,12 @@
</provides>
<releases>
+ <release version="4.4.0" date="2026-08-11">
+ <description>
+ <p>Correctness and safety release. A failed fetch, an unreadable setting or an incomplete option chain now reports an error instead of rendering as a confident number — missing financials show "no data" rather than a solvency verdict, and a quote served from stale cache is marked stale. Risk limits, per-broker order rate limits and the smart/basket order validators are enforced rather than merely configurable.</p>
+ <p>Destructive AI tools are disabled by default and enabled under Settings &gt; Security; live order tools require explicit confirmation. Broker credentials no longer travel on the command line, and the update manifest is verified against a pinned signing key.</p>
+ </description>
+ </release>
<release version="4.3.0" date="2026-07-25">
<description>
<p>MCP long-running tools now run as background jobs the assistant can poll, cancel, and watch progress on, instead of blocking a request for minutes. Oversized tool results are summarised and paged on demand rather than filling the conversation.</p>
diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
index 5b1daf017..3a8b569b1 100644
--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
@@ -55,7 +55,7 @@ modules:
# Main repository
- type: git
url: https://github.com/Fincept-Corporation/FinceptTerminal.git
- tag: v4.3.0
+ tag: v4.4.0
# Vendored FetchContent dependencies (no network during build)
- type: git
url: https://github.com/QtExcel/QXlsx.git
diff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
index 67ee7d7ff..c1a4477e8 100644
--- a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt
@@ -17,98 +17,106 @@ You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
================================================================================
- DUAL LICENSING NOTICE
+ LICENSING NOTICE
================================================================================
-Fincept Terminal is dual-licensed. Every user must comply with ONE of the
-following licenses:
-
-1. AGPL-3.0 (Open Source)
- - Free for personal use, individual learning, academic research by
- individual students, and open-source contribution to this repository.
- - Requires sharing modifications if distributed or made available as a
- network service.
- - Full text: https://www.gnu.org/licenses/agpl-3.0.html
-
-2. Fincept Commercial License
- - REQUIRED for any business or internal company use, regardless of
- revenue, size, or duration.
- - Required for SaaS, cloud, hosted, white-label, or resale offerings.
- - Required for forks that remove or replace Fincept's APIs, data
- sources, or service endpoints, where used commercially or internally.
- - See: docs/COMMERCIAL_LICENSE.md
-
-The AGPL-3.0 option is NOT available for Commercial Use as defined in
-docs/COMMERCIAL_LICENSE.md, Section 3. Commercial Use without an executed
-Commercial License is a breach of copyright and is subject to the full
-range of remedies set forth in docs/COMMERCIAL_LICENSE.md.
+This software — Fincept Terminal, open-source edition — is licensed under
+AGPL-3.0-or-later, and under no other licence.
-================================================================================
- CLONING / FORKING / MODIFICATION DOES NOT GRANT
- COMMERCIAL OR INTERNAL-USE RIGHTS
-================================================================================
+Fincept Corporation does NOT sell a separate commercial, enterprise, or
+academic licence for this software. The previous dual-licensing arrangement
+(Commercial License v2.0, April 30 2026) is withdrawn in full.
+
+Full text: https://www.gnu.org/licenses/agpl-3.0.html
+Details: docs/COMMERCIAL_LICENSE.md
+
+--------------------------------------------------------------------------------
+WHAT AGPL-3.0 MEANS IN PRACTICE
+
+AGPL-3.0 is strong copyleft, not a permissive licence.
-Cloning, forking, downloading, building, or modifying this repository does
-NOT grant any right to use Fincept Terminal — or any Modified Version or
-Derivative Work — for Commercial Use. Internal use within any for-profit
-organization, government body, fund, or revenue-generating non-profit is
-Commercial Use and requires a paid Commercial License.
+ * Running this software on your own machine, modified or not, without
+ distributing it — no obligations at all.
-The license attaches to the codebase and any Derivative Work of it, not to
-specific API integrations. Removing, replacing, disabling, or rewiring
-Fincept's APIs, data sources, or service endpoints does NOT sever or
-extinguish the licensing obligation.
+ * Distributing a build, internally or externally, modified or not — you
+ must provide the complete corresponding source of your version under
+ AGPL-3.0.
+
+ * Running a modified version as a network service that other people reach
+ — you must provide the complete corresponding source of your version to
+ those users, under AGPL-3.0 (AGPL section 13).
+
+ * Linking or building it into another product you ship — that product is
+ a derivative work and falls under AGPL-3.0.
+
+Removing, replacing, or rewiring Fincept's APIs and data integrations does
+not change any of the above. The obligation attaches to the codebase, not
+to the data sources.
+
+There is no paid exemption from these terms.
================================================================================
- FINCEPT DATA & API SERVICES
+ FINCEPT TERMINAL ENTERPRISE (SEPARATE PRODUCT)
================================================================================
-The Fincept Terminal software is offered under AGPL-3.0 for non-commercial
-use as described above.
+If AGPL-3.0 does not work for your organisation, the answer is Fincept
+Terminal Enterprise — a separate, closed-source product that is NOT this
+codebase, is not published as open source, and carries no copyleft
+obligations to manage.
+
+ Exclusive USD 99 / user / month
+ Exclusive+ USD 199 / user / month
+ Exclusive Pro USD 299 / user / month
+ Academic bundle - 5 Exclusive Pro seats USD 699 / month
-Fincept Data Sources and APIs are separate services subject to:
-- Commercial License: USD 10,200 / year
-- University & Academic License: USD 799 / month (20 accounts)
-- Free for individual personal and educational use only
+Monthly billing, no annual lock-in, no seat minimum, 15% off on quarterly.
+These are the only prices offered. There is no custom, negotiated, or
+enterprise-tier pricing, and no bespoke licensing track.
+
+ Overview: https://fincept.in/enterprise
+ Pricing: https://fincept.in/pricing
+ Comparison: https://fincept.in/comparison
+ Sign up: https://fincept.in/enterprise/signup
+ Universities: [email protected]
+
+Enterprise runs on a separate backend with separate user records. A free
+Fincept account does not sign in to it.
================================================================================
TRADEMARK NOTICE
================================================================================
"Fincept", "Fincept Terminal", "Fincept Corporation", and the Fincept logo
-are trademarks of Fincept Corporation. All rights reserved.
+are trademarks of Fincept Corporation. All rights reserved. Trademark
+rights are NOT granted by AGPL-3.0 and are expressly reserved.
You may not use these marks — or any colorable imitation, transliteration,
abbreviation, translation, or variation or derivative thereof — without
prior written permission from Fincept Corporation, except as strictly
necessary to comply with AGPL-3.0 attribution requirements.
-Removal, replacement, or rebranding of these marks in any fork or
-Derivative Work does NOT extinguish Fincept Corporation's rights in the
-underlying Software, nor does it sever the licensing obligations attaching
-to the codebase.
-
The Fincept Trade Dress — including screen layouts, color palette,
terminal command syntax, ticker conventions, function-code conventions,
keyboard shortcut conventions, dashboard widget vocabulary, and overall
visual identity of Fincept Terminal — is also protected. Substantially
similar replication, even with branding removed, is prohibited.
-Use of the trademarks or trade dress to promote derivative works or
-competing products is strictly prohibited.
+AGPL-3.0 section 7(e) permits the licensor to require removal of licensor
+trademarks from modified versions; Fincept Corporation exercises that
+right. Rebrand your fork.
+
+Removing or replacing the marks in a fork does not affect the AGPL-3.0
+obligations attaching to the code.
================================================================================
- ADDITIONAL RESTRICTIONS
+ CONDITIONS OF USE
================================================================================
-While AGPL-3.0 grants broad freedoms for non-commercial use, the following
-additional restrictions apply to all users of this Software:
-
-1. NETWORK USE REQUIREMENT (AGPL § 13)
+1. NETWORK USE REQUIREMENT (AGPL section 13)
If you run a modified version as a network service (SaaS, cloud
platform, web application), you MUST:
- - Provide users with access to the complete source code
- - Clearly indicate the source is available
+ - Provide users with access to the complete corresponding source code
+ - Clearly indicate that the source is available
- Make the source available via download or repository access
2. ATTRIBUTION REQUIREMENT
@@ -121,17 +129,14 @@ additional restrictions apply to all users of this Software:
- Must clearly differentiate Derivative Works from the official version
- Cannot replicate Fincept Trade Dress
-4. COMMERCIAL & INTERNAL-USE RESTRICTION
- - Commercial Use of any kind requires a Commercial License
- - Internal corporate use is Commercial Use, regardless of whether the
- Software is exposed to third parties
- - Forks that strip or replace Fincept APIs are still subject to the
- Commercial License requirement
-
================================================================================
CONTRIBUTOR LICENSE AGREEMENT (CLA)
================================================================================
+This section applies only to people who contribute code or content to the
+Fincept Terminal repository. It does not apply to ordinary use of this
+software.
+
By contributing to Fincept Terminal (via pull request, patch, comment,
issue, or any other means), each contributor agrees to the following terms:
@@ -145,15 +150,16 @@ issue, or any other means), each contributor agrees to the following terms:
Fincept Corporation a perpetual, worldwide, non-exclusive, royalty-free,
irrevocable, sublicensable license — with the right to sublicense
through multiple tiers — to use, reproduce, modify, distribute,
- sublicense, and relicense the contribution under AGPL-3.0, the Fincept
- Commercial License, and any future license selected by Fincept
- Corporation.
+ sublicense, and relicense the contribution under AGPL-3.0, under the
+ proprietary licence of Fincept Terminal Enterprise, and under any future
+ licence selected by Fincept Corporation.
2. NO JOINT AUTHORSHIP. Each contributor expressly disclaims any claim of
joint authorship in the Software as a whole or in any other
contributor's contributions. Contributing does NOT grant the contributor
- any license to the Software as a whole, to any other contributor's
- contributions, or to Commercial Use of the Software.
+ any license to the Software as a whole or to any other contributor's
+ contributions beyond the AGPL-3.0 licence under which the Software is
+ published.
3. WARRANTY AND INDEMNITY. Each contributor warrants that (a) the
contribution is the contributor's original work or is properly attributed
@@ -168,85 +174,22 @@ issue, or any other means), each contributor agrees to the following terms:
4. AS-IS. Contributions are provided "AS IS" without warranties of any
kind beyond the warranties in Section 3 above.
-5. NO COMMERCIAL RIGHTS BACK. Contributing does NOT grant the contributor
- Commercial Use rights, license-back rights, or access to Fincept Data
- Sources or APIs for commercial purposes.
+5. NO ENTERPRISE RIGHTS BACK. Contributing does NOT grant the contributor
+ a seat in, or any licence to, Fincept Terminal Enterprise, nor access to
+ Fincept's private datasets or paid API tiers.
================================================================================
- WHEN A COMMERCIAL LICENSE IS REQUIRED
+ WARRANTY AND FINANCIAL DISCLAIMER
================================================================================
-You NEED a Commercial License if you:
-- Use Fincept Terminal for any business purpose, paid or free
-- Use Fincept Terminal internally at a company, fund, or for-profit entity
- (regardless of whether it is exposed to third parties)
-- Are a startup at any stage, including pre-revenue and pre-product
-- Are a hedge fund, prop firm, bank, brokerage, asset manager, family
- office, fintech, or exchange
-- Offer Fincept Terminal as SaaS, PaaS, or any hosted service
-- White-label, rebrand, distribute, or resell Fincept Terminal
-- Maintain or operate a fork that strips or replaces Fincept APIs and use
- it commercially or internally
-- Engage a third-party developer, integrator, or consultancy to build,
- modify, deploy, host, or customize Fincept Terminal for any of the above
-
-You do NOT need a Commercial License if you:
-- Use Fincept Terminal for personal learning on your own machine
-- Are an individual student conducting non-commercial research
-- Are contributing to the open-source project
-
-When in doubt, assume a Commercial License is required and email
-
-================================================================================
- ENFORCEMENT, PENALTIES & LIABILITY
-================================================================================
+This software is provided "AS IS", without warranty of any kind, express
+or implied, as set out in AGPL-3.0 sections 15 and 16.
-Fincept Corporation actively monitors public code repositories, container
-registries, application stores, cloud marketplaces, SaaS platforms, and
-trademark registers for unlicensed Commercial Use of Fincept Terminal,
-Modified Versions, and Derivative Works.
-
-Unauthorized Commercial Use is subject to liquidated damages, including
-(without limitation):
-
- * USD 50,000 per organization per year for unauthorized internal
- corporate use (or 5x the then-current Commercial License fee,
- whichever is greater)
- * USD 250,000 per offering for unauthorized SaaS, hosting, or resale,
- plus full disgorgement of revenue
- * USD 100,000 per organization for unauthorized fork-and-replace-API
- deployments, plus 5x the Commercial License fee for each year of use
- * USD 150,000 per element for unauthorized use of Fincept Marks or
- Fincept Trade Dress
- * USD 10,000 per day for continued use after notice of breach
-
-In addition, Fincept Corporation will pursue:
-- Backdated license fees from the date of first unauthorized use, with
- 18% annual interest
-- Disgorgement of all profits, revenue, and cost savings derived from
- unauthorized use
-- DMCA takedowns (17 U.S.C. § 512), notices under the Information
- Technology Act, 2000 (India), and equivalent foreign statutes
-- Cease-and-desist letters and civil action for copyright and trademark
- infringement
-- Criminal complaints under the Copyright Act, 1957 (India) §§ 63-63B
- and equivalent foreign laws
-- All attorneys' fees, court costs, expert fees, and investigation costs
-
-JOINT AND SEVERAL LIABILITY. Any organization that engages, hires, or
-contracts with a third-party developer, integrator, IT consultancy,
-outsourcing vendor, freelancer, or offshore development center to build,
-modify, deploy, fork, host, or customize Fincept Terminal or any
-Derivative Work shall be JOINTLY AND SEVERALLY LIABLE with that third
-party for any unauthorized Commercial Use, breach of license, or
-infringement. The contracting company cannot escape liability by claiming
-that the developer was solely responsible. Liability extends to parents,
-subsidiaries, affiliates, successors, joint-venture partners, and
-acquirers. The duty to verify license compliance is non-delegable.
-
-Full enforcement, penalty, and joint-and-several liability terms are set
-forth in docs/COMMERCIAL_LICENSE.md, Sections 12, 13, and 14.
+Nothing in this software, and no output generated by it, constitutes
+investment, legal, tax, accounting, or financial advice. It is not
+warranted for any use where failure could cause financial loss or
+regulatory breach. Trading and investment involve risk of loss. You are
+solely responsible for any decision taken using this software.
================================================================================
GOVERNING LAW & JURISDICTION
@@ -264,27 +207,24 @@ worldwide to protect its intellectual property.
================================================================================
-Phone: +91-9773034108
Website: https://fincept.in
+Enterprise: https://fincept.in/enterprise
Repository: https://github.com/Fincept-Corporation/FinceptTerminal
Documentation: https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs
-Commercial: docs/COMMERCIAL_LICENSE.md
+Licensing: docs/COMMERCIAL_LICENSE.md
================================================================================
-Document Version: 2.0
-In Force From: April 30, 2026
-Status: Current and binding. These terms remain in full force and
- effect indefinitely until expressly superseded by a
+Document Version: 3.0
+In Force From: August 11, 2026
+Supersedes: Document Version 2.0 (April 30, 2026), withdrawn in full,
+ including its dual-licensing requirement, commercial and
+ academic licence fees, audit obligations, liquidated-damages
+ schedule, and joint-and-several liability provisions. Those
+ terms are not asserted against any user of this software.
+Status: Current. Remains in force until expressly superseded by a
subsequent version published by Fincept Corporation. The
date above marks the most recent revision and is NOT an
expiry date.
-Software Version: 4.3.0 (current release; license applies to all releases,
- branches, tags, and commits of the Software)
-
-This License governs all current and future use of the Software, including
-use of historical versions, regardless of when those versions were
-originally published. Any commercial or internal-corporate use of any
-version of Fincept Terminal — past, present, or future — is subject to
-the terms of this License and the accompanying Commercial License at
-docs/COMMERCIAL_LICENSE.md.
+Software Version: 4.4.0 (licence applies to all releases, branches, tags,
+ and commits of the open-source edition)
diff --git a/fincept-qt/packaging/linux/AppImageBuilder.yml b/fincept-qt/packaging/linux/AppImageBuilder.yml
index 4e1e09c47..01acfb1dd 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.3.0}
+ version: !ENV ${FINCEPT_VERSION:-4.4.0}
exec: usr/bin/FinceptTerminal
exec_args: $@
@@ -56,6 +56,6 @@ AppDir:
AppImage:
arch: x86_64
comp: xz
- file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.3.0}-x86_64.AppImage
+ file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.4.0}-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/packaging/linux/fincept-terminal.appdata.xml b/fincept-qt/packaging/linux/fincept-terminal.appdata.xml
index 3e8d30108..daa3fd1c3 100644
--- a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml
+++ b/fincept-qt/packaging/linux/fincept-terminal.appdata.xml
@@ -28,6 +28,11 @@
<binary>FinceptTerminal</binary>
</provides>
<releases>
+ <release version="4.4.0" date="2026-08-11">
+ <description>
+ <p>Version 4.4.0 — Correctness and safety release. Failed data fetches, unreadable settings and incomplete option chains now report an error instead of rendering as confident numbers. Risk limits, order rate limits and the smart/basket order validators are enforced rather than merely configurable. Destructive AI tools are off by default (Settings &gt; Security), live orders require explicit confirmation, and the update manifest is signature-verified.</p>
+ </description>
+ </release>
<release version="4.3.0" date="2026-07-25">
<description>
<p>Version 4.3.0 — MCP long-running tools now run as background jobs the assistant can poll and cancel, and oversized tool results are paged on demand instead of filling the conversation.</p>
diff --git a/fincept-qt/resources/requirements-numpy2.txt b/fincept-qt/resources/requirements-numpy2.txt
index 33a734671..34ffb6aa4 100644
--- a/fincept-qt/resources/requirements-numpy2.txt
+++ b/fincept-qt/resources/requirements-numpy2.txt
@@ -12,7 +12,7 @@ pandas>=2.3.3,<3.0
vnpy==4.3.0
# Data fetching
-ccxt>=4.5.44
+ccxt>=4.5.44,<5.0
requests==2.32.5
aiohttp==3.13.2
websockets==15.0.1
@@ -75,7 +75,10 @@ tiktoken>=0.5.0
# Note: litellm removed - model data extracted to llm_models_data.json (240KB static file)
# Agno AI Framework
-agno>=1.0.0
+# Upper bound: agno 1.x → 2.x rewrote the Agent/Team API. `>=1.0.0` alone
+# already silently resolved to 2.x (venv has 2.6.7), i.e. the lower bound is
+# stale and a 3.0 would break the same way. Cap it.
+agno>=1.0.0,<3.0
# Ollama client — required by agno.models.ollama.Ollama and the Ollama embedder.
# Without it, selecting the Ollama provider for an agent raises
@@ -109,7 +112,11 @@ river>=0.21.0
ta==0.11.0
# Portfolio optimization
-finquant-enhanced
+# finquant-enhanced was the ONLY requirement in either file with no version
+# specifier at all — `uv` would install whatever the index served, which makes
+# it the single best target for a compromised/typosquatted release. Pinned to
+# the version currently resolved in venv-numpy2.
+finquant-enhanced==0.7.1
cvxpy>=1.0.0
cvxopt==1.3.2
@@ -156,7 +163,7 @@ ruamel.yaml>=0.17.38,<0.18.0
python-redis-lock>=4.0.0
setuptools-scm>=8.0.0
tables>=3.8.0
-selenium>=4.0.0
+selenium>=4.0.0,<5.0
pyarrow>=16.0.0
pandarallel>=1.6.0
gymnasium>=1.0.0
@@ -165,7 +172,9 @@ gymnasium>=1.0.0
stable-baselines3>=2.7.0
# MLflow
-mlflow>=2.0.0
+# `>=2.0.0` already resolved to 3.x (venv has 3.12.0) across MLflow's breaking
+# 2→3 model/tracing API change. Cap below 4.0.
+mlflow>=2.0.0,<4.0
# VisionQuant Pattern Intelligence
faiss-cpu>=1.7.0
diff --git a/fincept-qt/sc97597.json b/fincept-qt/sc97597.json
deleted file mode 100644
index 3642ce83f..000000000
--- a/fincept-qt/sc97597.json
+++ /dev/null
@@ -1,518 +0,0 @@
-{
- "header": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"courtId\":\"OSCDB0024_SUP\",\"caseNumber\":\"SC97597\",\"caseDesc\":\"TOMAS CAESAR POPSON,APP V DAVID CORRION,ETAL,RES\",\"courtDesc\":\"Supreme Court\",\"location\":\"SUPREME COURT OF MISSOURI\",\"filingDate\":\"12/17/2018\",\"formattedFilingDate\":\"12/17/2018\",\"predCode\":\"ZD\",\"protectionOrder\":false,\"caseType\":\"AP Tran to SC- Post Opinion\",\"caseSecurity\":\"1\",\"caseTypeCode\":\"AY\",\"locnCode\":\"SC\",\"courtCode\":\"SC\",\"vineDisplay\":\"N\",\"vineID\":\"SC97597\",\"caseDispositionDetail\":{\"dispositionDescription\":\"Disp-App Tran to SC Denied\",\"docketFilingDate\":\"03/05/2019\",\"formattedDocketFilingDate\":\"03/05/2019\",\"docketTime\":\"13:00:00\",\"isLastSentenceSIS\":\"N\"},\"caseChargeList\":[],\"appellateOriginNo\":{\"siteCode\":\"OCASE\",\"caseValue\":\"JACKSON COUNTY CIRCUIT COURT NO. 1716-CV18338; WD82191\"},\"appellateCaseNo\":{\"siteCode\":\"XCASE\",\"caseValue\":\"WD82191\",\"courtId\":\"SMPDB0001_WAP\"},\"circuitCaseNo\":[],\"courtType\":\"A\",\"disposed\":true,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":false,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false,\"dismissed\":\"F\",\"fileId\":\"\",\"isTrafficOrCriminal\":\"n\"}",
- "parsed": {
- "courtId": "OSCDB0024_SUP",
- "caseNumber": "SC97597",
- "caseDesc": "TOMAS CAESAR POPSON,APP V DAVID CORRION,ETAL,RES",
- "courtDesc": "Supreme Court",
- "location": "SUPREME COURT OF MISSOURI",
- "filingDate": "12/17/2018",
- "formattedFilingDate": "12/17/2018",
- "predCode": "ZD",
- "protectionOrder": false,
- "caseType": "AP Tran to SC- Post Opinion",
- "caseSecurity": "1",
- "caseTypeCode": "AY",
- "locnCode": "SC",
- "courtCode": "SC",
- "vineDisplay": "N",
- "vineID": "SC97597",
- "caseDispositionDetail": {
- "dispositionDescription": "Disp-App Tran to SC Denied",
- "docketFilingDate": "03/05/2019",
- "formattedDocketFilingDate": "03/05/2019",
- "docketTime": "13:00:00",
- "isLastSentenceSIS": "N"
- },
- "caseChargeList": [],
- "appellateOriginNo": {
- "siteCode": "OCASE",
- "caseValue": "JACKSON COUNTY CIRCUIT COURT NO. 1716-CV18338; WD82191"
- },
- "appellateCaseNo": {
- "siteCode": "XCASE",
- "caseValue": "WD82191",
- "courtId": "SMPDB0001_WAP"
- },
- "circuitCaseNo": [],
- "courtType": "A",
- "disposed": true,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": false,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false,
- "dismissed": "F",
- "fileId": "",
- "isTrafficOrCriminal": "n"
- }
- },
- "party": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"caseNumber\":\"SC97597\",\"protectionOrder\":false,\"locnCode\":\"SC\",\"courtCode\":\"SC\",\"partyDetailsList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":3,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Appellant Acting Pro Se\",\"descCode\":\"APLP\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"5400 JOHNSON DR., SUITE 173\\nMISSION, KS 66205\",\"formattedPartyName\":\"POPSON, TOMAS CAESAR\",\"formattedTelePhone\":\"\",\"lcatCode\":\"L\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":2,\"sortSeq\":0},{\"addrSeqNo\":0,\"assoc\":5,\"attorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":3,\"assoc\":5,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Co-Counsel for Respondent\",\"descCode\":\"CRES\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"2300 MAIN STREET\\nSUITE 900\\nKANSAS CITY, MO 64108\",\"formattedPartyName\":\"BOND, LANCE LAMONT\",\"formattedTelePhone\":\"(816) 787-5532\",\"partyType\":\"co-attorney\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":6,\"sortSeq\":9}],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Attorney for Respondent\",\"descCode\":\"ARES\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"4806 LIBERTY ST \\nKANSAS CITY, MO 64112\",\"formattedPartyName\":\"DEEKEN, JEREMY JOSEPH\",\"formattedTelePhone\":\"\",\"partyType\":\"attorney\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":5,\"sortSeq\":9}],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Respondent\",\"descCode\":\"RES\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"\",\"formattedPartyName\":\"CORRION, DAVID\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":3,\"sortSeq\":4},{\"addrSeqNo\":0,\"assoc\":5,\"attorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":1,\"assoc\":0,\"attorneyList\":[],\"coAttorneyList\":[{\"addrAtyp\":\"MA\",\"addrSeqNo\":3,\"assoc\":5,\"attorneyList\":[],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Co-Counsel for Respondent\",\"descCode\":\"CRES\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"2300 MAIN STREET\\nSUITE 900\\nKANSAS CITY, MO 64108\",\"formattedPartyName\":\"BOND, LANCE LAMONT\",\"formattedTelePhone\":\"(816) 787-5532\",\"partyType\":\"co-attorney\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":6,\"sortSeq\":9}],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Attorney for Respondent\",\"descCode\":\"ARES\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"4806 LIBERTY ST \\nKANSAS CITY, MO 64112\",\"formattedPartyName\":\"DEEKEN, JEREMY JOSEPH\",\"formattedTelePhone\":\"\",\"partyType\":\"attorney\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":5,\"sortSeq\":9}],\"coAttorneyList\":[],\"otherAttorneyList\":[],\"criminalCase\":false,\"criminalInd\":\"N\",\"desc\":\"Respondent\",\"descCode\":\"RES\",\"startDate\":\"12/17/2018\",\"formattedPartyAddress\":\"\",\"formattedPartyName\":\"MARTINEZ, ROXANA\",\"formattedTelePhone\":\"\",\"litInd\":\"Y\",\"partyType\":\"party\",\"pidm\":0,\"predCode\":\"ZD\",\"prosecutingAtty\":false,\"ptySeqNo\":4,\"sortSeq\":4}],\"disposed\":false,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":false,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false}",
- "parsed": {
- "caseNumber": "SC97597",
- "protectionOrder": false,
- "locnCode": "SC",
- "courtCode": "SC",
- "partyDetailsList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 3,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Appellant Acting Pro Se",
- "descCode": "APLP",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "5400 JOHNSON DR., SUITE 173\nMISSION, KS 66205",
- "formattedPartyName": "POPSON, TOMAS CAESAR",
- "formattedTelePhone": "",
- "lcatCode": "L",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 2,
- "sortSeq": 0
- },
- {
- "addrSeqNo": 0,
- "assoc": 5,
- "attorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 3,
- "assoc": 5,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Co-Counsel for Respondent",
- "descCode": "CRES",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "2300 MAIN STREET\nSUITE 900\nKANSAS CITY, MO 64108",
- "formattedPartyName": "BOND, LANCE LAMONT",
- "formattedTelePhone": "(816) 787-5532",
- "partyType": "co-attorney",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 6,
- "sortSeq": 9
- }
- ],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Attorney for Respondent",
- "descCode": "ARES",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "4806 LIBERTY ST \nKANSAS CITY, MO 64112",
- "formattedPartyName": "DEEKEN, JEREMY JOSEPH",
- "formattedTelePhone": "",
- "partyType": "attorney",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 5,
- "sortSeq": 9
- }
- ],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Respondent",
- "descCode": "RES",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "",
- "formattedPartyName": "CORRION, DAVID",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 3,
- "sortSeq": 4
- },
- {
- "addrSeqNo": 0,
- "assoc": 5,
- "attorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 1,
- "assoc": 0,
- "attorneyList": [],
- "coAttorneyList": [
- {
- "addrAtyp": "MA",
- "addrSeqNo": 3,
- "assoc": 5,
- "attorneyList": [],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Co-Counsel for Respondent",
- "descCode": "CRES",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "2300 MAIN STREET\nSUITE 900\nKANSAS CITY, MO 64108",
- "formattedPartyName": "BOND, LANCE LAMONT",
- "formattedTelePhone": "(816) 787-5532",
- "partyType": "co-attorney",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 6,
- "sortSeq": 9
- }
- ],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Attorney for Respondent",
- "descCode": "ARES",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "4806 LIBERTY ST \nKANSAS CITY, MO 64112",
- "formattedPartyName": "DEEKEN, JEREMY JOSEPH",
- "formattedTelePhone": "",
- "partyType": "attorney",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 5,
- "sortSeq": 9
- }
- ],
- "coAttorneyList": [],
- "otherAttorneyList": [],
- "criminalCase": false,
- "criminalInd": "N",
- "desc": "Respondent",
- "descCode": "RES",
- "startDate": "12/17/2018",
- "formattedPartyAddress": "",
- "formattedPartyName": "MARTINEZ, ROXANA",
- "formattedTelePhone": "",
- "litInd": "Y",
- "partyType": "party",
- "pidm": 0,
- "predCode": "ZD",
- "prosecutingAtty": false,
- "ptySeqNo": 4,
- "sortSeq": 4
- }
- ],
- "disposed": false,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": false,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false
- }
- },
- "docket": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"caseNumber\":\"SC97597\",\"protectionOrder\":false,\"locnCode\":\"SC\",\"courtCode\":\"SC\",\"docketTabModelList\":[{\"whichone\":4,\"filingDate\":\"03/05/2019\",\"docketDesc\":\"Disp-App Tran to SC Denied\",\"predCode\":\"ZEDTR\",\"sequenceNumber\":4,\"docketText\":\"MANDATE SENT TO CLERK OF THE MISSOURI COURT OF APPEALS VIA E-MAIL, TO APPELLANT VIA REGULAR MAIL, AND TO ALL COUNSEL OF RECORD VIA THE MISSOURI EFILING SYSTEM.\",\"filingPartyFullName\":\"\",\"docketCode\":\"EZATD\",\"dtypPredCode\":\"ZD\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":3,\"filingDate\":\"12/17/2018\",\"docketDesc\":\"Filing Fee Paid\",\"predCode\":\"ZEPRF\",\"sequenceNumber\":3,\"filingPartyTypeCode\":\"APLP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"CAESAR\",\"filingPartyFullName\":\"TOMAS CAESAR POPSON\",\"docketCode\":\"EFMPD\",\"dtypPredCode\":\"ZD\",\"eventDesc\":\"Appellant Acting Pro Se\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":2,\"filingDate\":\"12/17/2018\",\"docketDesc\":\"Appl for Tran SC Filed in SC\",\"predCode\":\"ZMREH\",\"sequenceNumber\":2,\"docketText\":\"Appellant\\u0027s Application for Transfer from the Missouri Court of Appeals, Western District, and Attachments.\\n\\nA CASE RECORD CONTAINING ALL DOCKET ENTRIES AND CASE INFORMATION AND A RECEIPT FOR PAYMENT OF THE FILING FEE WERE MAILED TO APPELLANT TOMAS POPSON ON THIS DATE.\",\"filingPartyTypeCode\":\"APLP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"CAESAR\",\"filingPartyFullName\":\"TOMAS CAESAR POPSON\",\"docketCode\":\"EMTR4\",\"dtypPredCode\":\"ZD\",\"eventDesc\":\"Appellant Acting Pro Se\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false},{\"whichone\":1,\"filingDate\":\"12/17/2018\",\"docketDesc\":\"Transfer Summary - Form 15\",\"sequenceNumber\":1,\"docketText\":\"Form No. 15 - Cover Page to Appellant\\u0027s Application for Transfer.\",\"filingPartyTypeCode\":\"APLP\",\"filingPartyLastName\":\"POPSON\",\"filingPartyFirstName\":\"TOMAS\",\"filingPartyMidInitial\":\"CAESAR\",\"filingPartyFullName\":\"TOMAS CAESAR POPSON\",\"docketCode\":\"EFTSM\",\"dtypPredCode\":\"ZD\",\"eventDesc\":\"Appellant Acting Pro Se\",\"hrngOutcome\":\"N\",\"documentId\":0,\"associatedDocketInfoDetails\":[],\"associatedDocketScheduledInfo\":[],\"document\":[],\"behalfOfPartiesNames\":\"\",\"canSeeCaseDocuments\":false,\"confidential\":false}],\"courtType\":\"A\",\"disposed\":false,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":true,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false}",
- "parsed": {
- "caseNumber": "SC97597",
- "protectionOrder": false,
- "locnCode": "SC",
- "courtCode": "SC",
- "docketTabModelList": [
- {
- "whichone": 4,
- "filingDate": "03/05/2019",
- "docketDesc": "Disp-App Tran to SC Denied",
- "predCode": "ZEDTR",
- "sequenceNumber": 4,
- "docketText": "MANDATE SENT TO CLERK OF THE MISSOURI COURT OF APPEALS VIA E-MAIL, TO APPELLANT VIA REGULAR MAIL, AND TO ALL COUNSEL OF RECORD VIA THE MISSOURI EFILING SYSTEM.",
- "filingPartyFullName": "",
- "docketCode": "EZATD",
- "dtypPredCode": "ZD",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 3,
- "filingDate": "12/17/2018",
- "docketDesc": "Filing Fee Paid",
- "predCode": "ZEPRF",
- "sequenceNumber": 3,
- "filingPartyTypeCode": "APLP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "CAESAR",
- "filingPartyFullName": "TOMAS CAESAR POPSON",
- "docketCode": "EFMPD",
- "dtypPredCode": "ZD",
- "eventDesc": "Appellant Acting Pro Se",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 2,
- "filingDate": "12/17/2018",
- "docketDesc": "Appl for Tran SC Filed in SC",
- "predCode": "ZMREH",
- "sequenceNumber": 2,
- "docketText": "Appellant's Application for Transfer from the Missouri Court of Appeals, Western District, and Attachments.\n\nA CASE RECORD CONTAINING ALL DOCKET ENTRIES AND CASE INFORMATION AND A RECEIPT FOR PAYMENT OF THE FILING FEE WERE MAILED TO APPELLANT TOMAS POPSON ON THIS DATE.",
- "filingPartyTypeCode": "APLP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "CAESAR",
- "filingPartyFullName": "TOMAS CAESAR POPSON",
- "docketCode": "EMTR4",
- "dtypPredCode": "ZD",
- "eventDesc": "Appellant Acting Pro Se",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- },
- {
- "whichone": 1,
- "filingDate": "12/17/2018",
- "docketDesc": "Transfer Summary - Form 15",
- "sequenceNumber": 1,
- "docketText": "Form No. 15 - Cover Page to Appellant's Application for Transfer.",
- "filingPartyTypeCode": "APLP",
- "filingPartyLastName": "POPSON",
- "filingPartyFirstName": "TOMAS",
- "filingPartyMidInitial": "CAESAR",
- "filingPartyFullName": "TOMAS CAESAR POPSON",
- "docketCode": "EFTSM",
- "dtypPredCode": "ZD",
- "eventDesc": "Appellant Acting Pro Se",
- "hrngOutcome": "N",
- "documentId": 0,
- "associatedDocketInfoDetails": [],
- "associatedDocketScheduledInfo": [],
- "document": [],
- "behalfOfPartiesNames": "",
- "canSeeCaseDocuments": false,
- "confidential": false
- }
- ],
- "courtType": "A",
- "disposed": false,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": true,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false
- }
- },
- "charges": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "[]",
- "parsed": []
- },
- "judgment": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "[]",
- "parsed": []
- },
- "service": {
- "status": 200,
- "ct": "text/html;charset=ISO-8859-1",
- "text": "<!-- CSS -->\r\n<link href=\"https://www.courts.mo.gov/scr/lib/bootstrap/3.4.1/css/bootstrap.min.css\" rel=\"stylesheet\">\r\n<link href=\"/casenet/resources/css/casenet-bootstrap.css?v=1.1.19.9\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link href=\"/casenet/resources/css/casenet-bootstrap-nav.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/smartalert/alert/css/alert.css\">\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/fontawesome/4.5.0/css/font-awesome.min.css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.css\"/> \r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.date.css\"/>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.time.css\"/>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/casenet/resources/css/datatables-1.10.18.min.css\"/>\t\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/casenet/resources/css/responsive.dataTables.min.css\" />\r\n\r\n\r\n<!-- Scripts -->\r\n<script defer type=\"text/javascript\" src=\"/casenet/resources/js/x.js\"></script>\r\n<script defer type=\"text/javascript\" src=\"/casenet/resources/js/helper.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/browser.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/x.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/jquery/3.5.1/jquery-3.5.1.min.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/bootstrap/3.4.1/js/bootstrap.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/casenet.common.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/smartalert/alert/js/alert.js\"></script>\r\n\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.date.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.time.js\"></script>\r\n\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/datatables-1.10.18.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/dataTables.responsive.2.2.3.min.js\"></script>\t\r\n\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/css/buttons.dataTables.min.css\" />\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/dataTables.buttons.min.js \"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/buttons.print.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/buttons.html5.min.js\"></script>\r\n\r\n<script type=\"text/javascript\" language=\"javascript\">\r\nvar helpers =\r\n\r\n{\r\n\r\n buildDropdown: function(result, dropdown)\r\n\r\n {\r\n\r\n // Remove current options\r\n\r\n dropdown.html('');\r\n\r\n // Add the empty option with the empty message\r\n\t\t\r\n dropdown.append('<option value=\"\">All</option>');\r\n \r\n // Check result isnt empty\r\n\r\n if(result != '')\r\n\r\n {\r\n\r\n // Loop through each of the results and append the option to the dropdown\r\n\r\n $.each(result, function(k, v) {\r\n\r\n dropdown.append('<option value=\"' + v.code + '\">' + v.desc + '</option>');\r\n\r\n });\r\n\r\n }\r\n\r\n },\r\n \r\n buildJudgeDropdown:function(result, dropdown){\r\n\r\n // Remove current options\r\n\r\n dropdown.html('');\r\n\r\n // Add the empty option with the empty message\r\n\t\t\r\n dropdown.append('<option value=\"\">Selection List...</option>');\r\n \r\n $.each(result, function(k, v) {\r\n\r\n dropdown.append('<option value=\"' + v.pidm + '\">' + v.name + '</option>');\r\n\r\n });\r\n }\r\n\r\n}\r\nfunction autoTab(input,len, e) {\r\n\talert('hello');\r\n\tvar keyCode = (isNN) ? e.which : e.keyCode; \r\n\tvar filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];\r\n\tif (input.value.length >= len && !containsElement(filter,keyCode)) {\r\n\t\tinput.value = input.value.slice(0, len);\r\n\t\tinput.form[(getIndex(input)+1) % input.form.length].focus();\r\n\t}\r\n\r\n\tfunction containsElement(arr, ele) {\r\n\t\tvar found = false, index = 0;\r\n\t\twhile (!found && index < arr.length) {\r\n\t\t\tif (arr[index] == ele) {\r\n\t\t\t\tfound = true;\r\n\t\t\t} else {\r\n\t\t\t\tindex++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn found;\r\n\t}\r\n\r\n\tfunction getIndex(input) {\r\n\t\tvar index = -1, i = 0, found = false;\r\n\t\twhile (i < input.form.length && index == -1) {\r\n\t\t\tif (input.form[i] == input) {\r\n\t\t\t\tindex = i;\r\n\t\t\t} else {\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn index;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n</script>\r\n\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\r\n<head>\r\n<meta name=\"Viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0\" />\r\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\r\n\r\n<title>Error</title>\r\n</head>\r\n<body class=\"flexbox-body\">\r\n\t\t<script type=\"text/javascript\">\r\nfunction submitHeaderForm(searchBy){ \r\n\tdocument.getElementById(\"searchType\").value = searchBy;\r\n\tif(searchBy == 'payByWeb'){\r\n\t\twindow.location.href = document.getElementById('payByWebUrl');\r\n\t} else if (searchBy == 'smcCourtCalendar') {\r\n\t\twindow.location.href = document.getElementById('headerSmcCourtCalendarUrl').value;\r\n\t} else if (searchBy == 'smcJudgeMessages') {\r\n\t\twindow.open(document.getElementById('smcJudgeMessagesHeaderUrl').value);\r\n\t}\r\n\telse{\r\n\t\tdocument.getElementById(\"headerForm\").submit();\r\n\t}\r\n}\r\n\r\nfunction submitLogon() {\r\n\tvar loginUrl = '';\r\n\tvar backUrl = window.location.pathname;\r\n\tbackUrl = backUrl.replace('/casenet', '');\r\n\t\r\n\tvar paramList = window.location.search;\r\n\tif(paramList.length > 0){\r\n\t\tconst urlParams = new URLSearchParams(paramList);\r\n\t\tif(urlParams != null){\r\n\t\t\tvar ci = urlParams.get('inputVO.caseNumber');\r\n\t\t\tvar l = urlParams.get('inputVO.courtId');\r\n\t\t\tvar t = urlParams.get('inputVO.isTicket');\r\n\t\t\tvar encodedUrlParam = '?ci='+ci+'l='+l;\r\n\t\t\t\r\n\t\t\tif(t != null){\r\n\t\t\t\tencodedUrlParam = encodedUrlParam +'t='+t;\r\n\t\t\t}\r\n\t\t\tbackUrl = backUrl + encodedUrlParam;\r\n\t\t}\r\n\t}\r\n\t\r\n\tif(window.location.pathname === '/casenet/nameSearchEntry.do') {\r\n\t\tbackUrl = '/nameSearch.do';\r\n\t}\r\n\telse if (window.location.pathname === '/casenet/nameSearchEntry.do'){\r\n\t\tbackUrl = '/nameSearch.do';\r\n\t}\r\n\telse if(window.location.pathname === '/casenet/judgmentIndexResult.do') {\r\n\t\tbackUrl = '/judgmentIndex.do';\r\n\t}\r\n\t\t\r\n\tif(backUrl != null && backUrl.length > 0){\r\n\t\tloginUrl = '/casenet/logon.do?backUrl='+ backUrl;\r\n\t}else{\r\n\t\tloginUrl = '/casenet/logon.do';\r\n\t}\r\n\t\r\n\twindow.location.href=loginUrl;\r\n\t\r\n}\r\n\r\nfunction redirectToEfile() {\r\n\twindow.location.href='/ecf/logon.do';\r\n}\r\n\r\n\r\nfunction submitLogoff() {\r\n\tgetObjectById(\"logoutForm\").submit();\r\n}\r\n\r\nfunction printContent() {\r\n\twindow.print();\r\n}\r\n\r\n</script>\r\n\r\n\r\n<div id=\"header\" class=\"flexbox-header\">\r\n\t<div class=\"sec1 hidden-xs hidden-md hidden-sm\" >\r\n\t\t<div id=\"headerSeal\">\r\n\t\t\t<div class=\"container\">\r\n\t \t<div class=\"header-full-title\">\r\n\t <a href=\"#content\" class=\"sr-only sr-only-focusable\">Tab to main content</a>\r\n\t <a href=\"/\" tabindex=\"0\"><h1 style=\"cursor: pointer;\"><span class=\"sr-only\">Missouri Courts</span></h1></a>\r\n\t \t\t</div>\r\n\t\t \t</div>\r\n\t\t</div>\r\n\t\t<div id=\"headerSealBefore\"></div>\r\n\t\t<div id=\"headerSealAfter\">\r\n\t\t\t<a href=\"/casenet\" tabindex=\"0\" accesskey=\"1\">\r\n\t\t\t\t\t\t<img class=\"ribbon\" alt=\"Missouri Casenet Logo\" style=\"position: absolute; top: 6px; right: 6px;z-index: 101;\" src=\"/casenet/resources/images/casenet_logo3.png\" />\r\n\t\t\t\t\t</a>\t\t\t\r\n\t\t\t\t</div>\r\n\t</div>\r\n\t\r\n\t<div class=\"sec2\">\r\n\t\r\n\t\t<nav class=\"navbar navbar-expand-md\">\r\n\t\t <div class=\"container-fluid\">\r\n\t\t <!-- Brand and toggle get grouped for better mobile display -->\r\n\t\t <div class=\"navbar-header\">\r\n\t\t <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">\r\n\t\t <span class=\"sr-only\">Toggle navigation</span>\r\n\t\t <span class=\"fa fa-bars\"> </span>\r\n\t\t </button>\r\n\t\t <a class=\"navbar-brand hidden-lg\" href=\"/\" style=\"background-image: none; text-transform: none;\">Missouri Courts</a>\r\n\t\t </div>\r\n\t\t\r\n\t\t <!-- Collect the nav links, forms, and other content for toggling -->\r\n\t\t <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">\r\n\t\t <ul class=\"nav navbar-nav\">\r\n\t\t \t<li><a href=\"/casenet\" aria-label=\"Casenet Home Link\"><i class=\"glyphicon glyphicon-home\" aria-hidden=\"true\" style=\"font-size: 27px;\"> </i><span class=\"sr-only\">Home</span></a></li>\r\n\t\t\t \t\t<li title=\"Other court resources\" class=\"dropdown\">\r\n\t\t \t<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\" tabindex=\"0\">&nbsp;Judicial&nbsp;Links <span class=\"caret\"></span></a>\r\n\t\t \t<ul class=\"dropdown-menu\">\r\n\t\t \t \t <li>\r\n\t\t \t \t \t<a href=\"/page.jsp?id=27\" title=\"\">Supreme&nbsp;Court</a>\r\n\t\t \t \t </li>\r\n\t\t \t \t <li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=261\" title=\"\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;of&nbsp;Appeals\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=321\" title=\"\">\r\n\t\t\t\t\t\t\t\tCircuit&nbsp;Courts\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=233\" title=\"\">\r\n\t\t\t\t\t\t\t\tOffice&nbsp;of&nbsp;State&nbsp;Courts&nbsp;Administrator\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=1944\" title=\"\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;Opinions\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=594\" title=\"\">\r\n\t\t\t\t\t\t\t\tNewsroom\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=592\" title=\"\">\r\n\t\t\t\t\t\t\t\tRelated&nbsp;Sites\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t \t </ul>\r\n\t\t </li>\r\n\t\t \r\n\t\t \r\n\t\t <li class=\"dropdown\"><a title=\"eFiling logon\" href=\"#\" tabindex=\"0\" onclick=\"redirectToEfile()\">eFiling</a></li>\r\n\t\t \t<li class=\"dropdown\">\r\n\t \t\t<a title=\"Help Pages\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\" tabindex=\"0\">Help <span class=\"caret\"></span></a>\r\n\t \t\t<ul class=\"dropdown-menu\">\r\n\t \t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98876\" target=\"_blank\" title=\"Go to Our Help Page\">\r\n\t\t\t\t\t\t\t\tGeneral&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98877\" target=\"_blank\" title=\"Get Help Performing a Search\">\r\n\t\t\t\t\t\t\t\tSearch&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=99274\" target=\"_blank\" title=\"Get Specialized Help for a Court\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;Specific&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=124953\" target=\"_blank\" title=\"Go to Our Case Information Help Page\">\r\n\t\t\t\t\t\t\t\tCase&nbsp;Information&nbsp;Pages&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98833\" target=\"_blank\" title=\"Go to Our Municipal/Ordinance Help Page\">\r\n\t\t\t\t\t\t\t\tMunicipal/Ordinance&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98895\" target=\"_blank\" title=\"Go to Our Logon Help Page\">\r\n\t\t\t\t\t\t\t\tLogon&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=87154\" target=\"_blank\" title=\"Go to Track This Case Help Page\">\r\n\t\t\t\t\t\t\t\tTrack&nbsp;This&nbsp;Case&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a id=\"payByWebUrl\" href=\"https://www.courts.mo.gov/page.jsp?id=1886\" target=\"_blank\" title=\"Make a payment\">\r\n\t\t\t\t\t\t\t\t Make&nbsp;a&nbsp;Payment\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=611\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tNeed Legal Help?\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"http://www.vinelink.com/\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tRegister with MOVANS - Victim Automated Notification\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=136013\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tWhat you need to know about Manage My Case\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t \t\t</ul>\r\n\t\t </li>\t\t\r\n\t\t\t\t<li class=\"dropdown\">\r\n\t\t\t\t\t<a href=\"/casenet/contact.do\" title=\"Send comments or suggestions\">\r\n\t\t\t\t\t\tContact&nbsp;Us\r\n\t\t\t\t\t</a>\r\n\t\t\t\t</li>\r\n\t\t\t\t<li class=\"dropdown\"><a href=\"javascript: printContent();\" title=\"Print page content\" tabindex=\"0\">Print</a></li>\r\n\t\t </ul>\r\n\t\t \r\n\t\t \r\n\t\t <html:form action=\"/cases/searchCases\" styleId=\"headerForm\">\r\n\t\t\t\t\t<input type=\"hidden\" id=\"smcJudgeMessagesHeaderUrl\" value=\"/smc-web/getJudgeMessageWindowCnet.do?src=CASENET&userId=PUBLICUSER\"/>\r\n\t\t\t\t\t<input type=\"hidden\" id=\"headerSmcCourtCalendarUrl\" value=\"/smc-web/docketCalendar/getCalendar.do?src=CASENET\"/>\r\n\t\t\t\t\t<input type=\"hidden\" id=\"searchType\" name=\"searchType\" class=\"searchType\" value=\"\"/>\r\n\t\t\t\t</html:form>\r\n\t\t <ul class=\"nav navbar-nav navbar-right\">\r\n\t\t <li title=\"Search options\" class=\"dropdown\">\r\n\t\t \t<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\">Search for Cases By: <span class=\"caret\"></span></a>\r\n\t\t \t <ul class=\"dropdown-menu\">\r\n\t\t \t \r\n\t\t \t \r\n\t\t \t \t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/nameSearch.do?newSearch=Y\">Litigant&nbsp;Name</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/filingDateSearch.do?newSearch=Y\">Filing&nbsp;Date</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/caseNoSearch.do\">Case&nbsp;Number</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/scheduledHearingSearch.do?refreshForm=Y\">Scheduled&nbsp;Hearings&nbsp;&amp;&nbsp;Trials</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/judgmentIndex.do?newSearch=Y\">Judgment&nbsp;Index</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=1886\">Make&nbsp;a&nbsp;Payment</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t\t<a href=\"/amt/\">Manage&nbsp;My&nbsp;Case</a>\r\n\t\t\t\t\t\t\t</li>\t\t\t\t\t\t\r\n\t\t\t\t\t\t</ul>\r\n\t\t </li>\r\n\t\t <!-- \t\t\t\t\t\tUser NOT logged on -->\r\n\t\t\t\t\t\t<li class=\"dropdown\">\r\n\t\t\t\t\t\t\t\t<a class=\"logonLink\" id=\"logonLink\" href=\"#\" tabindex=\"0\" style=\"padding-bottom: 0px;\" onclick=\"submitLogon()\">Logon</a>\r\n\t\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t</ul>\r\n\t\t </div><!-- /.navbar-collapse -->\r\n\t\t </div><!-- /.container-fluid -->\r\n\t\t</nav>\r\n\t</div>\r\n</div>\r\n\r\n\r\n<script type=\"text/javascript\">\r\n\r\n// var finalUrl = $('.logonLink').attr('href')+\"?cnetSecureRedirectUrl=\"+url;\r\n// $('.logonLink').attr('href',encodeURI(finalUrl));\r\n$(document).ready(function(event) {\r\n\tvar url = window.location.href ;\r\n\t$('input[name=\"cnetSecureRedirectUrl\"]').val(encodeURIComponent(url));\r\n});\r\n\r\n</script><div id=\"mainContent\" class=\"flexbox-main\">\r\n\t\t<div class=\"subContent\">\r\n\t\t\t<div class=\"left col-xs-12 col-sm-12 col-md-12 col-lg-12\">\r\n\t\t\t\t<div class=\"alert alert-danger\">\r\n\t\t\t\t\t<i class=\"glyphicon glyphicon-info-sign\"></i><span\r\n\t\t\t\t\t\tstyle=\"valign: center\">&nbsp;&nbsp;THE FOLLOWING ERROR(S) OCCURRED:</span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"left col-xs-12 col-sm-12 col-md-12 col-lg-12\">\r\n\t\t\t\t<div class=\"text-left\">\r\n\t\t\t\t<span class=\"errormessage\">Content type 'application/x-www-form-urlencoded' not supported</span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<style type=\"text/css\">\r\n\t.footerbar{\r\n\t\tborder-top: 1px solid #cbcbcb;\r\n\t}\r\n\t.footerWrapper{\r\n\t\tposition: fixed;\r\n \tbottom: 0px;\r\n \t\twidth: 100%;\r\n \tbackground: #f8f8f8;\r\n\t}\r\n\t\r\n\t@media print {\r\n\t.footerbar{\r\n\t\tcontent: none !important;\r\n\t}\r\n\t.footerWrapper{\r\n\t\tcontent: none !important;\r\n\t}\r\n\t.visible-xs{\r\n\tcontent: none !important;\r\n\t}\r\n\t}\r\n</style>\r\n<div class=\"footerWrapper\">\r\n\t<div id=\"footer\" class=\"hidden-xs\">\r\n\t\t<div class=\"footerbar\"></div>\r\n\t\t<div class=\"footerContent \">\r\n\t\t\t<div style=\"font-weight: normal; text-align: left;\" class=\"col-sm-6 col-md-6\">\r\n\t\t\tCase.net Version 1.1.19.9</div>\r\n\t\t\t<div style=\"font-weight: normal; text-align: right;\" class=\"col-sm-6 col-md-6\">Released 04/27/2026</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<div id=\"footer-xs\" class=\"visible-xs\">\r\n\t\t<div class=\"footerContent-xs \">\r\n\t\t\t<div style=\"font-weight: normal;\"> Version 1.1.19.9 - Released 04/27/2026</div>\r\n\t\t</div>\r\n\t</div>\r\n</div>\r\n</body>\r\n</html>\r\n"
- },
- "event": {
- "status": 200,
- "ct": "text/html;charset=ISO-8859-1",
- "text": "<!-- CSS -->\r\n<link href=\"https://www.courts.mo.gov/scr/lib/bootstrap/3.4.1/css/bootstrap.min.css\" rel=\"stylesheet\">\r\n<link href=\"/casenet/resources/css/casenet-bootstrap.css?v=1.1.19.9\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link href=\"/casenet/resources/css/casenet-bootstrap-nav.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/smartalert/alert/css/alert.css\">\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/fontawesome/4.5.0/css/font-awesome.min.css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.css\"/> \r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.date.css\"/>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.time.css\"/>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/casenet/resources/css/datatables-1.10.18.min.css\"/>\t\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/casenet/resources/css/responsive.dataTables.min.css\" />\r\n\r\n\r\n<!-- Scripts -->\r\n<script defer type=\"text/javascript\" src=\"/casenet/resources/js/x.js\"></script>\r\n<script defer type=\"text/javascript\" src=\"/casenet/resources/js/helper.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/browser.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/x.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/jquery/3.5.1/jquery-3.5.1.min.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/bootstrap/3.4.1/js/bootstrap.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/casenet.common.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/smartalert/alert/js/alert.js\"></script>\r\n\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.date.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.time.js\"></script>\r\n\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/datatables-1.10.18.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/dataTables.responsive.2.2.3.min.js\"></script>\t\r\n\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/css/buttons.dataTables.min.css\" />\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/dataTables.buttons.min.js \"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/buttons.print.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/buttons.html5.min.js\"></script>\r\n\r\n<script type=\"text/javascript\" language=\"javascript\">\r\nvar helpers =\r\n\r\n{\r\n\r\n buildDropdown: function(result, dropdown)\r\n\r\n {\r\n\r\n // Remove current options\r\n\r\n dropdown.html('');\r\n\r\n // Add the empty option with the empty message\r\n\t\t\r\n dropdown.append('<option value=\"\">All</option>');\r\n \r\n // Check result isnt empty\r\n\r\n if(result != '')\r\n\r\n {\r\n\r\n // Loop through each of the results and append the option to the dropdown\r\n\r\n $.each(result, function(k, v) {\r\n\r\n dropdown.append('<option value=\"' + v.code + '\">' + v.desc + '</option>');\r\n\r\n });\r\n\r\n }\r\n\r\n },\r\n \r\n buildJudgeDropdown:function(result, dropdown){\r\n\r\n // Remove current options\r\n\r\n dropdown.html('');\r\n\r\n // Add the empty option with the empty message\r\n\t\t\r\n dropdown.append('<option value=\"\">Selection List...</option>');\r\n \r\n $.each(result, function(k, v) {\r\n\r\n dropdown.append('<option value=\"' + v.pidm + '\">' + v.name + '</option>');\r\n\r\n });\r\n }\r\n\r\n}\r\nfunction autoTab(input,len, e) {\r\n\talert('hello');\r\n\tvar keyCode = (isNN) ? e.which : e.keyCode; \r\n\tvar filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];\r\n\tif (input.value.length >= len && !containsElement(filter,keyCode)) {\r\n\t\tinput.value = input.value.slice(0, len);\r\n\t\tinput.form[(getIndex(input)+1) % input.form.length].focus();\r\n\t}\r\n\r\n\tfunction containsElement(arr, ele) {\r\n\t\tvar found = false, index = 0;\r\n\t\twhile (!found && index < arr.length) {\r\n\t\t\tif (arr[index] == ele) {\r\n\t\t\t\tfound = true;\r\n\t\t\t} else {\r\n\t\t\t\tindex++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn found;\r\n\t}\r\n\r\n\tfunction getIndex(input) {\r\n\t\tvar index = -1, i = 0, found = false;\r\n\t\twhile (i < input.form.length && index == -1) {\r\n\t\t\tif (input.form[i] == input) {\r\n\t\t\t\tindex = i;\r\n\t\t\t} else {\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn index;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n</script>\r\n\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\r\n<head>\r\n<meta name=\"Viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0\" />\r\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\r\n\r\n<title>Error</title>\r\n</head>\r\n<body class=\"flexbox-body\">\r\n\t\t<script type=\"text/javascript\">\r\nfunction submitHeaderForm(searchBy){ \r\n\tdocument.getElementById(\"searchType\").value = searchBy;\r\n\tif(searchBy == 'payByWeb'){\r\n\t\twindow.location.href = document.getElementById('payByWebUrl');\r\n\t} else if (searchBy == 'smcCourtCalendar') {\r\n\t\twindow.location.href = document.getElementById('headerSmcCourtCalendarUrl').value;\r\n\t} else if (searchBy == 'smcJudgeMessages') {\r\n\t\twindow.open(document.getElementById('smcJudgeMessagesHeaderUrl').value);\r\n\t}\r\n\telse{\r\n\t\tdocument.getElementById(\"headerForm\").submit();\r\n\t}\r\n}\r\n\r\nfunction submitLogon() {\r\n\tvar loginUrl = '';\r\n\tvar backUrl = window.location.pathname;\r\n\tbackUrl = backUrl.replace('/casenet', '');\r\n\t\r\n\tvar paramList = window.location.search;\r\n\tif(paramList.length > 0){\r\n\t\tconst urlParams = new URLSearchParams(paramList);\r\n\t\tif(urlParams != null){\r\n\t\t\tvar ci = urlParams.get('inputVO.caseNumber');\r\n\t\t\tvar l = urlParams.get('inputVO.courtId');\r\n\t\t\tvar t = urlParams.get('inputVO.isTicket');\r\n\t\t\tvar encodedUrlParam = '?ci='+ci+'l='+l;\r\n\t\t\t\r\n\t\t\tif(t != null){\r\n\t\t\t\tencodedUrlParam = encodedUrlParam +'t='+t;\r\n\t\t\t}\r\n\t\t\tbackUrl = backUrl + encodedUrlParam;\r\n\t\t}\r\n\t}\r\n\t\r\n\tif(window.location.pathname === '/casenet/nameSearchEntry.do') {\r\n\t\tbackUrl = '/nameSearch.do';\r\n\t}\r\n\telse if (window.location.pathname === '/casenet/nameSearchEntry.do'){\r\n\t\tbackUrl = '/nameSearch.do';\r\n\t}\r\n\telse if(window.location.pathname === '/casenet/judgmentIndexResult.do') {\r\n\t\tbackUrl = '/judgmentIndex.do';\r\n\t}\r\n\t\t\r\n\tif(backUrl != null && backUrl.length > 0){\r\n\t\tloginUrl = '/casenet/logon.do?backUrl='+ backUrl;\r\n\t}else{\r\n\t\tloginUrl = '/casenet/logon.do';\r\n\t}\r\n\t\r\n\twindow.location.href=loginUrl;\r\n\t\r\n}\r\n\r\nfunction redirectToEfile() {\r\n\twindow.location.href='/ecf/logon.do';\r\n}\r\n\r\n\r\nfunction submitLogoff() {\r\n\tgetObjectById(\"logoutForm\").submit();\r\n}\r\n\r\nfunction printContent() {\r\n\twindow.print();\r\n}\r\n\r\n</script>\r\n\r\n\r\n<div id=\"header\" class=\"flexbox-header\">\r\n\t<div class=\"sec1 hidden-xs hidden-md hidden-sm\" >\r\n\t\t<div id=\"headerSeal\">\r\n\t\t\t<div class=\"container\">\r\n\t \t<div class=\"header-full-title\">\r\n\t <a href=\"#content\" class=\"sr-only sr-only-focusable\">Tab to main content</a>\r\n\t <a href=\"/\" tabindex=\"0\"><h1 style=\"cursor: pointer;\"><span class=\"sr-only\">Missouri Courts</span></h1></a>\r\n\t \t\t</div>\r\n\t\t \t</div>\r\n\t\t</div>\r\n\t\t<div id=\"headerSealBefore\"></div>\r\n\t\t<div id=\"headerSealAfter\">\r\n\t\t\t<a href=\"/casenet\" tabindex=\"0\" accesskey=\"1\">\r\n\t\t\t\t\t\t<img class=\"ribbon\" alt=\"Missouri Casenet Logo\" style=\"position: absolute; top: 6px; right: 6px;z-index: 101;\" src=\"/casenet/resources/images/casenet_logo3.png\" />\r\n\t\t\t\t\t</a>\t\t\t\r\n\t\t\t\t</div>\r\n\t</div>\r\n\t\r\n\t<div class=\"sec2\">\r\n\t\r\n\t\t<nav class=\"navbar navbar-expand-md\">\r\n\t\t <div class=\"container-fluid\">\r\n\t\t <!-- Brand and toggle get grouped for better mobile display -->\r\n\t\t <div class=\"navbar-header\">\r\n\t\t <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">\r\n\t\t <span class=\"sr-only\">Toggle navigation</span>\r\n\t\t <span class=\"fa fa-bars\"> </span>\r\n\t\t </button>\r\n\t\t <a class=\"navbar-brand hidden-lg\" href=\"/\" style=\"background-image: none; text-transform: none;\">Missouri Courts</a>\r\n\t\t </div>\r\n\t\t\r\n\t\t <!-- Collect the nav links, forms, and other content for toggling -->\r\n\t\t <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">\r\n\t\t <ul class=\"nav navbar-nav\">\r\n\t\t \t<li><a href=\"/casenet\" aria-label=\"Casenet Home Link\"><i class=\"glyphicon glyphicon-home\" aria-hidden=\"true\" style=\"font-size: 27px;\"> </i><span class=\"sr-only\">Home</span></a></li>\r\n\t\t\t \t\t<li title=\"Other court resources\" class=\"dropdown\">\r\n\t\t \t<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\" tabindex=\"0\">&nbsp;Judicial&nbsp;Links <span class=\"caret\"></span></a>\r\n\t\t \t<ul class=\"dropdown-menu\">\r\n\t\t \t \t <li>\r\n\t\t \t \t \t<a href=\"/page.jsp?id=27\" title=\"\">Supreme&nbsp;Court</a>\r\n\t\t \t \t </li>\r\n\t\t \t \t <li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=261\" title=\"\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;of&nbsp;Appeals\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=321\" title=\"\">\r\n\t\t\t\t\t\t\t\tCircuit&nbsp;Courts\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=233\" title=\"\">\r\n\t\t\t\t\t\t\t\tOffice&nbsp;of&nbsp;State&nbsp;Courts&nbsp;Administrator\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=1944\" title=\"\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;Opinions\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=594\" title=\"\">\r\n\t\t\t\t\t\t\t\tNewsroom\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=592\" title=\"\">\r\n\t\t\t\t\t\t\t\tRelated&nbsp;Sites\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t \t </ul>\r\n\t\t </li>\r\n\t\t \r\n\t\t \r\n\t\t <li class=\"dropdown\"><a title=\"eFiling logon\" href=\"#\" tabindex=\"0\" onclick=\"redirectToEfile()\">eFiling</a></li>\r\n\t\t \t<li class=\"dropdown\">\r\n\t \t\t<a title=\"Help Pages\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\" tabindex=\"0\">Help <span class=\"caret\"></span></a>\r\n\t \t\t<ul class=\"dropdown-menu\">\r\n\t \t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98876\" target=\"_blank\" title=\"Go to Our Help Page\">\r\n\t\t\t\t\t\t\t\tGeneral&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98877\" target=\"_blank\" title=\"Get Help Performing a Search\">\r\n\t\t\t\t\t\t\t\tSearch&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=99274\" target=\"_blank\" title=\"Get Specialized Help for a Court\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;Specific&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=124953\" target=\"_blank\" title=\"Go to Our Case Information Help Page\">\r\n\t\t\t\t\t\t\t\tCase&nbsp;Information&nbsp;Pages&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98833\" target=\"_blank\" title=\"Go to Our Municipal/Ordinance Help Page\">\r\n\t\t\t\t\t\t\t\tMunicipal/Ordinance&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98895\" target=\"_blank\" title=\"Go to Our Logon Help Page\">\r\n\t\t\t\t\t\t\t\tLogon&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=87154\" target=\"_blank\" title=\"Go to Track This Case Help Page\">\r\n\t\t\t\t\t\t\t\tTrack&nbsp;This&nbsp;Case&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a id=\"payByWebUrl\" href=\"https://www.courts.mo.gov/page.jsp?id=1886\" target=\"_blank\" title=\"Make a payment\">\r\n\t\t\t\t\t\t\t\t Make&nbsp;a&nbsp;Payment\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=611\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tNeed Legal Help?\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"http://www.vinelink.com/\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tRegister with MOVANS - Victim Automated Notification\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=136013\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tWhat you need to know about Manage My Case\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t \t\t</ul>\r\n\t\t </li>\t\t\r\n\t\t\t\t<li class=\"dropdown\">\r\n\t\t\t\t\t<a href=\"/casenet/contact.do\" title=\"Send comments or suggestions\">\r\n\t\t\t\t\t\tContact&nbsp;Us\r\n\t\t\t\t\t</a>\r\n\t\t\t\t</li>\r\n\t\t\t\t<li class=\"dropdown\"><a href=\"javascript: printContent();\" title=\"Print page content\" tabindex=\"0\">Print</a></li>\r\n\t\t </ul>\r\n\t\t \r\n\t\t \r\n\t\t <html:form action=\"/cases/searchCases\" styleId=\"headerForm\">\r\n\t\t\t\t\t<input type=\"hidden\" id=\"smcJudgeMessagesHeaderUrl\" value=\"/smc-web/getJudgeMessageWindowCnet.do?src=CASENET&userId=PUBLICUSER\"/>\r\n\t\t\t\t\t<input type=\"hidden\" id=\"headerSmcCourtCalendarUrl\" value=\"/smc-web/docketCalendar/getCalendar.do?src=CASENET\"/>\r\n\t\t\t\t\t<input type=\"hidden\" id=\"searchType\" name=\"searchType\" class=\"searchType\" value=\"\"/>\r\n\t\t\t\t</html:form>\r\n\t\t <ul class=\"nav navbar-nav navbar-right\">\r\n\t\t <li title=\"Search options\" class=\"dropdown\">\r\n\t\t \t<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\">Search for Cases By: <span class=\"caret\"></span></a>\r\n\t\t \t <ul class=\"dropdown-menu\">\r\n\t\t \t \r\n\t\t \t \r\n\t\t \t \t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/nameSearch.do?newSearch=Y\">Litigant&nbsp;Name</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/filingDateSearch.do?newSearch=Y\">Filing&nbsp;Date</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/caseNoSearch.do\">Case&nbsp;Number</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/scheduledHearingSearch.do?refreshForm=Y\">Scheduled&nbsp;Hearings&nbsp;&amp;&nbsp;Trials</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/judgmentIndex.do?newSearch=Y\">Judgment&nbsp;Index</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=1886\">Make&nbsp;a&nbsp;Payment</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t\t<a href=\"/amt/\">Manage&nbsp;My&nbsp;Case</a>\r\n\t\t\t\t\t\t\t</li>\t\t\t\t\t\t\r\n\t\t\t\t\t\t</ul>\r\n\t\t </li>\r\n\t\t <!-- \t\t\t\t\t\tUser NOT logged on -->\r\n\t\t\t\t\t\t<li class=\"dropdown\">\r\n\t\t\t\t\t\t\t\t<a class=\"logonLink\" id=\"logonLink\" href=\"#\" tabindex=\"0\" style=\"padding-bottom: 0px;\" onclick=\"submitLogon()\">Logon</a>\r\n\t\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t</ul>\r\n\t\t </div><!-- /.navbar-collapse -->\r\n\t\t </div><!-- /.container-fluid -->\r\n\t\t</nav>\r\n\t</div>\r\n</div>\r\n\r\n\r\n<script type=\"text/javascript\">\r\n\r\n// var finalUrl = $('.logonLink').attr('href')+\"?cnetSecureRedirectUrl=\"+url;\r\n// $('.logonLink').attr('href',encodeURI(finalUrl));\r\n$(document).ready(function(event) {\r\n\tvar url = window.location.href ;\r\n\t$('input[name=\"cnetSecureRedirectUrl\"]').val(encodeURIComponent(url));\r\n});\r\n\r\n</script><div id=\"mainContent\" class=\"flexbox-main\">\r\n\t\t<div class=\"subContent\">\r\n\t\t\t<div class=\"left col-xs-12 col-sm-12 col-md-12 col-lg-12\">\r\n\t\t\t\t<div class=\"alert alert-danger\">\r\n\t\t\t\t\t<i class=\"glyphicon glyphicon-info-sign\"></i><span\r\n\t\t\t\t\t\tstyle=\"valign: center\">&nbsp;&nbsp;THE FOLLOWING ERROR(S) OCCURRED:</span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"left col-xs-12 col-sm-12 col-md-12 col-lg-12\">\r\n\t\t\t\t<div class=\"text-left\">\r\n\t\t\t\t<span class=\"errormessage\">Content type 'application/x-www-form-urlencoded' not supported</span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<style type=\"text/css\">\r\n\t.footerbar{\r\n\t\tborder-top: 1px solid #cbcbcb;\r\n\t}\r\n\t.footerWrapper{\r\n\t\tposition: fixed;\r\n \tbottom: 0px;\r\n \t\twidth: 100%;\r\n \tbackground: #f8f8f8;\r\n\t}\r\n\t\r\n\t@media print {\r\n\t.footerbar{\r\n\t\tcontent: none !important;\r\n\t}\r\n\t.footerWrapper{\r\n\t\tcontent: none !important;\r\n\t}\r\n\t.visible-xs{\r\n\tcontent: none !important;\r\n\t}\r\n\t}\r\n</style>\r\n<div class=\"footerWrapper\">\r\n\t<div id=\"footer\" class=\"hidden-xs\">\r\n\t\t<div class=\"footerbar\"></div>\r\n\t\t<div class=\"footerContent \">\r\n\t\t\t<div style=\"font-weight: normal; text-align: left;\" class=\"col-sm-6 col-md-6\">\r\n\t\t\tCase.net Version 1.1.19.9</div>\r\n\t\t\t<div style=\"font-weight: normal; text-align: right;\" class=\"col-sm-6 col-md-6\">Released 04/27/2026</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<div id=\"footer-xs\" class=\"visible-xs\">\r\n\t\t<div class=\"footerContent-xs \">\r\n\t\t\t<div style=\"font-weight: normal;\"> Version 1.1.19.9 - Released 04/27/2026</div>\r\n\t\t</div>\r\n\t</div>\r\n</div>\r\n</body>\r\n</html>\r\n"
- },
- "garnishment": {
- "status": 200,
- "ct": "text/html;charset=ISO-8859-1",
- "text": "<!-- CSS -->\r\n<link href=\"https://www.courts.mo.gov/scr/lib/bootstrap/3.4.1/css/bootstrap.min.css\" rel=\"stylesheet\">\r\n<link href=\"/casenet/resources/css/casenet-bootstrap.css?v=1.1.19.9\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link href=\"/casenet/resources/css/casenet-bootstrap-nav.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/smartalert/alert/css/alert.css\">\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/fontawesome/4.5.0/css/font-awesome.min.css\" />\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.css\"/> \r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.date.css\"/>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/themes/default.time.css\"/>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/casenet/resources/css/datatables-1.10.18.min.css\"/>\t\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/casenet/resources/css/responsive.dataTables.min.css\" />\r\n\r\n\r\n<!-- Scripts -->\r\n<script defer type=\"text/javascript\" src=\"/casenet/resources/js/x.js\"></script>\r\n<script defer type=\"text/javascript\" src=\"/casenet/resources/js/helper.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/browser.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/x.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/jquery/3.5.1/jquery-3.5.1.min.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/bootstrap/3.4.1/js/bootstrap.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/casenet.common.js\"></script>\r\n<script src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/smartalert/alert/js/alert.js\"></script>\r\n\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.date.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/jqueryplugins/pickadate/3.6.2/picker.time.js\"></script>\r\n\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/datatables-1.10.18.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"/casenet/resources/js/dataTables.responsive.2.2.3.min.js\"></script>\t\r\n\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/css/buttons.dataTables.min.css\" />\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/dataTables.buttons.min.js \"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/buttons.print.min.js\"></script>\r\n<script type=\"text/javascript\" src=\"https://www.courts.mo.gov/scr/lib/datatablesplugins/buttons/1.7.0/js/buttons.html5.min.js\"></script>\r\n\r\n<script type=\"text/javascript\" language=\"javascript\">\r\nvar helpers =\r\n\r\n{\r\n\r\n buildDropdown: function(result, dropdown)\r\n\r\n {\r\n\r\n // Remove current options\r\n\r\n dropdown.html('');\r\n\r\n // Add the empty option with the empty message\r\n\t\t\r\n dropdown.append('<option value=\"\">All</option>');\r\n \r\n // Check result isnt empty\r\n\r\n if(result != '')\r\n\r\n {\r\n\r\n // Loop through each of the results and append the option to the dropdown\r\n\r\n $.each(result, function(k, v) {\r\n\r\n dropdown.append('<option value=\"' + v.code + '\">' + v.desc + '</option>');\r\n\r\n });\r\n\r\n }\r\n\r\n },\r\n \r\n buildJudgeDropdown:function(result, dropdown){\r\n\r\n // Remove current options\r\n\r\n dropdown.html('');\r\n\r\n // Add the empty option with the empty message\r\n\t\t\r\n dropdown.append('<option value=\"\">Selection List...</option>');\r\n \r\n $.each(result, function(k, v) {\r\n\r\n dropdown.append('<option value=\"' + v.pidm + '\">' + v.name + '</option>');\r\n\r\n });\r\n }\r\n\r\n}\r\nfunction autoTab(input,len, e) {\r\n\talert('hello');\r\n\tvar keyCode = (isNN) ? e.which : e.keyCode; \r\n\tvar filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];\r\n\tif (input.value.length >= len && !containsElement(filter,keyCode)) {\r\n\t\tinput.value = input.value.slice(0, len);\r\n\t\tinput.form[(getIndex(input)+1) % input.form.length].focus();\r\n\t}\r\n\r\n\tfunction containsElement(arr, ele) {\r\n\t\tvar found = false, index = 0;\r\n\t\twhile (!found && index < arr.length) {\r\n\t\t\tif (arr[index] == ele) {\r\n\t\t\t\tfound = true;\r\n\t\t\t} else {\r\n\t\t\t\tindex++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn found;\r\n\t}\r\n\r\n\tfunction getIndex(input) {\r\n\t\tvar index = -1, i = 0, found = false;\r\n\t\twhile (i < input.form.length && index == -1) {\r\n\t\t\tif (input.form[i] == input) {\r\n\t\t\t\tindex = i;\r\n\t\t\t} else {\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn index;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n</script>\r\n\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\r\n<head>\r\n<meta name=\"Viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0\" />\r\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\r\n\r\n<title>Error</title>\r\n</head>\r\n<body class=\"flexbox-body\">\r\n\t\t<script type=\"text/javascript\">\r\nfunction submitHeaderForm(searchBy){ \r\n\tdocument.getElementById(\"searchType\").value = searchBy;\r\n\tif(searchBy == 'payByWeb'){\r\n\t\twindow.location.href = document.getElementById('payByWebUrl');\r\n\t} else if (searchBy == 'smcCourtCalendar') {\r\n\t\twindow.location.href = document.getElementById('headerSmcCourtCalendarUrl').value;\r\n\t} else if (searchBy == 'smcJudgeMessages') {\r\n\t\twindow.open(document.getElementById('smcJudgeMessagesHeaderUrl').value);\r\n\t}\r\n\telse{\r\n\t\tdocument.getElementById(\"headerForm\").submit();\r\n\t}\r\n}\r\n\r\nfunction submitLogon() {\r\n\tvar loginUrl = '';\r\n\tvar backUrl = window.location.pathname;\r\n\tbackUrl = backUrl.replace('/casenet', '');\r\n\t\r\n\tvar paramList = window.location.search;\r\n\tif(paramList.length > 0){\r\n\t\tconst urlParams = new URLSearchParams(paramList);\r\n\t\tif(urlParams != null){\r\n\t\t\tvar ci = urlParams.get('inputVO.caseNumber');\r\n\t\t\tvar l = urlParams.get('inputVO.courtId');\r\n\t\t\tvar t = urlParams.get('inputVO.isTicket');\r\n\t\t\tvar encodedUrlParam = '?ci='+ci+'l='+l;\r\n\t\t\t\r\n\t\t\tif(t != null){\r\n\t\t\t\tencodedUrlParam = encodedUrlParam +'t='+t;\r\n\t\t\t}\r\n\t\t\tbackUrl = backUrl + encodedUrlParam;\r\n\t\t}\r\n\t}\r\n\t\r\n\tif(window.location.pathname === '/casenet/nameSearchEntry.do') {\r\n\t\tbackUrl = '/nameSearch.do';\r\n\t}\r\n\telse if (window.location.pathname === '/casenet/nameSearchEntry.do'){\r\n\t\tbackUrl = '/nameSearch.do';\r\n\t}\r\n\telse if(window.location.pathname === '/casenet/judgmentIndexResult.do') {\r\n\t\tbackUrl = '/judgmentIndex.do';\r\n\t}\r\n\t\t\r\n\tif(backUrl != null && backUrl.length > 0){\r\n\t\tloginUrl = '/casenet/logon.do?backUrl='+ backUrl;\r\n\t}else{\r\n\t\tloginUrl = '/casenet/logon.do';\r\n\t}\r\n\t\r\n\twindow.location.href=loginUrl;\r\n\t\r\n}\r\n\r\nfunction redirectToEfile() {\r\n\twindow.location.href='/ecf/logon.do';\r\n}\r\n\r\n\r\nfunction submitLogoff() {\r\n\tgetObjectById(\"logoutForm\").submit();\r\n}\r\n\r\nfunction printContent() {\r\n\twindow.print();\r\n}\r\n\r\n</script>\r\n\r\n\r\n<div id=\"header\" class=\"flexbox-header\">\r\n\t<div class=\"sec1 hidden-xs hidden-md hidden-sm\" >\r\n\t\t<div id=\"headerSeal\">\r\n\t\t\t<div class=\"container\">\r\n\t \t<div class=\"header-full-title\">\r\n\t <a href=\"#content\" class=\"sr-only sr-only-focusable\">Tab to main content</a>\r\n\t <a href=\"/\" tabindex=\"0\"><h1 style=\"cursor: pointer;\"><span class=\"sr-only\">Missouri Courts</span></h1></a>\r\n\t \t\t</div>\r\n\t\t \t</div>\r\n\t\t</div>\r\n\t\t<div id=\"headerSealBefore\"></div>\r\n\t\t<div id=\"headerSealAfter\">\r\n\t\t\t<a href=\"/casenet\" tabindex=\"0\" accesskey=\"1\">\r\n\t\t\t\t\t\t<img class=\"ribbon\" alt=\"Missouri Casenet Logo\" style=\"position: absolute; top: 6px; right: 6px;z-index: 101;\" src=\"/casenet/resources/images/casenet_logo3.png\" />\r\n\t\t\t\t\t</a>\t\t\t\r\n\t\t\t\t</div>\r\n\t</div>\r\n\t\r\n\t<div class=\"sec2\">\r\n\t\r\n\t\t<nav class=\"navbar navbar-expand-md\">\r\n\t\t <div class=\"container-fluid\">\r\n\t\t <!-- Brand and toggle get grouped for better mobile display -->\r\n\t\t <div class=\"navbar-header\">\r\n\t\t <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">\r\n\t\t <span class=\"sr-only\">Toggle navigation</span>\r\n\t\t <span class=\"fa fa-bars\"> </span>\r\n\t\t </button>\r\n\t\t <a class=\"navbar-brand hidden-lg\" href=\"/\" style=\"background-image: none; text-transform: none;\">Missouri Courts</a>\r\n\t\t </div>\r\n\t\t\r\n\t\t <!-- Collect the nav links, forms, and other content for toggling -->\r\n\t\t <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">\r\n\t\t <ul class=\"nav navbar-nav\">\r\n\t\t \t<li><a href=\"/casenet\" aria-label=\"Casenet Home Link\"><i class=\"glyphicon glyphicon-home\" aria-hidden=\"true\" style=\"font-size: 27px;\"> </i><span class=\"sr-only\">Home</span></a></li>\r\n\t\t\t \t\t<li title=\"Other court resources\" class=\"dropdown\">\r\n\t\t \t<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\" tabindex=\"0\">&nbsp;Judicial&nbsp;Links <span class=\"caret\"></span></a>\r\n\t\t \t<ul class=\"dropdown-menu\">\r\n\t\t \t \t <li>\r\n\t\t \t \t \t<a href=\"/page.jsp?id=27\" title=\"\">Supreme&nbsp;Court</a>\r\n\t\t \t \t </li>\r\n\t\t \t \t <li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=261\" title=\"\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;of&nbsp;Appeals\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=321\" title=\"\">\r\n\t\t\t\t\t\t\t\tCircuit&nbsp;Courts\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=233\" title=\"\">\r\n\t\t\t\t\t\t\t\tOffice&nbsp;of&nbsp;State&nbsp;Courts&nbsp;Administrator\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=1944\" title=\"\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;Opinions\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=594\" title=\"\">\r\n\t\t\t\t\t\t\t\tNewsroom\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/page.jsp?id=592\" title=\"\">\r\n\t\t\t\t\t\t\t\tRelated&nbsp;Sites\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t \t </ul>\r\n\t\t </li>\r\n\t\t \r\n\t\t \r\n\t\t <li class=\"dropdown\"><a title=\"eFiling logon\" href=\"#\" tabindex=\"0\" onclick=\"redirectToEfile()\">eFiling</a></li>\r\n\t\t \t<li class=\"dropdown\">\r\n\t \t\t<a title=\"Help Pages\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\" tabindex=\"0\">Help <span class=\"caret\"></span></a>\r\n\t \t\t<ul class=\"dropdown-menu\">\r\n\t \t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98876\" target=\"_blank\" title=\"Go to Our Help Page\">\r\n\t\t\t\t\t\t\t\tGeneral&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98877\" target=\"_blank\" title=\"Get Help Performing a Search\">\r\n\t\t\t\t\t\t\t\tSearch&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=99274\" target=\"_blank\" title=\"Get Specialized Help for a Court\">\r\n\t\t\t\t\t\t\t\tCourt&nbsp;Specific&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=124953\" target=\"_blank\" title=\"Go to Our Case Information Help Page\">\r\n\t\t\t\t\t\t\t\tCase&nbsp;Information&nbsp;Pages&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98833\" target=\"_blank\" title=\"Go to Our Municipal/Ordinance Help Page\">\r\n\t\t\t\t\t\t\t\tMunicipal/Ordinance&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=98895\" target=\"_blank\" title=\"Go to Our Logon Help Page\">\r\n\t\t\t\t\t\t\t\tLogon&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=87154\" target=\"_blank\" title=\"Go to Track This Case Help Page\">\r\n\t\t\t\t\t\t\t\tTrack&nbsp;This&nbsp;Case&nbsp;Help\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a id=\"payByWebUrl\" href=\"https://www.courts.mo.gov/page.jsp?id=1886\" target=\"_blank\" title=\"Make a payment\">\r\n\t\t\t\t\t\t\t\t Make&nbsp;a&nbsp;Payment\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=611\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tNeed Legal Help?\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"http://www.vinelink.com/\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tRegister with MOVANS - Victim Automated Notification\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=136013\" target=\"_blank\">\r\n\t\t\t\t\t\t\t\tWhat you need to know about Manage My Case\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t</li>\r\n\t \t\t</ul>\r\n\t\t </li>\t\t\r\n\t\t\t\t<li class=\"dropdown\">\r\n\t\t\t\t\t<a href=\"/casenet/contact.do\" title=\"Send comments or suggestions\">\r\n\t\t\t\t\t\tContact&nbsp;Us\r\n\t\t\t\t\t</a>\r\n\t\t\t\t</li>\r\n\t\t\t\t<li class=\"dropdown\"><a href=\"javascript: printContent();\" title=\"Print page content\" tabindex=\"0\">Print</a></li>\r\n\t\t </ul>\r\n\t\t \r\n\t\t \r\n\t\t <html:form action=\"/cases/searchCases\" styleId=\"headerForm\">\r\n\t\t\t\t\t<input type=\"hidden\" id=\"smcJudgeMessagesHeaderUrl\" value=\"/smc-web/getJudgeMessageWindowCnet.do?src=CASENET&userId=PUBLICUSER\"/>\r\n\t\t\t\t\t<input type=\"hidden\" id=\"headerSmcCourtCalendarUrl\" value=\"/smc-web/docketCalendar/getCalendar.do?src=CASENET\"/>\r\n\t\t\t\t\t<input type=\"hidden\" id=\"searchType\" name=\"searchType\" class=\"searchType\" value=\"\"/>\r\n\t\t\t\t</html:form>\r\n\t\t <ul class=\"nav navbar-nav navbar-right\">\r\n\t\t <li title=\"Search options\" class=\"dropdown\">\r\n\t\t \t<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\"\r\n\t\t\t\t\t\t\taria-expanded=\"false\" href=\"#\">Search for Cases By: <span class=\"caret\"></span></a>\r\n\t\t \t <ul class=\"dropdown-menu\">\r\n\t\t \t \r\n\t\t \t \r\n\t\t \t \t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/nameSearch.do?newSearch=Y\">Litigant&nbsp;Name</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/filingDateSearch.do?newSearch=Y\">Filing&nbsp;Date</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/caseNoSearch.do\">Case&nbsp;Number</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/scheduledHearingSearch.do?refreshForm=Y\">Scheduled&nbsp;Hearings&nbsp;&amp;&nbsp;Trials</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"/casenet/judgmentIndex.do?newSearch=Y\">Judgment&nbsp;Index</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t<a href=\"https://www.courts.mo.gov/page.jsp?id=1886\">Make&nbsp;a&nbsp;Payment</a>\r\n\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t\t<a href=\"/amt/\">Manage&nbsp;My&nbsp;Case</a>\r\n\t\t\t\t\t\t\t</li>\t\t\t\t\t\t\r\n\t\t\t\t\t\t</ul>\r\n\t\t </li>\r\n\t\t <!-- \t\t\t\t\t\tUser NOT logged on -->\r\n\t\t\t\t\t\t<li class=\"dropdown\">\r\n\t\t\t\t\t\t\t\t<a class=\"logonLink\" id=\"logonLink\" href=\"#\" tabindex=\"0\" style=\"padding-bottom: 0px;\" onclick=\"submitLogon()\">Logon</a>\r\n\t\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t</ul>\r\n\t\t </div><!-- /.navbar-collapse -->\r\n\t\t </div><!-- /.container-fluid -->\r\n\t\t</nav>\r\n\t</div>\r\n</div>\r\n\r\n\r\n<script type=\"text/javascript\">\r\n\r\n// var finalUrl = $('.logonLink').attr('href')+\"?cnetSecureRedirectUrl=\"+url;\r\n// $('.logonLink').attr('href',encodeURI(finalUrl));\r\n$(document).ready(function(event) {\r\n\tvar url = window.location.href ;\r\n\t$('input[name=\"cnetSecureRedirectUrl\"]').val(encodeURIComponent(url));\r\n});\r\n\r\n</script><div id=\"mainContent\" class=\"flexbox-main\">\r\n\t\t<div class=\"subContent\">\r\n\t\t\t<div class=\"left col-xs-12 col-sm-12 col-md-12 col-lg-12\">\r\n\t\t\t\t<div class=\"alert alert-danger\">\r\n\t\t\t\t\t<i class=\"glyphicon glyphicon-info-sign\"></i><span\r\n\t\t\t\t\t\tstyle=\"valign: center\">&nbsp;&nbsp;THE FOLLOWING ERROR(S) OCCURRED:</span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"left col-xs-12 col-sm-12 col-md-12 col-lg-12\">\r\n\t\t\t\t<div class=\"text-left\">\r\n\t\t\t\t<span class=\"errormessage\">Content type 'application/x-www-form-urlencoded' not supported</span>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<style type=\"text/css\">\r\n\t.footerbar{\r\n\t\tborder-top: 1px solid #cbcbcb;\r\n\t}\r\n\t.footerWrapper{\r\n\t\tposition: fixed;\r\n \tbottom: 0px;\r\n \t\twidth: 100%;\r\n \tbackground: #f8f8f8;\r\n\t}\r\n\t\r\n\t@media print {\r\n\t.footerbar{\r\n\t\tcontent: none !important;\r\n\t}\r\n\t.footerWrapper{\r\n\t\tcontent: none !important;\r\n\t}\r\n\t.visible-xs{\r\n\tcontent: none !important;\r\n\t}\r\n\t}\r\n</style>\r\n<div class=\"footerWrapper\">\r\n\t<div id=\"footer\" class=\"hidden-xs\">\r\n\t\t<div class=\"footerbar\"></div>\r\n\t\t<div class=\"footerContent \">\r\n\t\t\t<div style=\"font-weight: normal; text-align: left;\" class=\"col-sm-6 col-md-6\">\r\n\t\t\tCase.net Version 1.1.19.9</div>\r\n\t\t\t<div style=\"font-weight: normal; text-align: right;\" class=\"col-sm-6 col-md-6\">Released 04/27/2026</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<div id=\"footer-xs\" class=\"visible-xs\">\r\n\t\t<div class=\"footerContent-xs \">\r\n\t\t\t<div style=\"font-weight: normal;\"> Version 1.1.19.9 - Released 04/27/2026</div>\r\n\t\t</div>\r\n\t</div>\r\n</div>\r\n</body>\r\n</html>\r\n"
- },
- "payment": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "{\"courtId\":\"OSCDB0024_SUP\",\"caseNumber\":\"SC97597\",\"protectionOrder\":false,\"locnCode\":\"SC\",\"courtCode\":\"SC\",\"disposed\":true,\"legalFileAccepted\":false,\"paperAccepted\":false,\"confidential\":false,\"displayJudgeNotes\":false,\"caseNoteCount\":0,\"displayLegalFileViewer\":false,\"displayFileViewer\":false,\"canUserSeePublicDocuments\":false,\"canUserSeeCaseDocuments\":false,\"canUserSeeEnoticeHistory\":false,\"canSelectDocket\":false,\"canSeeEcfLinks\":false,\"canSeeLegalFileLinks\":false,\"isTicket\":false,\"dismissed\":\"F\"}",
- "parsed": {
- "courtId": "OSCDB0024_SUP",
- "caseNumber": "SC97597",
- "protectionOrder": false,
- "locnCode": "SC",
- "courtCode": "SC",
- "disposed": true,
- "legalFileAccepted": false,
- "paperAccepted": false,
- "confidential": false,
- "displayJudgeNotes": false,
- "caseNoteCount": 0,
- "displayLegalFileViewer": false,
- "displayFileViewer": false,
- "canUserSeePublicDocuments": false,
- "canUserSeeCaseDocuments": false,
- "canUserSeeEnoticeHistory": false,
- "canSelectDocket": false,
- "canSeeEcfLinks": false,
- "canSeeLegalFileLinks": false,
- "isTicket": false,
- "dismissed": "F"
- }
- },
- "enotice": {
- "status": 200,
- "ct": "text/plain;charset=ISO-8859-1",
- "text": "[{\"jisPartyId\":\"63780\",\"firstName\":\"Jeremy\",\"middleName\":\"Joseph\",\"lastName\":\"Deeken\",\"fullName\":\"Jeremy Joseph Deeken\",\"sentDate\":\"03/05/2019\",\"sentDateString\":\"03/05/2019 04:35 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"65497\",\"firstName\":\"Lance\",\"middleName\":\"Lamont\",\"lastName\":\"Bond\",\"fullName\":\"Lance Lamont Bond\",\"sentDate\":\"03/05/2019\",\"sentDateString\":\"03/05/2019 04:35 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"63780\",\"firstName\":\"Jeremy\",\"middleName\":\"Joseph\",\"lastName\":\"Deeken\",\"fullName\":\"Jeremy Joseph Deeken\",\"sentDate\":\"12/17/2018\",\"sentDateString\":\"12/17/2018 06:06 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"63780\",\"firstName\":\"Jeremy\",\"middleName\":\"Joseph\",\"lastName\":\"Deeken\",\"fullName\":\"Jeremy Joseph Deeken\",\"sentDate\":\"12/17/2018\",\"sentDateString\":\"12/17/2018 06:06 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"63780\",\"firstName\":\"Jeremy\",\"middleName\":\"Joseph\",\"lastName\":\"Deeken\",\"fullName\":\"Jeremy Joseph Deeken\",\"sentDate\":\"12/17/2018\",\"sentDateString\":\"12/17/2018 06:06 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"65497\",\"firstName\":\"Lance\",\"middleName\":\"Lamont\",\"lastName\":\"Bond\",\"fullName\":\"Lance Lamont Bond\",\"sentDate\":\"12/17/2018\",\"sentDateString\":\"12/17/2018 06:06 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"65497\",\"firstName\":\"Lance\",\"middleName\":\"Lamont\",\"lastName\":\"Bond\",\"fullName\":\"Lance Lamont Bond\",\"sentDate\":\"12/17/2018\",\"sentDateString\":\"12/17/2018 06:06 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false},{\"jisPartyId\":\"65497\",\"firstName\":\"Lance\",\"middleName\":\"Lamont\",\"lastName\":\"Bond\",\"fullName\":\"Lance Lamont Bond\",\"sentDate\":\"12/17/2018\",\"sentDateString\":\"12/17/2018 06:06 PM\",\"email\":\"[email protected]\",\"hasEnotice\":false}]",
- "parsed": [
- {
- "jisPartyId": "63780",
- "firstName": "Jeremy",
- "middleName": "Joseph",
- "lastName": "Deeken",
- "fullName": "Jeremy Joseph Deeken",
- "sentDate": "03/05/2019",
- "sentDateString": "03/05/2019 04:35 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "65497",
- "firstName": "Lance",
- "middleName": "Lamont",
- "lastName": "Bond",
- "fullName": "Lance Lamont Bond",
- "sentDate": "03/05/2019",
- "sentDateString": "03/05/2019 04:35 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "63780",
- "firstName": "Jeremy",
- "middleName": "Joseph",
- "lastName": "Deeken",
- "fullName": "Jeremy Joseph Deeken",
- "sentDate": "12/17/2018",
- "sentDateString": "12/17/2018 06:06 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "63780",
- "firstName": "Jeremy",
- "middleName": "Joseph",
- "lastName": "Deeken",
- "fullName": "Jeremy Joseph Deeken",
- "sentDate": "12/17/2018",
- "sentDateString": "12/17/2018 06:06 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "63780",
- "firstName": "Jeremy",
- "middleName": "Joseph",
- "lastName": "Deeken",
- "fullName": "Jeremy Joseph Deeken",
- "sentDate": "12/17/2018",
- "sentDateString": "12/17/2018 06:06 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "65497",
- "firstName": "Lance",
- "middleName": "Lamont",
- "lastName": "Bond",
- "fullName": "Lance Lamont Bond",
- "sentDate": "12/17/2018",
- "sentDateString": "12/17/2018 06:06 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "65497",
- "firstName": "Lance",
- "middleName": "Lamont",
- "lastName": "Bond",
- "fullName": "Lance Lamont Bond",
- "sentDate": "12/17/2018",
- "sentDateString": "12/17/2018 06:06 PM",
- "email": "[email protected]",
- "hasEnotice": false
- },
- {
- "jisPartyId": "65497",
- "firstName": "Lance",
- "middleName": "Lamont",
- "lastName": "Bond",
- "fullName": "Lance Lamont Bond",
- "sentDate": "12/17/2018",
- "sentDateString": "12/17/2018 06:06 PM",
- "email": "[email protected]",
- "hasEnotice": false
- }
- ]
- }
-}
\ No newline at end of file
diff --git a/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py b/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py
index c9e830143..9308911f9 100644
--- a/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py
+++ b/fincept-qt/scripts/Analytics/backtesting/base/fincept_strategy_runner.py
@@ -43,7 +43,16 @@ class FinceptStrategyRunner:
if not info:
raise ValueError(f"Strategy {strategy_id} not found in registry")
- strategy_path = self.strategies_dir / info['path']
+ # Containment check. `Path / value` silently ESCAPES the root when
+ # `value` is absolute ("C:/x", "/etc/x") or walks up ("../../x"), and
+ # the code below exec()s whatever it reads. Resolve first, then assert
+ # the result is still under strategies_dir.
+ root = self.strategies_dir.resolve()
+ strategy_path = (root / info['path']).resolve()
+ if not strategy_path.is_relative_to(root):
+ raise ValueError(
+ f"Strategy path escapes the strategies directory: {info['path']}"
+ )
if not strategy_path.exists():
raise FileNotFoundError(f"Strategy file not found: {strategy_path}")
diff --git a/fincept-qt/scripts/Analytics/portfolioManagement/ffn_analysis.py b/fincept-qt/scripts/Analytics/portfolioManagement/ffn_analysis.py
deleted file mode 100644
index 2e205e13a..000000000
--- a/fincept-qt/scripts/Analytics/portfolioManagement/ffn_analysis.py
+++ /dev/null
@@ -1,357 +0,0 @@
-"""
-FFN (Financial Functions) Analysis — Deep analytics per symbol.
-Input: JSON via stdin: {"symbols": ["AAPL","MSFT"], "weights": {"AAPL": 0.6, "MSFT": 0.4}}
-Output: JSON to stdout with per-symbol stats, rebased series, drawdown series,
- rolling correlations, and portfolio optimisation weights.
-"""
-import sys
-import json
-import numpy as np
-
-
-def convert_numpy(obj):
- if isinstance(obj, dict):
- return {k: convert_numpy(v) for k, v in obj.items()}
- elif isinstance(obj, (list, tuple)):
- return [convert_numpy(v) for v in obj]
- elif isinstance(obj, (np.integer,)):
- return int(obj)
- elif isinstance(obj, (np.floating,)):
- v = float(obj)
- if np.isnan(v) or np.isinf(v):
- return 0.0
- return v
- elif isinstance(obj, np.ndarray):
- return [convert_numpy(x) for x in obj]
- elif isinstance(obj, float):
- if np.isnan(obj) or np.isinf(obj):
- return 0.0
- return obj
-
-
-def max_streak(series):
- max_s, cur = 0, 0
- for v in series:
- if v:
- cur += 1
- max_s = max(max_s, cur)
- else:
- cur = 0
- return max_s
-
-
-def portfolio_stats(close_df, weights_arr, symbols):
- """Compute blended portfolio stats from a close DataFrame and weight array."""
- import pandas as pd
- w = np.array(weights_arr)
- w = w / w.sum()
- port_returns = (close_df.pct_change().dropna() * w).sum(axis=1)
- total_ret = float((1 + port_returns).prod() - 1)
- n = len(port_returns)
- cagr = float((1 + total_ret) ** (252.0 / max(n, 1)) - 1)
- vol = float(port_returns.std() * np.sqrt(252))
- sharpe = float((cagr - 0.04) / vol) if vol > 0 else 0.0
- cum = (1 + port_returns).cumprod()
- peak = cum.expanding().max()
- dd = (cum - peak) / peak
- max_dd = float(dd.min())
- return {
- "total_return": total_ret,
- "cagr": cagr,
- "volatility": vol,
- "sharpe": sharpe,
- "max_drawdown": max_dd,
- }
-
-
-def compute_ffn(symbols, weights, period="1y"):
- import yfinance as yf
- import pandas as pd
-
- data = yf.download(symbols, period=period, interval="1d", progress=False, auto_adjust=True)
- if data is None or data.empty:
- return {"error": "Could not fetch price data"}
-
- # Normalise to a Close DataFrame regardless of yfinance version
- if isinstance(data.columns, pd.MultiIndex):
- if "Close" in data.columns.get_level_values(0):
- close = data["Close"]
- elif "Adj Close" in data.columns.get_level_values(0):
- close = data["Adj Close"]
- else:
- close = data.iloc[:, 0:len(symbols)]
- else:
- close = data[["Close"]] if "Close" in data.columns else data
-
- if not isinstance(close, pd.DataFrame):
- close = pd.DataFrame(close)
-
- # If single symbol yfinance returns a Series — wrap it
- if isinstance(close, pd.Series):
- close = close.to_frame(name=symbols[0])
-
- # Ensure column names match symbols when single symbol
- if len(symbols) == 1 and list(close.columns) != symbols:
- close.columns = [symbols[0]]
-
- result = {}
-
- # ── Per-symbol stats ──────────────────────────────────────────────────────
- for sym in symbols:
- if sym not in close.columns:
- continue
- prices = close[sym].dropna()
- if len(prices) < 2:
- continue
-
- returns = prices.pct_change().dropna()
- cumulative = (1 + returns).cumprod()
-
- total_ret = float(cumulative.iloc[-1] - 1)
- ann_ret = float((1 + total_ret) ** (252.0 / max(len(returns), 1)) - 1)
- ann_vol = float(returns.std() * np.sqrt(252))
- peak = prices.expanding().max()
- dd = (prices - peak) / peak
- max_dd = float(dd.min())
- monthly_ret = float(returns.mean() * 21)
- pos = (returns > 0).astype(int).tolist()
- neg = (returns < 0).astype(int).tolist()
-
- result[sym] = {
- "total_return": total_ret,
- "annualized_return": ann_ret,
- "annualized_volatility": ann_vol,
- "max_drawdown": max_dd,
- "sharpe_ratio": float((ann_ret - 0.04) / ann_vol) if ann_vol > 0 else 0.0,
- "current_price": float(prices.iloc[-1]),
- "start_price": float(prices.iloc[0]),
- "best_day": float(returns.max()),
- "worst_day": float(returns.min()),
- "avg_daily_return": float(returns.mean()),
- "positive_days": int((returns > 0).sum()),
- "negative_days": int((returns < 0).sum()),
- "max_win_streak": max_streak(pos),
- "max_loss_streak": max_streak(neg),
- "avg_monthly_return": monthly_ret,
- "skewness": float(returns.skew()),
- "kurtosis": float(returns.kurtosis()),
- }
-
- # Only keep symbols we actually computed
- valid_syms = [s for s in symbols if s in result]
- if not valid_syms:
- return result
-
- valid_close = close[valid_syms].dropna(how="all")
- LIMIT = 252
-
- # ── Rebased price series ──────────────────────────────────────────────────
- rebased_out = {}
- try:
- import ffn
- rebased_df = ffn.rebase(valid_close.dropna(), 100)
- rebased_df = rebased_df.tail(LIMIT)
- for sym in valid_syms:
- if sym in rebased_df.columns:
- series = rebased_df[sym].dropna()
- rebased_out[sym] = {
- idx.strftime("%Y-%m-%d"): float(v)
- for idx, v in series.items()
- if not (isinstance(v, float) and (np.isnan(v) or np.isinf(v)))
- }
- except Exception:
- # ffn not available — compute manually
- try:
- base = valid_close.dropna().tail(LIMIT)
- for sym in valid_syms:
- if sym not in base.columns:
- continue
- s = base[sym].dropna()
- if s.empty:
- continue
- rebased = s / s.iloc[0] * 100.0
- rebased_out[sym] = {
- idx.strftime("%Y-%m-%d"): float(v)
- for idx, v in rebased.items()
- if not (isinstance(v, float) and (np.isnan(v) or np.isinf(v)))
- }
- except Exception:
- pass
-
- result["rebased"] = rebased_out
-
- # ── Drawdown series ───────────────────────────────────────────────────────
- drawdown_out = {}
- try:
- import ffn
- for sym in valid_syms:
- if sym not in valid_close.columns:
- continue
- prices_s = valid_close[sym].dropna()
- if len(prices_s) < 2:
- continue
- dd_series = ffn.to_drawdown_series(prices_s).tail(LIMIT)
- drawdown_out[sym] = {
- idx.strftime("%Y-%m-%d"): float(v)
- for idx, v in dd_series.items()
- if not (isinstance(v, float) and (np.isnan(v) or np.isinf(v)))
- }
- except Exception:
- try:
- for sym in valid_syms:
- if sym not in valid_close.columns:
- continue
- prices_s = valid_close[sym].dropna()
- if len(prices_s) < 2:
- continue
- peak = prices_s.expanding().max()
- dd_s = ((prices_s - peak) / peak).tail(LIMIT)
- drawdown_out[sym] = {
- idx.strftime("%Y-%m-%d"): float(v)
- for idx, v in dd_s.items()
- if not (isinstance(v, float) and (np.isnan(v) or np.isinf(v)))
- }
- except Exception:
- pass
-
- result["drawdown_series"] = drawdown_out
-
- # ── Rolling correlations ──────────────────────────────────────────────────
- rolling_out = {}
- try:
- if len(valid_syms) >= 2:
- ret_df = valid_close[valid_syms].pct_change().dropna()
- WINDOW = 60
- # rolling().corr() returns a MultiIndex series: (date, sym) -> corr_with_sym
- rolling_corr = ret_df.rolling(WINDOW).corr()
- for i in range(len(valid_syms)):
- for j in range(i + 1, len(valid_syms)):
- s1, s2 = valid_syms[i], valid_syms[j]
- key = f"{s1}_{s2}"
- try:
- # Select the cross-correlation column
- pair_series = rolling_corr.xs(s2, level=1)[s1].dropna().tail(LIMIT)
- rolling_out[key] = {
- idx.strftime("%Y-%m-%d"): float(v)
- for idx, v in pair_series.items()
- if not (isinstance(v, float) and (np.isnan(v) or np.isinf(v)))
- }
- except Exception:
- pass
- except Exception:
- pass
-
- result["rolling_corr"] = rolling_out
-
- # ── Portfolio optimisation ────────────────────────────────────────────────
- opt_out = {}
- try:
- if len(valid_syms) >= 2:
- ret_df = valid_close[valid_syms].pct_change().dropna()
- n = len(valid_syms)
-
- if len(ret_df) >= 30:
- # Equal weights
- equal_w = {s: round(1.0 / n, 6) for s in valid_syms}
-
- # Current weights (passed in from C++)
- cur_w_arr = np.array([weights.get(s, 1.0 / n) for s in valid_syms])
- cur_w_arr = cur_w_arr / cur_w_arr.sum()
- current_w = {s: round(float(cur_w_arr[i]), 6) for i, s in enumerate(valid_syms)}
-
- # ERC weights via ffn
- erc_w = equal_w.copy()
- try:
- import ffn
- erc_arr = ffn.calc_erc_weights(
- ret_df,
- covar_method="ledoit-wolf",
- risk_parity_method="ccd",
- maximum_iterations=100,
- tolerance=1e-8,
- )
- erc_w = {s: round(float(erc_arr[i]), 6) for i, s in enumerate(valid_syms)}
- except Exception:
- pass
-
- # Inverse-vol weights via ffn
- inv_vol_w = equal_w.copy()
- try:
- import ffn
- iv_arr = ffn.calc_inv_vol_weights(ret_df)
- inv_vol_w = {s: round(float(iv_arr[i]), 6) for i, s in enumerate(valid_syms)}
- except Exception:
- try:
- vols = ret_df.std()
- inv_v = 1.0 / vols
- iv_norm = inv_v / inv_v.sum()
- inv_vol_w = {s: round(float(iv_norm[s]), 6) for s in valid_syms}
- except Exception:
- pass
-
- # Portfolio stats for each weight set
- def w_arr(w_dict):
- return [w_dict.get(s, 0.0) for s in valid_syms]
-
- stats = {}
- for name, wd in [("erc", erc_w), ("inv_vol", inv_vol_w),
- ("equal", equal_w), ("current", current_w)]:
- try:
- stats[name] = portfolio_stats(valid_close[valid_syms].dropna(),
- w_arr(wd), valid_syms)
- except Exception:
- stats[name] = {
- "total_return": 0.0, "cagr": 0.0,
- "volatility": 0.0, "sharpe": 0.0, "max_drawdown": 0.0,
- }
-
- opt_out = {
- "erc": erc_w,
- "inv_vol": inv_vol_w,
- "equal": equal_w,
- "current": current_w,
- "stats": stats,
- }
- except Exception:
- pass
-
- result["optimization"] = opt_out
-
- return result
-
-
-def main():
- stdin_data = sys.stdin.read()
- if not stdin_data.strip():
- print(json.dumps({"error": "No input data"}))
- return
-
- try:
- params = json.loads(stdin_data)
- except Exception as exc:
- print(json.dumps({"error": f"JSON parse error: {exc}"}))
- return
-
- symbols = params.get("symbols", [])
- if not symbols:
- print(json.dumps({"error": "No symbols provided"}))
- return
-
- # weights dict: symbol -> fraction (0-1); fall back to equal weight
- raw_weights = params.get("weights", {})
- n = len(symbols)
- weights = {}
- for s in symbols:
- weights[s] = float(raw_weights.get(s, 1.0 / n))
- total_w = sum(weights.values())
- if total_w > 0:
- weights = {s: v / total_w for s, v in weights.items()}
- else:
- weights = {s: 1.0 / n for s in symbols}
-
- result = compute_ffn(symbols, weights)
- print(json.dumps(convert_numpy(result)))
-
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/cnstats_data.py b/fincept-qt/scripts/cnstats_data.py
index 9adb2274d..557d5ada5 100644
--- a/fincept-qt/scripts/cnstats_data.py
+++ b/fincept-qt/scripts/cnstats_data.py
@@ -148,9 +148,13 @@ def easyquery(m: str = 'QueryData', dbcode: str = 'hgyd', rowcode: str = 'zb',
if wdcode:
obj['wdcode'] = wdcode
- # Exact request handling from cnstats
- requests.packages.urllib3.disable_warnings()
- response = requests.post(url, data=obj, headers=API_HEADERS, verify=False, timeout=TIMEOUT)
+ # TLS verification is ON. The upstream cnstats snippet this mirrors used
+ # `verify=False` + `disable_warnings()`; that silently accepted any
+ # certificate AND hid the warning, so a MITM could substitute arbitrary
+ # content that we then parse and render as official economic data.
+ # If data.stats.gov.cn ever presents a chain your store lacks, pin the
+ # CA explicitly (verify="/path/to/ca-bundle.pem") — never disable it.
+ response = requests.post(url, data=obj, headers=API_HEADERS, timeout=TIMEOUT)
response.raise_for_status()
return response.json()
diff --git a/fincept-qt/scripts/country_codes_only.txt b/fincept-qt/scripts/country_codes_only.txt
deleted file mode 100644
index c45519a2b..000000000
--- a/fincept-qt/scripts/country_codes_only.txt
+++ /dev/null
@@ -1,266 +0,0 @@
- "999": "999", # Not Applicable
- "abw": "533", # Aruba
- "afg": "004", # Afghanistan
- "ago": "024", # Angola
- "aia": "660", # Anguila
- "alb": "008", # Albania
- "and": "020", # Andorra
- "ant": "530", # Netherlands Antilles
- "are": "784", # United Arab Emirates
- "arg": "032", # Argentina
- "arm": "051", # Armenia
- "asm": "016", # American Samoa
- "ata": "010", # Antarctica
- "atf": "260", # Fr. So. Ant. Tr
- "atg": "028", # Antigua and Barbuda
- "aus": "036", # Australia
- "aut": "040", # Austria
- "aze": "031", # Azerbaijan
- "bat": "080", # Br. Antr. Terr
- "bdi": "108", # Burundi
- "bel": "056", # Belgium
- "ben": "204", # Benin
- "bes": "535", # Bonaire
- "bfa": "854", # Burkina Faso
- "bgd": "050", # Bangladesh
- "bgr": "100", # Bulgaria
- "bhr": "048", # Bahrain
- "bhs": "044", # Bahamas, The
- "bih": "070", # Bosnia and Herzegovina
- "blm": "652", # Saint Barth�lemy
- "blr": "112", # Belarus
- "blx": "058", # Belgium-Luxembourg
- "blz": "084", # Belize
- "bmu": "060", # Bermuda
- "bol": "068", # Bolivia
- "bra": "076", # Brazil
- "brb": "052", # Barbados
- "brn": "096", # Brunei
- "btn": "064", # Bhutan
- "bun": "837", # Bunkers
- "bvt": "074", # Bouvet Island
- "bwa": "072", # Botswana
- "caf": "140", # Central African Republic
- "can": "124", # Canada
- "cck": "166", # Cocos (Keeling) Islands
- "che": "756", # Switzerland
- "chl": "152", # Chile
- "chn": "156", # China
- "civ": "384", # Cote d'Ivoire
- "cmr": "120", # Cameroon
- "cog": "178", # Congo, Rep.
- "cok": "184", # Cook Islands
- "col": "170", # Colombia
- "com": "174", # Comoros
- "cpv": "132", # Cape Verde
- "cri": "188", # Costa Rica
- "csk": "200", # Czechoslovakia
- "cub": "192", # Cuba
- "cuw": "531", # Cura�ao
- "cxr": "162", # Christmas Island
- "cym": "136", # Cayman Islands
- "cyp": "196", # Cyprus
- "cze": "203", # Czech Republic
- "ddr": "278", # German Democratic Republic
- "deu": "276", # Germany
- "dji": "262", # Djibouti
- "dma": "212", # Dominica
- "dnk": "208", # Denmark
- "dom": "214", # Dominican Republic
- "dza": "012", # Algeria
- "eas": "EAS", # East Asia & Pacific
- "ecs": "ECS", # Europe & Central Asia
- "ecu": "218", # Ecuador
- "egy": "818", # Egypt, Arab Rep.
- "eri": "232", # Eritrea
- "esh": "732", # Western Sahara
- "esp": "724", # Spain
- "est": "233", # Estonia
- "etf": "230", # Ethiopia(includes Eritrea)
- "eth": "231", # Ethiopia(excludes Eritrea)
- "fin": "246", # Finland
- "fji": "242", # Fiji
- "flk": "238", # Falkland Island
- "fra": "250", # France
- "fre": "838", # Free Zones
- "fro": "234", # Faeroe Islands
- "fsm": "583", # Micronesia, Fed. Sts.
- "gab": "266", # Gabon
- "gbr": "826", # United Kingdom
- "geo": "268", # Georgia
- "gha": "288", # Ghana
- "gib": "292", # Gibraltar
- "gin": "324", # Guinea
- "glp": "312", # Guadeloupe
- "gmb": "270", # Gambia, The
- "gnb": "624", # Guinea-Bissau
- "gnq": "226", # Equatorial Guinea
- "grc": "300", # Greece
- "grd": "308", # Grenada
- "grl": "304", # Greenland
- "gtm": "320", # Guatemala
- "guf": "254", # French Guiana
- "gum": "316", # Guam
- "guy": "328", # Guyana
- "hkg": "344", # Hong Kong, China
- "hmd": "334", # Heard Island and McDonald Isla
- "hnd": "340", # Honduras
- "hrv": "191", # Croatia
- "hti": "332", # Haiti
- "hun": "348", # Hungary
- "idn": "360", # Indonesia
- "ind": "356", # India
- "iot": "086", # British Indian Ocean Ter.
- "irl": "372", # Ireland
- "irn": "364", # Iran, Islamic Rep.
- "irq": "368", # Iraq
- "isl": "352", # Iceland
- "isr": "376", # Israel
- "ita": "380", # Italy
- "jam": "388", # Jamaica
- "jor": "400", # Jordan
- "jpn": "392", # Japan
- "kaz": "398", # Kazakhstan
- "ken": "404", # Kenya
- "kgz": "417", # Kyrgyz Republic
- "khm": "116", # Cambodia
- "kir": "296", # Kiribati
- "kna": "659", # St. Kitts and Nevis
- "kor": "410", # Korea, Rep.
- "kwt": "414", # Kuwait
- "lao": "418", # Lao PDR
- "lbn": "422", # Lebanon
- "lbr": "430", # Liberia
- "lby": "434", # Libya
- "lca": "662", # St. Lucia
- "lcn": "LCN", # Latin America & Caribbean
- "lka": "144", # Sri Lanka
- "lso": "426", # Lesotho
- "ltu": "440", # Lithuania
- "lux": "442", # Luxembourg
- "lva": "428", # Latvia
- "mac": "446", # Macao
- "mar": "504", # Morocco
- "mco": "492", # Monaco
- "mda": "498", # Moldova
- "mdg": "450", # Madagascar
- "mdv": "462", # Maldives
- "mea": "MEA", # Middle East, North Africa, Afghanistan & Pakistan
- "mex": "484", # Mexico
- "mhl": "584", # Marshall Islands
- "mkd": "807", # North Macedonia
- "mli": "466", # Mali
- "mlt": "470", # Malta
- "mmr": "104", # Myanmar
- "mng": "496", # Mongolia
- "mnp": "580", # Northern Mariana Islands
- "mnt": "499", # Montenegro
- "moz": "508", # Mozambique
- "mrt": "478", # Mauritania
- "msr": "500", # Montserrat
- "mtq": "474", # Martinique
- "mus": "480", # Mauritius
- "mwi": "454", # Malawi
- "mys": "458", # Malaysia
- "myt": "175", # Mayotte
- "nac": "NAC", # North America
- "nam": "516", # Namibia
- "ncl": "540", # New Caledonia
- "ner": "562", # Niger
- "nfk": "574", # Norfolk Island
- "nga": "566", # Nigeria
- "nic": "558", # Nicaragua
- "niu": "570", # Niue
- "nld": "528", # Netherlands
- "nor": "578", # Norway
- "npl": "524", # Nepal
- "nru": "520", # Nauru
- "nze": "536", # Neutral Zone
- "nzl": "554", # New Zealand
- "oas": "490", # Other Asia, nes
- "omn": "512", # Oman
- "pak": "586", # Pakistan
- "pan": "591", # Panama
- "pce": "582", # Pacific Islands
- "pcn": "612", # Pitcairn
- "per": "604", # Peru
- "phl": "608", # Philippines
- "plw": "585", # Palau
- "png": "598", # Papua New Guinea
- "pol": "616", # Poland
- "prk": "408", # Korea, Dem. Rep.
- "prt": "620", # Portugal
- "pry": "600", # Paraguay
- "pse": "275", # Occ.Pal.Terr
- "pyf": "258", # French Polynesia
- "qat": "634", # Qatar
- "reu": "638", # Reunion
- "rom": "642", # Romania
- "rus": "643", # Russian Federation
- "rwa": "646", # Rwanda
- "sas": "SAS", # South Asia
- "sau": "682", # Saudi Arabia
- "sdn": "736", # Fm Sudan
- "sen": "686", # Senegal
- "ser": "891", # Serbia, FR(Serbia/Montenegro)
- "sgp": "702", # Singapore
- "sgs": "239", # South Georgia and the South Sa
- "shn": "654", # Saint Helena
- "slb": "090", # Solomon Islands
- "sle": "694", # Sierra Leone
- "slv": "222", # El Salvador
- "smr": "674", # San Marino
- "som": "706", # Somalia
- "spe": "839", # Special Categories
- "spm": "666", # Saint Pierre and Miquelon
- "ssd": "728", # South Sudan
- "ssf": "SSF", # Sub-Saharan Africa
- "stp": "678", # Sao Tome and Principe
- "sud": "729", # Sudan
- "sur": "740", # Suriname
- "svk": "703", # Slovak Republic
- "svn": "705", # Slovenia
- "svu": "810", # Soviet Union
- "swe": "752", # Sweden
- "swz": "748", # Eswatini
- "sxm": "534", # Saint Maarten (Dutch part)
- "syc": "690", # Seychelles
- "syr": "760", # Syrian Arab Republic
- "tca": "796", # Turks and Caicos Isl.
- "tcd": "148", # Chad
- "tgo": "768", # Togo
- "tha": "764", # Thailand
- "tjk": "762", # Tajikistan
- "tkl": "772", # Tokelau
- "tkm": "795", # Turkmenistan
- "tmp": "626", # East Timor
- "ton": "776", # Tonga
- "tto": "780", # Trinidad and Tobago
- "tun": "788", # Tunisia
- "tur": "792", # Turkey
- "tuv": "798", # Tuvalu
- "tza": "834", # Tanzania
- "uga": "800", # Uganda
- "ukr": "804", # Ukraine
- "umi": "581", # United States Minor Outlying I
- "uns": "898", # Unspecified
- "ury": "858", # Uruguay
- "usa": "840", # United States
- "usp": "849", # Us Msc.Pac.I
- "uzb": "860", # Uzbekistan
- "vat": "336", # Holy See
- "vct": "670", # St. Vincent and the Grenadines
- "ven": "862", # Venezuela
- "vgb": "092", # British Virgin Islands
- "vnm": "704", # Vietnam
- "vut": "548", # Vanuatu
- "wld": "000", # World
- "wlf": "876", # Wallis and Futura Isl.
- "wsm": "882", # Samoa
- "ydr": "720", # Yemen Democratic
- "yem": "887", # Yemen
- "yug": "890", # Yugoslavia,FR(Serbia/Montenegr
- "zaf": "710", # South Africa
- "zar": "180", # Congo, Dem. Rep.
- "zmb": "894", # Zambia
- "zwe": "716", # Zimbabwe
diff --git a/fincept-qt/scripts/debug_out.txt b/fincept-qt/scripts/debug_out.txt
deleted file mode 100644
index d3379b8e9..000000000
--- a/fincept-qt/scripts/debug_out.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-starting
-200 OK
-{"success": true, "message": "Success", "data": {"original": {"amount": 100.0, "currency": "USD"}, "converted": {"amount": 92.0, "currency": "EUR"}, "rate": 0.92}}
-done
diff --git a/fincept-qt/scripts/exchange/broker_ws_bridge.py b/fincept-qt/scripts/exchange/broker_ws_bridge.py
index 209dfe41b..fc4dacddc 100644
--- a/fincept-qt/scripts/exchange/broker_ws_bridge.py
+++ b/fincept-qt/scripts/exchange/broker_ws_bridge.py
@@ -6,8 +6,13 @@ Imports the openalgo broker streaming adapters directly, captures their
ZMQ output, and re-emits normalized JSON lines to stdout.
Usage:
- python broker_ws_bridge.py <broker> <api_key> <access_token> \
- [user_id] [--symbols SYM:EXCH:TOKEN ...]
+ BROKER_API_KEY=... BROKER_ACCESS_TOKEN=... [BROKER_FEED_TOKEN=...] \
+ python broker_ws_bridge.py <broker> "" "" [user_id] \
+ [--symbols SYM:EXCH:TOKEN ...]
+
+Credentials come from the environment — NEVER from argv, which is readable by
+any process running as the same user. The positional api_key/access_token slots
+remain only as a legacy fallback and are passed empty by the terminal.
Where TOKEN is the broker-specific instrument token (int).
If no TOKEN is known, pass 0 and we fall back to a symbol-only subscribe.
@@ -384,24 +389,58 @@ def _create_adapter(broker: str):
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("broker", help="Broker name e.g. zerodha")
- p.add_argument("api_key", help="API key")
- p.add_argument("access_token", help="Access/auth token")
+ # Credentials are read from the environment (see read_credentials). These
+ # positionals only exist so an older caller that still passes them keeps
+ # working; the current caller sends empty placeholders.
+ p.add_argument("api_key", nargs="?", default="", help="DEPRECATED — use BROKER_API_KEY")
+ p.add_argument("access_token", nargs="?", default="", help="DEPRECATED — use BROKER_ACCESS_TOKEN")
p.add_argument("user_id", nargs="?", default="", help="User/client ID")
p.add_argument("--feed-token", default="", dest="feed_token",
- help="Separate feed token (AngelOne feedToken)")
+ help="DEPRECATED — use BROKER_FEED_TOKEN")
p.add_argument("--symbols", nargs="*", default=[],
help="Symbols as SYMBOL:EXCHANGE[:TOKEN] e.g. RELIANCE:NSE:738561")
return p.parse_args()
+def read_credentials(args):
+ """Resolve broker credentials: environment first, argv as legacy fallback.
+
+ Credentials must NOT travel in argv. A process command line is readable by
+ any process running as the same user (Win32_Process.CommandLine via WMI on
+ Windows without elevation, /proc/<pid>/cmdline on Linux) and is captured by
+ crash dumps and EDR telemetry. These tokens stay valid for the whole
+ trading session, so leaking them defeats the terminal's encrypted
+ credential storage completely.
+
+ Returns (api_key, access_token, feed_token, user_id).
+ """
+ api_key = os.environ.get("BROKER_API_KEY", "") or args.api_key
+ access_token = os.environ.get("BROKER_ACCESS_TOKEN", "") or args.access_token
+ feed_token = (os.environ.get("BROKER_FEED_TOKEN", "")
+ or args.feed_token
+ or access_token) # AngelOne-style separate feed token; else reuse
+ # user_id is a client code, not a secret. Falling back to api_key here (in
+ # the child process) keeps the key out of the parent's argv.
+ user_id = os.environ.get("BROKER_USER_ID", "") or args.user_id or api_key
+
+ if not os.environ.get("BROKER_ACCESS_TOKEN") and args.access_token:
+ print("WARNING: broker credentials received via argv — they are readable "
+ "by any process running as this user. Pass BROKER_API_KEY / "
+ "BROKER_ACCESS_TOKEN / BROKER_FEED_TOKEN in the environment.",
+ file=sys.stderr)
+
+ return api_key, access_token, feed_token, user_id
+
+
def main():
args = parse_args()
- broker = args.broker.lower()
- api_key = args.api_key
- access_token = args.access_token
- user_id = args.user_id or api_key
- feed_token = args.feed_token or access_token # fallback to access_token if not provided
+ broker = args.broker.lower()
+ api_key, access_token, feed_token, user_id = read_credentials(args)
+
+ if not api_key or not access_token:
+ emit_error(broker, "Missing broker credentials (BROKER_API_KEY / BROKER_ACCESS_TOKEN)")
+ sys.exit(1)
# Parse symbol list: "RELIANCE:NSE:738561" → ("RELIANCE","NSE","738561")
symbols = []
diff --git a/fincept-qt/scripts/exchange/driver_stderr.txt b/fincept-qt/scripts/exchange/driver_stderr.txt
deleted file mode 100644
index e69de29bb..000000000
diff --git a/fincept-qt/scripts/exchange/totp_gen.py b/fincept-qt/scripts/exchange/totp_gen.py
index 0c46d6d7f..690a2a279 100644
--- a/fincept-qt/scripts/exchange/totp_gen.py
+++ b/fincept-qt/scripts/exchange/totp_gen.py
@@ -1,15 +1,67 @@
"""Generate current TOTP code from a base32 secret.
-Usage: totp_gen.py <base32_secret>
+
+The secret is the broker's PERMANENT TOTP seed, not a one-time code — anyone
+who reads it owns the second factor forever. So it must never appear in argv:
+on Windows any process running as the same user can read another process's full
+command line (Win32_Process.CommandLine via WMI, no elevation required), on
+Linux via /proc/<pid>/cmdline, and crash dumps / EDR telemetry capture it too.
+
+Input precedence (most to least secure):
+ 1. --stdin flag — read one line from stdin. PREFERRED. Opt-in via the flag
+ because the caller must also close the write channel;
+ reading stdin unconditionally would hang whenever the
+ parent leaves the pipe open (which PythonRunner does).
+ 2. FINCEPT_TOTP_SECRET environment variable.
+ 3. sys.argv[1] — DEPRECATED, kept only so an older caller keeps working.
+ Emits a warning on stderr when used.
+
+Usage (preferred):
+ echo <base32_secret> | totp_gen.py --stdin
+
Prints JSON: {"code": "123456", "valid_for": 15}
"""
-import sys, json, time
+import os
+import sys
+import json
+import time
+
+
+def read_secret():
+ """Resolve the base32 secret from stdin, then env, then argv."""
+ argv = sys.argv[1:]
+
+ # 1. stdin — explicit opt-in. The caller must write one line and close the
+ # write channel; without the flag we must NOT touch stdin, because a
+ # parent that keeps the pipe open would make readline() block forever.
+ if "--stdin" in argv:
+ try:
+ line = sys.stdin.readline()
+ except Exception:
+ line = ""
+ return line.strip()
+
+ # 2. Environment.
+ env_secret = os.environ.get("FINCEPT_TOTP_SECRET", "").strip()
+ if env_secret:
+ return env_secret
+
+ # 3. Legacy argv path.
+ positional = [a for a in argv if not a.startswith("--")]
+ if positional and positional[0].strip():
+ print("WARNING: TOTP secret passed via argv — it is readable by any "
+ "process running as this user. Pipe it on stdin with --stdin "
+ "instead.", file=sys.stderr)
+ return positional[0].strip()
+
+ return ""
+
def main():
- if len(sys.argv) < 2:
+ secret = read_secret()
+ if not secret:
print(json.dumps({"error": "No secret provided"}))
sys.exit(1)
- secret = sys.argv[1].strip()
try:
import pyotp
totp = pyotp.TOTP(secret)
@@ -29,5 +81,6 @@ def main():
valid_for = 30 - (int(time.time()) % 30)
print(json.dumps({"code": code, "valid_for": valid_for}))
+
if __name__ == "__main__":
main()
diff --git a/fincept-qt/scripts/fincept_json.py b/fincept-qt/scripts/fincept_json.py
new file mode 100644
index 000000000..5da097ee5
--- /dev/null
+++ b/fincept-qt/scripts/fincept_json.py
@@ -0,0 +1,142 @@
+"""Safe JSON output boundary for Fincept Terminal scripts.
+
+WHY THIS EXISTS
+---------------
+`json.dumps` defaults to ``allow_nan=True``, which emits the bare tokens
+``NaN`` / ``Infinity`` / ``-Infinity``. None of those are valid JSON.
+``QJsonDocument::fromJson()`` on the C++ side does not repair them — it returns
+a **null document**, so the host discards the *entire* payload, not just the
+offending field. One halted trading day inside a 250-row price series is enough
+to blank a whole chart, and the user sees no error at all.
+
+Financial data produces non-finite floats routinely: a halted bar, a zero
+denominator in a ratio, ``pct_change()`` on the first row, an empty rolling
+window, a division by a zero previous close.
+
+USAGE
+-----
+Replace the output boundary only — you do not need to touch intermediate
+computation::
+
+ import fincept_json
+ print(fincept_json.dumps(result)) # instead of print(json.dumps(result))
+ fincept_json.emit(result) # same thing, one call
+
+For a daemon/framed protocol use the bytes form::
+
+ payload = fincept_json.dumps_bytes(response)
+
+NOTES
+-----
+* ``allow_nan=False`` alone is a *detector*, not a fix — it raises ``ValueError``.
+ These helpers always run :func:`sanitize` first, so the flag only ever fires
+ on something the sanitiser genuinely could not reach (which is a bug worth
+ hearing about, not something to swallow).
+* numpy/pandas are imported lazily and optionally: this module is imported from
+ both venv-numpy1 and venv-numpy2, and from scripts that have neither.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from decimal import Decimal
+
+__all__ = ["sanitize", "dumps", "dumps_bytes", "emit"]
+
+# Optional scientific stack. Imported once, tolerated absent.
+try: # pragma: no cover - trivial
+ import numpy as _np
+except Exception: # pragma: no cover - numpy is optional
+ _np = None
+
+try: # pragma: no cover - trivial
+ import pandas as _pd
+except Exception: # pragma: no cover - pandas is optional
+ _pd = None
+
+
+def _finite_or_none(value):
+ """float -> the float, or None when it is NaN / +-Infinity."""
+ return None if (math.isnan(value) or math.isinf(value)) else value
+
+
+def sanitize(obj):
+ """Recursively replace every non-finite float in `obj` with ``None``.
+
+ Containers are rebuilt, not mutated, so the caller's data is untouched.
+ Handles the types that actually reach our output boundaries:
+
+ * ``float`` and ``numpy.float64`` (which subclasses ``float``)
+ * ``numpy.float32`` / ``float16`` — these do **NOT** subclass ``float``, so
+ an ``isinstance(obj, float)`` check alone silently lets ``nan`` through
+ to ``default=str`` and it lands in the JSON as the *string* ``"nan"``.
+ * ``numpy.ndarray`` — not a list/tuple, so it is easy to miss entirely.
+ * ``pandas`` NA / NaT scalars.
+ * dict keys, which must end up as JSON strings.
+ """
+ # --- scalars ------------------------------------------------------------
+ if obj is None or isinstance(obj, (str, bool, int)):
+ # bool before int on purpose (bool IS an int); both are always finite.
+ return obj
+
+ if isinstance(obj, float): # covers numpy.float64
+ return _finite_or_none(obj)
+
+ if isinstance(obj, Decimal):
+ return None if not obj.is_finite() else float(obj)
+
+ if _np is not None:
+ if isinstance(obj, _np.ndarray):
+ return [sanitize(v) for v in obj.tolist()]
+ if isinstance(obj, _np.floating): # float16/32/128 — NOT a python float
+ return _finite_or_none(float(obj))
+ if isinstance(obj, _np.integer):
+ return int(obj)
+ if isinstance(obj, _np.bool_):
+ return bool(obj)
+
+ if _pd is not None:
+ # NaT and pd.NA are not floats and would otherwise stringify.
+ if obj is getattr(_pd, "NaT", None) or obj is getattr(_pd, "NA", None):
+ return None
+ if isinstance(obj, _pd.Series):
+ return [sanitize(v) for v in obj.tolist()]
+ if isinstance(obj, _pd.DataFrame):
+ return sanitize(obj.to_dict(orient="records"))
+
+ # --- containers ---------------------------------------------------------
+ if isinstance(obj, dict):
+ # JSON object keys must be strings; a NaN key would be nonsense anyway.
+ return {(k if isinstance(k, str) else str(k)): sanitize(v) for k, v in obj.items()}
+
+ if isinstance(obj, (list, tuple, set, frozenset)):
+ return [sanitize(v) for v in obj]
+
+ # Anything else (datetime, custom objects) is left for `default=str`.
+ return obj
+
+
+def dumps(obj, **kwargs) -> str:
+ """``json.dumps`` that can never emit invalid JSON.
+
+ Extra kwargs are forwarded, except ``allow_nan`` and ``default`` which are
+ fixed. Do NOT pass ``indent``: the host's stdout parser wants the JSON
+ envelope on one line (see the note in yfinance_data.py::main).
+ """
+ kwargs.pop("allow_nan", None)
+ kwargs.setdefault("default", str)
+ kwargs.setdefault("ensure_ascii", False)
+ return json.dumps(sanitize(obj), allow_nan=False, **kwargs)
+
+
+def dumps_bytes(obj, **kwargs) -> bytes:
+ """UTF-8 encoded :func:`dumps` — for length-prefixed frame protocols."""
+ return dumps(obj, **kwargs).encode("utf-8")
+
+
+def emit(obj, **kwargs) -> str:
+ """``print(dumps(obj))`` and return what was printed."""
+ text = dumps(obj, **kwargs)
+ print(text)
+ return text
diff --git a/fincept-qt/scripts/ps_output.txt b/fincept-qt/scripts/ps_output.txt
deleted file mode 100644
index e69de29bb..000000000
diff --git a/fincept-qt/scripts/ql_corrected_results.txt b/fincept-qt/scripts/ql_corrected_results.txt
deleted file mode 100644
index 41d1552ba..000000000
--- a/fincept-qt/scripts/ql_corrected_results.txt
+++ /dev/null
@@ -1,60 +0,0 @@
---- #8_linear POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "linear"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: linear"}
-
---- #8_mortgage POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "mortgage", "rate": 0.05}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: mortgage"}
-
---- #8_bullet POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "bullet"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: bullet"}
-
---- #8_LINEAR POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "LINEAR"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: LINEAR"}
-
---- #47_fixings_ok POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "fixings": {"2024-01-01": 0.04, "2024-04-01": 0.041, "2024-07-01": 0.042, "2024-10-01": 0.043, "2025-01-01": 0.044, "2025-04-01": 0.045, "2025-07-01": 0.046, "2025-10-01": 0.047}}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #50_daycount POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count": "ACT/360"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #50_minimal POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51_fixing_rate POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "fixing_rate": 0.04}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51_fixing_rate_dc POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "fixing_rate": 0.04, "day_count": "ACT/360"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51_no_fixing POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "day_count": "ACT/360"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #45_check POST /quantlib/core/ops/zero-rate-convert
- Body: {"direction": "continuous_to_annual", "value": 0.05, "t": 1.0}
- Status: 200 OK
- data keys: ['discount_factor']
- data: {"discount_factor": 0.951229424500714}
-
diff --git a/fincept-qt/scripts/ql_final2_results.txt b/fincept-qt/scripts/ql_final2_results.txt
deleted file mode 100644
index b22aa6a02..000000000
--- a/fincept-qt/scripts/ql_final2_results.txt
+++ /dev/null
@@ -1,19 +0,0 @@
---- #openapi_schema GET /openapi.json
- Status: 200 OK
- notional-schedule excerpt: TTPValidationError"}}}}}}}, "/quantlib/core/types/notional-schedule": {"post": {"tags": ["quantlib-core"], "summary": "Notional Schedule", "description": "Generate a notional schedule (constant, linear, mortgage, bullet)", "operationId": "notional_schedule_quantlib_core_types_notional_schedule_post", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/NotionalScheduleRequest"}}}, "required": true}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}},
- float-coupon excerpt: [{"APIKeyHeader": []}]}}, "/quantlib/core/periods/float-coupon": {"post": {"tags": ["quantlib-core"], "summary": "Float Coupon Period", "description": "Create a floating coupon period and return accrual and cashflow", "operationId": "float_coupon_period_quantlib_core_periods_float_coupon_post", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/FloatPeriodRequest"}}}, "required": true}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}}, "422": {"de
-
---- #docs_redoc GET /redoc
- Status: 0 FAIL
- detail: "Expecting value: line 2 column 5 (char 5)"
-
---- #47P POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "fixings": {"2024-01-01": 0.04, "2024-04-01": 0.041, "2024-07-01": 0.042, "2024-10-01": 0.043, "2025-01-01": 0.044, "2025-04-01": 0.045, "2025-07-01": 0.046, "2025-10-01": 0.047}}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47Q POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "fixings": {"rate": 0.04}}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot parse date from string: rate", "error_code": "VALIDATION_ERROR"}
-
diff --git a/fincept-qt/scripts/ql_final_results.txt b/fincept-qt/scripts/ql_final_results.txt
deleted file mode 100644
index fa7779a3c..000000000
--- a/fincept-qt/scripts/ql_final_results.txt
+++ /dev/null
@@ -1,95 +0,0 @@
---- #8_principal POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "principal"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: principal"}
-
---- #8_par POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "par"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: par"}
-
---- #8_face POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "face"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: face"}
-
---- #8_outstanding POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "outstanding"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: outstanding"}
-
---- #8_remaining POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "remaining"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: remaining"}
-
---- #8_proportional POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "proportional"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: proportional"}
-
---- #8_staggered POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "staggered"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: staggered"}
-
---- #8_even POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "even"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: even"}
-
---- #8_regular POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "regular"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: regular"}
-
---- #8_level POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "level"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: level"}
-
---- #47L POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "fixings": [0.04, 0.041, 0.042, 0.043, 0.044, 0.045, 0.046, 0.047]}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> fixings: Input should be a valid dictionary", "error_code": "VALIDATION_ERROR"}
-
---- #47M POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "discount_curve": [0.04, 0.041, 0.042, 0.043]}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47N POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "zero_rates": [0.04, 0.041, 0.042, 0.043]}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47O POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "forward_rates": [0.04, 0.041, 0.042, 0.043]}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #50_min POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count_fraction": 0.5}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51_nolib POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51_nolib2 POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "spread": 0.0, "start_date": "2024-01-01", "end_date": "2024-04-01"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
diff --git a/fincept-qt/scripts/ql_results.txt b/fincept-qt/scripts/ql_results.txt
deleted file mode 100644
index 739363aa3..000000000
--- a/fincept-qt/scripts/ql_results.txt
+++ /dev/null
@@ -1,158 +0,0 @@
---- #4 POST /quantlib/core/types/money/convert
- Status: 200 OK
- data keys: ['original', 'converted', 'rate']
- data sample: {"original": {"amount": 100.0, "currency": "USD"}, "converted": {"amount": 92.0, "currency": "EUR"}, "rate": 0.92}
-
---- #5 POST /quantlib/core/types/rate/convert
- Status: 200 OK
- data keys: ['decimal', 'percentage', 'bps', 'display']
- data sample: {"decimal": 0.05, "percentage": 5.0, "bps": 500.0, "display": "5.0000%"}
-
---- #6 GET /quantlib/core/types/spread/from-bps?bps=50
- Status: 405 FAIL
- detail: "Method Not Allowed"
-
---- #7 POST /quantlib/core/types/tenor/add-to-date
- Status: 200 OK
- data keys: ['result_date', 'tenor', 'start_date']
- data sample: {"result_date": "2024-04-01", "tenor": "3M", "start_date": "2024-01-01"}
-
---- #8 POST /quantlib/core/types/notional-schedule
- Status: 200 OK
- data keys: ['success', 'message']
- data sample: {"success": false, "message": "Unknown schedule type: linear"}
-
---- #10 POST /quantlib/core/conventions/format-date
- Status: 200 OK
- data keys: ['formatted']
- data sample: {"formatted": "2024-01-15"}
-
---- #11 POST /quantlib/core/conventions/days-to-years
- Status: 200 OK
- data keys: ['years']
- data sample: {"years": 0.999315537303217}
-
---- #12 POST /quantlib/core/conventions/years-to-days
- Status: 200 OK
- data keys: ['days']
- data sample: {"days": 365}
-
---- #13 POST /quantlib/core/conventions/normalize-rate
- Status: 200 OK
- data keys: ['normalized']
- data sample: {"normalized": 0.05}
-
---- #14 POST /quantlib/core/conventions/normalize-volatility
- Status: 200 OK
- data keys: ['normalized']
- data sample: {"normalized": 0.2}
-
---- #15 POST /quantlib/core/autodiff/dual-eval
- Status: 200 OK
- data keys: ['x', 'f_x', 'f_prime_x', 'function']
- data sample: {"x": 1.0, "f_x": 0.8414709848078965, "f_prime_x": 0.5403023058681398, "function": "sin"}
-
---- #16 POST /quantlib/core/autodiff/gradient
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> x: Input should be a valid list", "error_code": "VALIDATION_ERROR"}
-
---- #17 POST /quantlib/core/autodiff/taylor-expand
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> x0: Field required", "error_code": "VALIDATION_ERROR"}
-
---- #26 POST /quantlib/core/distributions/gamma/cdf
- Status: 200 OK
- data keys: ['x', 'alpha', 'beta', 'cdf']
- data sample: {"x": 2.0, "alpha": 2.0, "beta": 1.0, "cdf": 0.5939941502901617}
-
---- #27 POST /quantlib/core/distributions/gamma/pdf
- Status: 200 OK
- data keys: ['x', 'alpha', 'beta', 'pdf']
- data sample: {"x": 2.0, "alpha": 2.0, "beta": 1.0, "pdf": 0.2706705664732254}
-
---- #32 POST /quantlib/core/math/eval
- Status: 200 OK
- data keys: ['function', 'x', 'result']
- data sample: {"function": "sqrt", "x": 2.0, "result": 1.4142135623730951}
-
---- #33 POST /quantlib/core/math/two-arg
- Status: 200 OK
- data keys: ['success', 'message']
- data sample: {"success": false, "message": "Unknown function. Available: maximum, minimum, power"}
-
---- #34 POST /quantlib/core/ops/black-scholes
- Status: 200 OK
- data keys: ['option_type', 'price']
- data sample: {"option_type": "call", "price": 8.021352235143176}
-
---- #35 POST /quantlib/core/ops/black76
- Status: 200 OK
- data keys: ['option_type', 'price']
- data sample: {"option_type": "call", "price": 5.6103137979777165}
-
---- #36 POST /quantlib/core/ops/forward-rate
- Status: 200 OK
- data keys: ['forward_rate']
- data sample: {"forward_rate": 0.05555555555555558}
-
---- #37 POST /quantlib/core/ops/discount-cashflows
- Status: 200 OK
- data keys: ['present_value']
- data sample: {"present_value": 1131.0}
-
---- #38 POST /quantlib/core/ops/interpolate
- Status: 200 OK
- data keys: ['method', 'x', 'interpolated_value']
- data sample: {"method": "linear", "x": 2.5, "interpolated_value": 6.5}
-
---- #39 POST /quantlib/core/ops/statistics
- Status: 200 OK
- data keys: ['mean', 'std']
- data sample: {"mean": 5.5, "std": 2.8722813232690143}
-
---- #40 POST /quantlib/core/ops/var
- Status: 200 OK
- data keys: ['method', 'var', 'expected_shortfall', 'confidence']
- data sample: {"method": "historical", "var": 0.01875, "expected_shortfall": 0.02, "confidence": 0.95}
-
---- #41 POST /quantlib/core/ops/percentile
- Status: 200 OK
- data keys: ['percentile', 'value']
- data sample: {"percentile": 0.9, "value": 1.081}
-
---- #42 POST /quantlib/core/ops/covariance-matrix
- Status: 200 OK
- data keys: ['covariance_matrix']
- data sample: {"covariance_matrix": [[0.0002916666666666667, -0.000275], [-0.000275, 0.00029166666666666664]]}
-
---- #44 POST /quantlib/core/ops/gbm-paths
- Status: 200 OK
- data keys: ['n_paths', 'n_steps', 'paths']
- data sample: {"n_paths": 3, "n_steps": 10, "paths": [[100.0, 99.39055742071399, 98.60497626250829, 98.20739286493368, 102.974238502196, 102.45354268413615, 93.47635426000927, 95.7486152874648, 94.42617001688603, 93.41917159359475, 94.38911741909445], [100.0, 101.78492257702875, 109.88692666433222, 114.8906994462369, 116.0441038420629, 111.08267747800558, 104.49109823818493, 106.45069624136136, 116.00136567265582, 116.65683320858784, 116.22315579932328], [100.0, 103.73117192575477, 94.90462033160532, 93.32819310162508, 96.55719129663343, 102.34755592486744, 101.10460515431208, 103.85274079901804, 105.812889
-
---- #45 POST /quantlib/core/ops/zero-rate-convert
- Status: 200 OK
- data keys: ['discount_factor']
- data sample: {"discount_factor": 0.951229424500714}
-
---- #46 POST /quantlib/core/legs/fixed
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot parse tenor: SEMIANNUAL", "error_code": "VALIDATION_ERROR"}
-
---- #47 POST /quantlib/core/legs/float
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot parse tenor: QUARTERLY", "error_code": "VALIDATION_ERROR"}
-
---- #48 POST /quantlib/core/legs/zero-coupon
- Status: 200 OK
- data keys: ['cashflows', 'compounded_rate', 'cashflow_amount']
- data sample: {"cashflows": [{"date": "2029-01-01", "amount": 280960.3667873155}], "compounded_rate": 0.2809603667873155, "cashflow_amount": 280960.3667873155}
-
---- #50 POST /quantlib/core/periods/fixed-coupon
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51 POST /quantlib/core/periods/float-coupon
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
diff --git a/fincept-qt/scripts/ql_retry2_results.txt b/fincept-qt/scripts/ql_retry2_results.txt
deleted file mode 100644
index 8bbb6a748..000000000
--- a/fincept-qt/scripts/ql_retry2_results.txt
+++ /dev/null
@@ -1,138 +0,0 @@
---- #8_fixed POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "fixed"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: fixed"}
-
---- #8_declining POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "declining"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: declining"}
-
---- #8_reducing POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "reducing"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: reducing"}
-
---- #8_flat POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "flat"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: flat"}
-
---- #8_equal POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "equal"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: equal"}
-
---- #8_uniform POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "uniform"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: uniform"}
-
---- #8_constant POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "constant"}
- Status: 200 OK
- data keys: ['schedule_type', 'notionals', 'average_notional']
- data: {"schedule_type": "constant", "notionals": [1000000.0, 1000000.0, 1000000.0, 1000000.0], "average_notional": 1000000.0}
-
---- #8_accreting POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "accreting"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: accreting"}
-
---- #8_straight-line POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "straight-line"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: straight-line"}
-
---- #8_straight_line POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "straight_line"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: straight_line"}
-
---- #8_linear_amortization POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "linear_amortization"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: linear_amortization"}
-
---- #8_scheduled POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "scheduled"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: scheduled"}
-
---- #8_custom POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "custom"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: custom"}
-
---- #47c POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "fixing_rate": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47d POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "fixed_rate": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47e POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "rate": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #50e POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count": "ACT/365"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #50f POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count": "Actual/365"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #50g POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count": "30/360"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #50h POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count_fraction": 0.4958904109589041}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51d POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> start_date: Field required; body -> end_date: Field required", "error_code": "VALIDATION_ERROR"}
-
---- #51e POST /quantlib/core/periods/float-coupon
- Body: {}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> notional: Field required; body -> start_date: Field required; body -> end_date: Field required", "error_code": "VALIDATION_ERROR"}
-
---- #51f POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "libor_rate": 0.04, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "day_count": "ACT/360"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51g POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "rate": 0.04, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "day_count": "ACT/360"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51h POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "fixing_rate": 0.04, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "day_count_fraction": 0.25}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
diff --git a/fincept-qt/scripts/ql_retry3_results.txt b/fincept-qt/scripts/ql_retry3_results.txt
deleted file mode 100644
index e174cccb2..000000000
--- a/fincept-qt/scripts/ql_retry3_results.txt
+++ /dev/null
@@ -1,100 +0,0 @@
---- #8_amortization POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "amortization"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: amortization"}
-
---- #8_amortized POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "amortized"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: amortized"}
-
---- #8_annuity POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "annuity"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: annuity"}
-
---- #8_schedule POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "schedule"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: schedule"}
-
---- #8_notional POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "notional"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: notional"}
-
---- #8_linearly_declining POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "linearly_declining"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: linearly_declining"}
-
---- #8_step POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "step"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: step"}
-
---- #8_balloon POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "balloon"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: balloon"}
-
---- #8_interest_only POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "interest_only"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: interest_only"}
-
---- #8_bond POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "bond"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: bond"}
-
---- #47f POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "curve": [0.04, 0.042, 0.043, 0.044, 0.045, 0.046, 0.047, 0.048]}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47g POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "curve": {"rates": [0.04, 0.042, 0.043, 0.044], "tenors": ["3M", "6M", "9M", "1Y"]}}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47h POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "flat_rate": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47i POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "index_rate": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47j POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "libor": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47k POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01", "flat_forward": 0.04}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #50_probe POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": "X", "rate": "X", "start_date": "X", "end_date": "X", "day_count_fraction": "X"}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> notional: Input should be a valid number, unable to parse string as a number; body -> rate: Input should be a valid number, unable to parse string as a number", "error_code": "VALIDATION_ERROR"}
-
---- #51_probe POST /quantlib/core/periods/float-coupon
- Body: {"notional": "X", "start_date": "X", "end_date": "X", "libor_rate": "X", "spread": "X", "day_count_fraction": "X"}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> notional: Input should be a valid number, unable to parse string as a number; body -> spread: Input should be a valid number, unable to parse string as a number", "error_code": "VALIDATION_ERROR"}
-
diff --git a/fincept-qt/scripts/ql_retry_results.txt b/fincept-qt/scripts/ql_retry_results.txt
deleted file mode 100644
index 73c9dd3bd..000000000
--- a/fincept-qt/scripts/ql_retry_results.txt
+++ /dev/null
@@ -1,142 +0,0 @@
---- #6a POST /quantlib/core/types/spread/from-bps
- Body: {"bps": 50}
- Status: 422 FAIL
- detail: {"success": false, "message": "query -> bps: Field required", "error_code": "VALIDATION_ERROR"}
-
---- #6b GET /quantlib/core/types/spread/from-bps
- Body: null
- Status: 405 FAIL
- detail: "Method Not Allowed"
-
---- #6c POST /quantlib/core/types/spread/from-bps?bps=50
- Body: {}
- Status: 200 OK
- data keys: ['decimal', 'bps']
- data: {"decimal": 0.005, "bps": 50.0}
-
---- #8a POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "amortizing"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: amortizing"}
-
---- #8b POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "bullet"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: bullet"}
-
---- #8c POST /quantlib/core/types/notional-schedule
- Body: {"notional": 1000000, "periods": 4, "schedule_type": "step_down"}
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: step_down"}
-
---- #16a POST /quantlib/core/autodiff/gradient
- Body: {"func_name": "sin", "x": [1.0]}
- Status: 200 OK
- data keys: ['gradient']
- data: {"gradient": 0.5403023058681398}
-
---- #16b POST /quantlib/core/autodiff/gradient
- Body: {"func_name": "sin", "x": [1.0, 2.0]}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #17a POST /quantlib/core/autodiff/taylor-expand
- Body: {"func_name": "sin", "x0": 1.0, "order": 3}
- Status: 200 OK
- data keys: ['x0', 'order', 'coefficients']
- data: {"x0": 1.0, "order": 3, "coefficients": [0.8414709848078965, 0.5403023058681398, -0.42073549240394825, -0.09005038431135663]}
-
---- #17b POST /quantlib/core/autodiff/taylor-expand
- Body: {"func_name": "sin", "x0": 1.0, "x": 1.5, "order": 3}
- Status: 200 OK
- data keys: ['x0', 'order', 'coefficients']
- data: {"x0": 1.0, "order": 3, "coefficients": [0.8414709848078965, 0.5403023058681398, -0.42073549240394825, -0.09005038431135663]}
-
---- #33a POST /quantlib/core/math/two-arg
- Body: {"func_name": "power", "x": 2.0, "y": 10.0}
- Status: 200 OK
- data keys: ['function', 'x', 'y', 'result']
- data: {"function": "power", "x": 2.0, "y": 10.0, "result": 1024.0}
-
---- #33b POST /quantlib/core/math/two-arg
- Body: {"func_name": "maximum", "x": 2.0, "y": 10.0}
- Status: 200 OK
- data keys: ['function', 'x', 'y', 'result']
- data: {"function": "maximum", "x": 2.0, "y": 10.0, "result": 10.0}
-
---- #45b POST /quantlib/core/ops/zero-rate-convert
- Body: {"direction": "annual_to_continuous", "value": 0.05, "t": 1.0}
- Status: 200 OK
- data keys: ['discount_factor']
- data: {"discount_factor": 0.951229424500714}
-
---- #46a POST /quantlib/core/legs/fixed
- Body: {"notional": 1000000, "rate": 0.05, "frequency": "semi-annual", "start_date": "2024-01-01", "end_date": "2026-01-01"}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot parse tenor: SEMI-ANNUAL", "error_code": "VALIDATION_ERROR"}
-
---- #46b POST /quantlib/core/legs/fixed
- Body: {"notional": 1000000, "rate": 0.05, "frequency": "6M", "start_date": "2024-01-01", "end_date": "2026-01-01"}
- Status: 200 OK
- data keys: ['cashflows', 'count']
- data: {"cashflows": [{"date": "2024-07-01", "amount": 25277.777777777777}, {"date": "2025-01-01", "amount": 25555.555555555555}, {"date": "2025-07-01", "amount": 25138.888888888887}, {"date": "2026-01-01", "amount": 25555.555555555555}], "count": 4}
-
---- #46c POST /quantlib/core/legs/fixed
- Body: {"notional": 1000000, "rate": 0.05, "frequency": "annual", "start_date": "2024-01-01", "end_date": "2026-01-01"}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot parse tenor: ANNUAL", "error_code": "VALIDATION_ERROR"}
-
---- #46d POST /quantlib/core/legs/fixed
- Body: {"notional": 1000000, "rate": 0.05, "frequency": "1Y", "start_date": "2024-01-01", "end_date": "2026-01-01"}
- Status: 200 OK
- data keys: ['cashflows', 'count']
- data: {"cashflows": [{"date": "2025-01-01", "amount": 50833.33333333333}, {"date": "2026-01-01", "amount": 50694.444444444445}], "count": 2}
-
---- #47a POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "3M", "start_date": "2024-01-01", "end_date": "2026-01-01"}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot calculate cashflow: no fixing rate, fixed rate, or curve provided", "error_code": "VALIDATION_ERROR"}
-
---- #47b POST /quantlib/core/legs/float
- Body: {"notional": 1000000, "spread": 0.01, "frequency": "quarterly", "start_date": "2024-01-01", "end_date": "2026-01-01"}
- Status: 400 FAIL
- detail: {"success": false, "message": "Cannot parse tenor: QUARTERLY", "error_code": "VALIDATION_ERROR"}
-
---- #50a POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "dcf": 0.5}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #50b POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "coupon_rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count_fraction": 0.5}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> rate: Field required", "error_code": "VALIDATION_ERROR"}
-
---- #50c POST /quantlib/core/periods/fixed-coupon
- Body: {"notional": 1000000, "rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #50d POST /quantlib/core/periods/fixed-coupon
- Body: {"face_value": 1000000, "coupon_rate": 0.05, "start_date": "2024-01-01", "end_date": "2024-07-01", "day_count_fraction": 0.5}
- Status: 422 FAIL
- detail: {"success": false, "message": "body -> notional: Field required; body -> rate: Field required", "error_code": "VALIDATION_ERROR"}
-
---- #51a POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "rate": 0.05, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51b POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "index_rate": 0.04, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01"}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
---- #51c POST /quantlib/core/periods/float-coupon
- Body: {"notional": 1000000, "libor_rate": 0.04, "spread": 0.01, "start_date": "2024-01-01", "end_date": "2024-04-01", "day_count_fraction": 0.25}
- Status: 500 FAIL
- detail: {"success": false, "message": "Internal server error", "error_code": "INTERNAL_ERROR"}
-
diff --git a/fincept-qt/scripts/ql_schema_results.txt b/fincept-qt/scripts/ql_schema_results.txt
deleted file mode 100644
index 4c325af7d..000000000
--- a/fincept-qt/scripts/ql_schema_results.txt
+++ /dev/null
@@ -1,683 +0,0 @@
-=== NotionalScheduleRequest ===
-{
- "properties": {
- "schedule_type": {
- "type": "string",
- "title": "Schedule Type"
- },
- "notional": {
- "type": "number",
- "title": "Notional"
- },
- "periods": {
- "type": "integer",
- "title": "Periods"
- },
- "rate": {
- "anyOf": [
- {
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "title": "Rate"
- }
- },
- "type": "object",
- "required": [
- "schedule_type",
- "notional",
- "periods"
- ],
- "title": "NotionalScheduleRequest"
-}
-
-=== FloatLegRequest ===
-{
- "properties": {
- "notional": {
- "type": "number",
- "title": "Notional"
- },
- "spread": {
- "type": "number",
- "title": "Spread",
- "default": 0.0
- },
- "start_date": {
- "type": "string",
- "title": "Start Date"
- },
- "end_date": {
- "type": "string",
- "title": "End Date"
- },
- "frequency": {
- "type": "string",
- "title": "Frequency",
- "default": "Quarterly"
- },
- "day_count": {
- "type": "string",
- "title": "Day Count",
- "default": "ACT/360"
- },
- "index_name": {
- "type": "string",
- "title": "Index Name",
- "default": "SOFR"
- },
- "fixings": {
- "anyOf": [
- {
- "additionalProperties": {
- "type": "number"
- },
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "title": "Fixings"
- }
- },
- "type": "object",
- "required": [
- "notional",
- "start_date",
- "end_date"
- ],
- "title": "FloatLegRequest"
-}
-
-=== FloatPeriodRequest ===
-{
- "properties": {
- "notional": {
- "type": "number",
- "title": "Notional"
- },
- "spread": {
- "type": "number",
- "title": "Spread",
- "default": 0.0
- },
- "start_date": {
- "type": "string",
- "title": "Start Date"
- },
- "end_date": {
- "type": "string",
- "title": "End Date"
- },
- "day_count": {
- "type": "string",
- "title": "Day Count",
- "default": "ACT/360"
- },
- "fixing_rate": {
- "anyOf": [
- {
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "title": "Fixing Rate"
- }
- },
- "type": "object",
- "required": [
- "notional",
- "start_date",
- "end_date"
- ],
- "title": "FloatPeriodRequest"
-}
-
-=== FixedCouponPeriodRequest: NOT FOUND ===
- Similar: []
-
-=== FixedPeriodRequest ===
-{
- "properties": {
- "notional": {
- "type": "number",
- "title": "Notional"
- },
- "rate": {
- "type": "number",
- "title": "Rate"
- },
- "start_date": {
- "type": "string",
- "title": "Start Date"
- },
- "end_date": {
- "type": "string",
- "title": "End Date"
- },
- "day_count": {
- "type": "string",
- "title": "Day Count",
- "default": "ACT/360"
- }
- },
- "type": "object",
- "required": [
- "notional",
- "rate",
- "start_date",
- "end_date"
- ],
- "title": "FixedPeriodRequest"
-}
-
-=== ALL SCHEMA NAMES ===
- ARForecastRequest
- ARIMAForecastRequest
- ARIMARequest
- ARRequest
- ASWSpreadRequest
- AccrualsRatioRequest
- AddBusinessDaysRequest
- AdjustDateRequest
- AircraftRequest
- AltmanZRequest
- AntitheticRequest
- AreaSearchRequest
- AsyncLLMRequest
- AsyncLLMResponse
- AuctionRequest
- AuctionRevenueRequest
- BSDigitalRequest
- BSImpliedVolRequest
- BSPriceRequest
- BachelierImpliedVolRequest
- BachelierPriceRequest
- BacktestRequest
- BalanceSheetInput
- BankingRequest
- BasisRequest
- BasisSpreadRequest
- BasketLevyRequest
- BatchAdjustRequest
- BatchYearFractionRequest
- BeneishMRequest
- BerkusRequest
- BetaDistRequest
- BetaEvalRequest
- BetaLGDRequest
- BinomialBarrierRequest
- BinomialBermudanRequest
- BinomialDistRequest
- BinomialEvalRequest
- BinomialRequest
- BivariateNormRequest
- Black76ImpliedVolRequest
- Black76PriceRequest
- Black76Request
- BlackLittermanRequest
- BlackScholesRequest
- Body_extract_pdf_text_research_pdf_extract_post
- BoltzmannRequest
- BondFutureRequest
- BondPriceRequest
- BootstrapInstrument
- BootstrapRequest
- BroadcastMessageRequest
- BrownianBridgeRequest
- BucketDeltaRequest
- BuildCurveRequest
- BusinessDaysBetweenRequest
- ButterflyRequest
- CARARequest
- CDSRequest
- CEApproxRequest
- CESRequest
- CIRRequest
- CRRARequest
- CalendarFeaturesRequest
- CalibrateVasicekRequest
- CalibrationRequest
- CapFloorletRequest
- CapitalProjectionRequest
- CapitalRatioRequest
- CapitalStructureRequest
- CarnotRequest
- CarryRequest
- CashEarningsRequest
- CashFlowAnalysisRequest
- CashFlowInput
- CashFlowRatioRequest
- CertaintyEquivRequest
- ChangepointRequest
- ChatRequest
- ChatSessionCreate
- Chi2Request
- ChiSquaredDistRequest
- ChiSquaredEvalRequest
- CholeskyRequest
- ClassicGameRequest
- ClassificationMetricsRequest
- ClausiusClapeyronRequest
- CobbDouglasRequest
- CommodityFutureRequest
- ComparableRequest
- ComponentVaRRequest
- CompositeCurveRequest
- ComprehensiveRequest
- ContactFormCreate
- ContentReaderRequest
- ConvexityAdjRequest
- ConvexityRequest
- CopulaRequest
- CorrelatedBMRequest
- CorrelatedNormalsRequest
- CorrelationStressRequest
- CostOfEquityRequest
- CovMatrixRequest
- CovarianceEstimatorRequest
- CovariationRequest
- CreateOrderRequest
- CreditAdjustmentRequest
- CreditRWARequest
- CreditSpreadRequest
- CriticalTempRequest
- CrossCurrencyBasisRequest
- CrossGammaRequest
- CrossSectionalFactorRequest
- CrossSectionalRequest
- CurvePointsRequest
- CurveQueryRequest
- DBSCANRequest
- DCFRequest
- DDMRequest
- DatabaseCreateRequest
- DatabaseSubscriptionRequest
- DateFormatRequest
- DayCountFractionRequest
- DayCountRequest
- DaysYearsRequest
- DecompRequest
- DepositRequest
- DifferentialEntropyRequest
- DiscountCashflowsRequest
- DiscountFactorRequest
- DiscriminationRequest
- DistanceToDefaultRequest
- DistressScoreRequest
- DistributionSampleRequest
- DivergenceRequest
- DominatedRequest
- DotRequest
- DuPontRequest
- DualEvalRequest
- DupireRequest
- DurationRequest
- EADRequest
- ECL12MRequest
- EGARCHRequest
- ESOptRequest
- EVARequest
- EarningsHistoryRequest
- EfficiencyRatioRequest
- EfficiencyRequest
- EfficientFrontierRequest
- EnsembleRequest
- EntropyRequest
- EulerMaruyamaNDRequest
- EulerMaruyamaRequest
- ExactCIRRequest
- ExactGBMRequest
- ExchangeEconomyRequest
- ExpDistRequest
- ExpPpfRequest
- ExpectedUtilityRequest
- ExponentialDistRequest
- ExponentialEvalRequest
- ExponentialPpfRequest
- ExposureProfileRequest
- FCFMarginRequest
- FDistEvalRequest
- FDistRequest
- FFTConvolveRequest
- FFTRequest
- FRARequest
- FXForwardRequest
- FactorModelRequest
- FeedbackCreate
- FictitiousPlayRequest
- FinancialRatiosRequest
- FiniteDiffDerivRequest
- FiniteDiffGradientRequest
- FiniteDiffHessianRequest
- FirstChicagoRequest
- FisherInfoRequest
- FixedBondRequest
- FixedLegRequest
- FixedPeriodRequest
- FlatVolRequest
- FloatLegRequest
- FloatPeriodRequest
- ForumCommentCreate
- ForumPostCreate
- ForumProfileUpdate
- ForumVoteCreate
- ForwardFuturesConvRequest
- FreeEnergyRequest
- GARCHForecastRequest
- GARCHHybridRequest
- GARCHRequest
- GBMPathsRequest
- GBMRequest
- GEVRequest
- GJRGARCHRequest
- GPCurveRequest
- GPDRequest
- GPVolSurfaceRequest
- GSpreadRequest
- GameRequest
- GammaEvalRequest
- GarmanKohlhagenRequest
- GenerateCheckoutTokenRequest
- GenerateScheduleRequest
- GeometricDistRequest
- GeometricEvalRequest
- GeometricPpfRequest
- GirsanovRequest
- GordonGrowthRequest
- GradientRequest
- GreeksRequest
- GrokipediaRequest
- GrowthRatioRequest
- GrowthRequest
- HMMRequest
- HTTPValidationError
- HWCalibRequest
- HazardRateRequest
- HestonExactRequest
- HestonMCRequest
- HestonModelRequest
- HestonRequest
- HierarchicalRequest
- HistoricalVaRRequest
- HypergeometricDistRequest
- HypergeometricEvalRequest
- IFRS9StageRequest
- IRRRequest
- ISpreadRequest
- IdealGasRequest
- ImpliedRepoRequest
- ImpliedToLocalRequest
- ImpliedVolBlack76Request
- ImpliedVolRequest
- IncomeStatementInput
- InflationBondRequest
- InflationBootstrapRequest
- InflationCurveRequest
- InsuranceRequest
- InternalGrowthRequest
- InterpolationDerivRequest
- InterpolationRequest
- InterpretabilityRequest
- InverseRequest
- InverseVolRequest
- IsBusinessDayRequest
- IsingRequest
- IsolationForestRequest
- ItoLemmaRequest
- JointEntropyRequest
- JouleThomsonRequest
- JumpSamplerRequest
- KMeansRequest
- KeyRateDurationRequest
- KeyRateShiftRequest
- KirkSpreadRequest
- KouModelRequest
- LCRRequest
- LLMRequest
- LagsFeaturesRequest
- LeverageRatioRequest
- LifetimeECLRequest
- LiquidityRatioRequest
- LiquidityRequest
- LocalVolConstRequest
- LogUtilityRequest
- LogisticRequest
- LognormalDistRequest
- LognormalEvalRequest
- LognormalPpfRequest
- LstSqRequest
- MARequest
- MLMCRequest
- MargrabeRequest
- MarketDataInput
- MarkovEntropyRequest
- MartingaleTestRequest
- MatMulRequest
- MatVecRequest
- MathFuncRequest
- MathTwoArgRequest
- MaxEntropyRequest
- MeasureChangeRequest
- MertonJumpRequest
- MessageCreate
- MetricsRequest
- MigrationRequest
- MilsteinRequest
- MoneyConvertRequest
- MoneyRequest
- MonitorCommandRequest
- MonitorStartRequest
- MonitorStatusResponse
- MonteCarloIntRequest
- MultiCurveSetupRequest
- MultiVesselRequest
- MultivariateNormalRequest
- NLLeastSquaresRequest
- NNCurveRequest
- NNPortfolioRequest
- NNVolSurfaceRequest
- NSFRRequest
- NSSEvalRequest
- NSSRequest
- NashCheckRequest
- NegBinomialDistRequest
- NegBinomialEvalRequest
- NelsonSiegelEvalRequest
- NelsonSiegelRequest
- NewsAnalysisRequest
- NewsletterSubscribe
- NewtonRequest
- NextBusinessDayRequest
- NormCdfRequest
- NormPdfRequest
- NormPpfRequest
- NormRequest
- NormalDistRequest
- NormalEvalRequest
- NormalPpfEvalRequest
- NormalizeRateRequest
- NormalizeVolRequest
- NotionalScheduleRequest
- OASRequest
- OCFMarginRequest
- ODERequest
- OISCurveRequest
- OISRequest
- OTPVerification
- OURequest
- OperationalRWARequest
- OptimalHedgeRequest
- OptimizationRequest
- OptimizeRequest
- OuterRequest
- OutlierRequest
- PCARequest
- PGFRequest
- PV01Request
- ParRateRequest
- ParallelShiftRequest
- ParametricVaRRequest
- ParseDateRequest
- PasswordReset
- PasswordResetConfirm
- PercentileRequest
- PiotroskiFRequest
- PoissonDistRequest
- PoissonEvalRequest
- PoissonRequest
- ProFormaRequest
- ProfileCreate
- ProfileData
- ProfileUpdate
- ProfitabilityRatioRequest
- ProfitabilityRequest
- ProspectTheoryRequest
- ProxyCurveRequest
- QuadVarRequest
- QuadraticUtilityRequest
- QuadratureRequest
- QualityRequest
- REITRequest
- RIValuationRequest
- RateRequest
- RatioRequest
- RealRateCurveRequest
- RegressionRequest
- RenyiEntropyRequest
- RepoRequest
- ResidualIncomeRequest
- RiskContribRequest
- RiskParityRequest
- RiskPremiumRequest
- RollCurveRequest
- RollingRequest
- Root1DRequest
- RootNDRequest
- SABRCalibrateRequest
- SABRDensityRequest
- SABRDynamicsRequest
- SABRNormalVolRequest
- SABRSmileRequest
- SABRVolRequest
- SACCRRequest
- SICRRequest
- STIRFutureRequest
- SVIRequest
- ScaledCurveRequest
- ScalerRequest
- ScorecardRequest
- ScreenRequest
- SeasonalityRequest
- SegmentAnalysisRequest
- SegmentInput
- ShiftSensitivityRequest
- ShiftedLognormalRequest
- ShortRateBondRequest
- ShortRateMCRequest
- ShortRateRequest
- SimulateAuctionsRequest
- SmileRequest
- SobolRequest
- SolveRequest
- SolvencyRequest
- SpeechInput
- SplineDerivRequest
- SplineEvalRequest
- StabilityRequest
- StatFactorModelRequest
- StationarityRequest
- StatsArrayRequest
- StochasticDominanceRequest
- StratifiedSamplingRequest
- StressScenarioRequest
- StudentTDistRequest
- StudentTEvalRequest
- SurfaceFromPointsRequest
- SurfaceGridRequest
- SurvivalRequest
- SustainableGrowthRequest
- SwapRequest
- SwaptionRequest
- SystemConfigRequest
- TBillRequest
- TCdfRequest
- TPdfRequest
- TPpfRequest
- TailRiskRequest
- TargetReturnRequest
- TaskStatusResponse
- TaylorExpandRequest
- TechnicalRequest
- TenorRequest
- TermStructureVolRequest
- TerminalValueRequest
- TicketCreate
- TicketUpdate
- TimeSeriesImportanceRequest
- TimeShiftCurveRequest
- TobinsQRequest
- TotalVarianceRequest
- TransferEntropyRequest
- TransformRequest
- TransposeRequest
- TreeRequest
- TsallisEntropyRequest
- TwistRequest
- TwoStageDCFRequest
- TwoStageLGDRequest
- UserCreateRequest
- UserLogin
- UserRegistration
- UserUpdateRequest
- UtilityRequest
- VCMethodRequest
- VGModelRequest
- VGRequest
- ValidationError
- ValuationRatioRequest
- VanDerWaalsRequest
- VarianceSwapRequest
- VasicekRequest
- VerifyCheckoutTokenRequest
- VesselPositionRequest
- VisualAnalysisRequest
- VolConversionRequest
- VolSwapRequest
- WACCRequest
- WalrasianRequest
- WebSearchRequest
- WienerRequest
- WinsorizerRequest
- WoERequest
- XIRRRequest
- XVARequest
- YearFractionRequest
- ZSpreadRequest
- ZeroBondRequest
- ZeroCouponLegRequest
- ZeroRateConvertRequest
- ZeroRateRequest
- quantlib_api__analysis__MertonModelRequest
- quantlib_api__core__ForwardRateRequest
- quantlib_api__core__GammaDistRequest
- quantlib_api__core__InterpolateRequest
- quantlib_api__core__VaRRequest
- quantlib_api__curves__ForwardRateRequest
- quantlib_api__instruments__BondYieldRequest
- quantlib_api__models__MertonModelRequest
- quantlib_api__numerical__InterpolateRequest
- quantlib_api__portfolio__IncrementalVaRRequest
- quantlib_api__portfolio__PortfolioRiskRequest
- quantlib_api__portfolio__PortfolioRiskRequest__2
- quantlib_api__portfolio__VaRRequest
- quantlib_api__risk__IncrementalVaRRequest
- quantlib_api__solver__BondYieldRequest
- quantlib_api__solver__ForwardRateRequest
- quantlib_api__statistics__GammaDistRequest
diff --git a/fincept-qt/scripts/tedata_out.txt b/fincept-qt/scripts/tedata_out.txt
deleted file mode 100644
index 10101458f..000000000
--- a/fincept-qt/scripts/tedata_out.txt
+++ /dev/null
@@ -1,37 +0,0 @@
-INFO - tedata package initialized successfully!
-Attributes: ['BrowserType', 'apply_x_index', 'browser', 'chart_soup', 'chart_type', 'chart_types', 'click_button', 'click_max_button', 'close', 'create_chart_types_dict', 'created_at', 'custom_date_span', 'custom_date_span_js', 'date_span', 'date_span_dict', 'date_spans', 'determine_date_span', 'driver', 'dtIndex', 'export_data', 'extract_axis_limits', 'find_max_button', 'full_chart', 'full_page', 'full_series_fromTooltips', 'get_chart_dims', 'get_chart_type_from_highcharts', 'get_datamax_min', 'get_earliest_points', 'get_element', 'get_page_source', 'get_xlims_from_tooltips', 'get_y_axis', 'has_no_data_message', 'headless', 'init_tooltipScraper', 'last_url', 'load_page', 'make_x_index', 'metadata', 'observers', 'page_soup', 'page_source', 'plot_series', 'register', 'save_plot', 'scale_series', 'scrape_metadata', 'select_chart_type', 'series', 'series_from_chart_soup', 'series_from_highcharts', 'series_metadata', 'series_name', 'set_chartType_highcharts', 'set_chartType_js', 'set_date_span', 'set_max_date_span_viaCalendar', 'tooltip_multiScrape', 'update_chart', 'update_date_span', 'wait']
-browser: 'firefox'
-chart_type: None
-chart_types: {'Column': '.barChart', 'Spline': '.splineChart', 'Areaspline': '.areasplineChart', 'Stepline': '.stepLine', 'Line': '.lineChart', 'Area': '.areaChart'}
-created_at: 1774857017.814064
-date_span: '10Y'
-date_span_dict: ''
-date_spans: OrderedDict({'': 'a.dkLabels-label-btn:nth-child(1)', '1Y': 'a.hawk-chartOptions-datePicker-cnt-btn:nth-child(2)', '3Y': 'a.hawk-chartOptions-datePicker-cnt-btn:nth-child(3)', '5Y': 'a.hawk-chartOptions-datePicker-cnt-btn:nth-child(4)', '10Y': 'a.hawk-chartOptions-datePicker-cnt-btn:nth-child(5)', '
-driver: <tedata.base.TimestampedFirefox (session="9b057609-2cac-4e0a-9dfc-830a5142f395")>
-full_chart: [<div class="" id="trading_chart" style="position: relative; height: 445px;"><div style="height: 100%; width: 100%;"><div class="chartCompareDiv" style="height: 100%;"><div class="chart_module chart1 undertaker-section" id="chart" style="margin-top: 10px; height: 410px;"><div class="chart_preview un
-full_page: '<html><head id="ctl00_Head1"><meta charset="utf-8"><title>\n\tGermany North Rhine-Westphalia CPI YoY\n</title><meta id="metaDesc" name="description" content="North Rhine Westphalia CPI YoY in Germany decreased to 1.80 percent in February from 2 percent in January of 2026. This page includes a chart
-headless: True
-last_url: 'https://tradingeconomics.com/germany/north-rhine-westphalia-cpi-yoy'
-metadata: {'units': '%', 'original_source': 'Landesbetrieb Information und Technik Nordrhein-Westfalen', 'title': 'Germany North Rhine-Westphalia CPI YoY', 'indicator': 'north rhine westphalia cpi yoy', 'country': 'germany', 'source': 'Trading Economics', 'id': 'germany/north-rhine-westphalia-cpi-yoy', 'descr
-observers: [<tedata.scraper.TE_Scraper object at 0x0000027E543AF0E0>]
-page_source: '<html><head id="ctl00_Head1"><meta charset="utf-8"><title>\n\tGermany North Rhine-Westphalia CPI YoY\n</title><meta id="metaDesc" name="description" content="North Rhine Westphalia CPI YoY in Germany decreased to 1.80 percent in February from 2 percent in January of 2026. This page includes a chart
-series: date
-2016-03-01 0.4
-2016-04-01 -0.1
-2016-05-01 0.2
-2016-06-01 0.3
-2016-07-01 0.5
- ...
-2025-10-01 2.3
-2025-11-01 2.3
-2025-12-01 1.8
-2026-01-01 2.0
-2026-02-01 1.8
-Name: Germany North Rhine-Westphalia CPI YoY, Length: 120, dtype: float64
-series_metadata: units %
-original_source Landesbetrieb Information und Technik Nordrhei...
-title Germany North Rhine-Westphalia CPI YoY
-indicator north rhine westphalia cpi yoy
-country
-series_name: 'north rhine westphalia cpi yoy'
-wait: <selenium.webdriver.support.wait.WebDriverWait (session="9b057609-2cac-4e0a-9dfc-830a5142f395")>
diff --git a/fincept-qt/scripts/test_results_batch1.txt b/fincept-qt/scripts/test_results_batch1.txt
deleted file mode 100644
index 00c4f29aa..000000000
--- a/fincept-qt/scripts/test_results_batch1.txt
+++ /dev/null
@@ -1,62 +0,0 @@
---- #4 POST /quantlib/core/types/money/convert
- Status: 200 OK
- data keys: ['original', 'converted', 'rate']
- data: {"original": {"amount": 100.0, "currency": "USD"}, "converted": {"amount": 92.0, "currency": "EUR"}, "rate": 0.92}
-
---- #5 POST /quantlib/core/types/rate/convert
- Status: 200 OK
- data keys: ['decimal', 'percentage', 'bps', 'display']
- data: {"decimal": 0.05, "percentage": 5.0, "bps": 500.0, "display": "5.0000%"}
-
---- #6 GET /quantlib/core/types/spread/from-bps?bps=50
- Status: 405 FAIL
- full_resp: {"detail": "Method Not Allowed"}
-
---- #7 POST /quantlib/core/types/tenor/add-to-date
- Status: 200 OK
- data keys: ['result_date', 'tenor', 'start_date']
- data: {"result_date": "2024-04-01", "tenor": "3M", "start_date": "2024-01-01"}
-
---- #8 POST /quantlib/core/types/notional-schedule
- Status: 200 OK
- data keys: ['success', 'message']
- data: {"success": false, "message": "Unknown schedule type: linear"}
-
---- #10 POST /quantlib/core/conventions/format-date
- Status: 200 OK
- data keys: ['formatted']
- data: {"formatted": "2024-01-15"}
-
---- #11 POST /quantlib/core/conventions/days-to-years
- Status: 200 OK
- data keys: ['years']
- data: {"years": 0.999315537303217}
-
---- #12 POST /quantlib/core/conventions/years-to-days
- Status: 200 OK
- data keys: ['days']
- data: {"days": 365}
-
---- #13 POST /quantlib/core/conventions/normalize-rate
- Status: 200 OK
- data keys: ['normalized']
- data: {"normalized": 0.05}
-
---- #14 POST /quantlib/core/conventions/normalize-volatility
- Status: 200 OK
- data keys: ['normalized']
- data: {"normalized": 0.2}
-
---- #15 POST /quantlib/core/autodiff/dual-eval
- Status: 200 OK
- data keys: ['x', 'f_x', 'f_prime_x', 'function']
- data: {"x": 1.0, "f_x": 0.8414709848078965, "f_prime_x": 0.5403023058681398, "function": "sin"}
-
---- #16 POST /quantlib/core/autodiff/gradient
- Status: 422 FAIL
- full_resp: {"success": false, "message": "body -> x: Input should be a valid list", "error_code": "VALIDATION_ERROR"}
-
---- #17 POST /quantlib/core/autodiff/taylor-expand
- Status: 422 FAIL
- full_resp: {"success": false, "message": "body -> x0: Field required", "error_code": "VALIDATION_ERROR"}
-
diff --git a/fincept-qt/scripts/vision_quant/models/attention_cae.py b/fincept-qt/scripts/vision_quant/models/attention_cae.py
index f198c93ed..e693dac87 100644
--- a/fincept-qt/scripts/vision_quant/models/attention_cae.py
+++ b/fincept-qt/scripts/vision_quant/models/attention_cae.py
@@ -231,7 +231,10 @@ class AttentionCAETrainer:
}, path)
def load_checkpoint(self, path: str):
- checkpoint = torch.load(path, map_location=self.device)
+ # weights_only=True: a checkpoint is an untrusted pickle. Without this,
+ # torch.load() runs arbitrary code via __reduce__ on load. Matches
+ # vision_quant/engine.py and vision_quant/setup_index.py.
+ checkpoint = torch.load(path, map_location=self.device, weights_only=True)
self.model.load_state_dict(checkpoint["model_state_dict"])
self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
return checkpoint["epoch"], checkpoint["loss"]
diff --git a/fincept-qt/scripts/wits_countries_mapping.txt b/fincept-qt/scripts/wits_countries_mapping.txt
deleted file mode 100644
index 34569ce56..000000000
--- a/fincept-qt/scripts/wits_countries_mapping.txt
+++ /dev/null
@@ -1,271 +0,0 @@
-Total countries: 266
-
-Python dict format:
-ISO3_TO_NUMERIC = {
- "999": "999", # Not Applicable
- "abw": "533", # Aruba
- "afg": "004", # Afghanistan
- "ago": "024", # Angola
- "aia": "660", # Anguila
- "alb": "008", # Albania
- "and": "020", # Andorra
- "ant": "530", # Netherlands Antilles
- "are": "784", # United Arab Emirates
- "arg": "032", # Argentina
- "arm": "051", # Armenia
- "asm": "016", # American Samoa
- "ata": "010", # Antarctica
- "atf": "260", # Fr. So. Ant. Tr
- "atg": "028", # Antigua and Barbuda
- "aus": "036", # Australia
- "aut": "040", # Austria
- "aze": "031", # Azerbaijan
- "bat": "080", # Br. Antr. Terr
- "bdi": "108", # Burundi
- "bel": "056", # Belgium
- "ben": "204", # Benin
- "bes": "535", # Bonaire
- "bfa": "854", # Burkina Faso
- "bgd": "050", # Bangladesh
- "bgr": "100", # Bulgaria
- "bhr": "048", # Bahrain
- "bhs": "044", # Bahamas, The
- "bih": "070", # Bosnia and Herzegovina
- "blm": "652", # Saint Barth�lemy
- "blr": "112", # Belarus
- "blx": "058", # Belgium-Luxembourg
- "blz": "084", # Belize
- "bmu": "060", # Bermuda
- "bol": "068", # Bolivia
- "bra": "076", # Brazil
- "brb": "052", # Barbados
- "brn": "096", # Brunei
- "btn": "064", # Bhutan
- "bun": "837", # Bunkers
- "bvt": "074", # Bouvet Island
- "bwa": "072", # Botswana
- "caf": "140", # Central African Republic
- "can": "124", # Canada
- "cck": "166", # Cocos (Keeling) Islands
- "che": "756", # Switzerland
- "chl": "152", # Chile
- "chn": "156", # China
- "civ": "384", # Cote d'Ivoire
- "cmr": "120", # Cameroon
- "cog": "178", # Congo, Rep.
- "cok": "184", # Cook Islands
- "col": "170", # Colombia
- "com": "174", # Comoros
- "cpv": "132", # Cape Verde
- "cri": "188", # Costa Rica
- "csk": "200", # Czechoslovakia
- "cub": "192", # Cuba
- "cuw": "531", # Cura�ao
- "cxr": "162", # Christmas Island
- "cym": "136", # Cayman Islands
- "cyp": "196", # Cyprus
- "cze": "203", # Czech Republic
- "ddr": "278", # German Democratic Republic
- "deu": "276", # Germany
- "dji": "262", # Djibouti
- "dma": "212", # Dominica
- "dnk": "208", # Denmark
- "dom": "214", # Dominican Republic
- "dza": "012", # Algeria
- "eas": "EAS", # East Asia & Pacific
- "ecs": "ECS", # Europe & Central Asia
- "ecu": "218", # Ecuador
- "egy": "818", # Egypt, Arab Rep.
- "eri": "232", # Eritrea
- "esh": "732", # Western Sahara
- "esp": "724", # Spain
- "est": "233", # Estonia
- "etf": "230", # Ethiopia(includes Eritrea)
- "eth": "231", # Ethiopia(excludes Eritrea)
- "fin": "246", # Finland
- "fji": "242", # Fiji
- "flk": "238", # Falkland Island
- "fra": "250", # France
- "fre": "838", # Free Zones
- "fro": "234", # Faeroe Islands
- "fsm": "583", # Micronesia, Fed. Sts.
- "gab": "266", # Gabon
- "gbr": "826", # United Kingdom
- "geo": "268", # Georgia
- "gha": "288", # Ghana
- "gib": "292", # Gibraltar
- "gin": "324", # Guinea
- "glp": "312", # Guadeloupe
- "gmb": "270", # Gambia, The
- "gnb": "624", # Guinea-Bissau
- "gnq": "226", # Equatorial Guinea
- "grc": "300", # Greece
- "grd": "308", # Grenada
- "grl": "304", # Greenland
- "gtm": "320", # Guatemala
- "guf": "254", # French Guiana
- "gum": "316", # Guam
- "guy": "328", # Guyana
- "hkg": "344", # Hong Kong, China
- "hmd": "334", # Heard Island and McDonald Isla
- "hnd": "340", # Honduras
- "hrv": "191", # Croatia
- "hti": "332", # Haiti
- "hun": "348", # Hungary
- "idn": "360", # Indonesia
- "ind": "356", # India
- "iot": "086", # British Indian Ocean Ter.
- "irl": "372", # Ireland
- "irn": "364", # Iran, Islamic Rep.
- "irq": "368", # Iraq
- "isl": "352", # Iceland
- "isr": "376", # Israel
- "ita": "380", # Italy
- "jam": "388", # Jamaica
- "jor": "400", # Jordan
- "jpn": "392", # Japan
- "kaz": "398", # Kazakhstan
- "ken": "404", # Kenya
- "kgz": "417", # Kyrgyz Republic
- "khm": "116", # Cambodia
- "kir": "296", # Kiribati
- "kna": "659", # St. Kitts and Nevis
- "kor": "410", # Korea, Rep.
- "kwt": "414", # Kuwait
- "lao": "418", # Lao PDR
- "lbn": "422", # Lebanon
- "lbr": "430", # Liberia
- "lby": "434", # Libya
- "lca": "662", # St. Lucia
- "lcn": "LCN", # Latin America & Caribbean
- "lka": "144", # Sri Lanka
- "lso": "426", # Lesotho
- "ltu": "440", # Lithuania
- "lux": "442", # Luxembourg
- "lva": "428", # Latvia
- "mac": "446", # Macao
- "mar": "504", # Morocco
- "mco": "492", # Monaco
- "mda": "498", # Moldova
- "mdg": "450", # Madagascar
- "mdv": "462", # Maldives
- "mea": "MEA", # Middle East, North Africa, Afghanistan & Pakistan
- "mex": "484", # Mexico
- "mhl": "584", # Marshall Islands
- "mkd": "807", # North Macedonia
- "mli": "466", # Mali
- "mlt": "470", # Malta
- "mmr": "104", # Myanmar
- "mng": "496", # Mongolia
- "mnp": "580", # Northern Mariana Islands
- "mnt": "499", # Montenegro
- "moz": "508", # Mozambique
- "mrt": "478", # Mauritania
- "msr": "500", # Montserrat
- "mtq": "474", # Martinique
- "mus": "480", # Mauritius
- "mwi": "454", # Malawi
- "mys": "458", # Malaysia
- "myt": "175", # Mayotte
- "nac": "NAC", # North America
- "nam": "516", # Namibia
- "ncl": "540", # New Caledonia
- "ner": "562", # Niger
- "nfk": "574", # Norfolk Island
- "nga": "566", # Nigeria
- "nic": "558", # Nicaragua
- "niu": "570", # Niue
- "nld": "528", # Netherlands
- "nor": "578", # Norway
- "npl": "524", # Nepal
- "nru": "520", # Nauru
- "nze": "536", # Neutral Zone
- "nzl": "554", # New Zealand
- "oas": "490", # Other Asia, nes
- "omn": "512", # Oman
- "pak": "586", # Pakistan
- "pan": "591", # Panama
- "pce": "582", # Pacific Islands
- "pcn": "612", # Pitcairn
- "per": "604", # Peru
- "phl": "608", # Philippines
- "plw": "585", # Palau
- "png": "598", # Papua New Guinea
- "pol": "616", # Poland
- "prk": "408", # Korea, Dem. Rep.
- "prt": "620", # Portugal
- "pry": "600", # Paraguay
- "pse": "275", # Occ.Pal.Terr
- "pyf": "258", # French Polynesia
- "qat": "634", # Qatar
- "reu": "638", # Reunion
- "rom": "642", # Romania
- "rus": "643", # Russian Federation
- "rwa": "646", # Rwanda
- "sas": "SAS", # South Asia
- "sau": "682", # Saudi Arabia
- "sdn": "736", # Fm Sudan
- "sen": "686", # Senegal
- "ser": "891", # Serbia, FR(Serbia/Montenegro)
- "sgp": "702", # Singapore
- "sgs": "239", # South Georgia and the South Sa
- "shn": "654", # Saint Helena
- "slb": "090", # Solomon Islands
- "sle": "694", # Sierra Leone
- "slv": "222", # El Salvador
- "smr": "674", # San Marino
- "som": "706", # Somalia
- "spe": "839", # Special Categories
- "spm": "666", # Saint Pierre and Miquelon
- "ssd": "728", # South Sudan
- "ssf": "SSF", # Sub-Saharan Africa
- "stp": "678", # Sao Tome and Principe
- "sud": "729", # Sudan
- "sur": "740", # Suriname
- "svk": "703", # Slovak Republic
- "svn": "705", # Slovenia
- "svu": "810", # Soviet Union
- "swe": "752", # Sweden
- "swz": "748", # Eswatini
- "sxm": "534", # Saint Maarten (Dutch part)
- "syc": "690", # Seychelles
- "syr": "760", # Syrian Arab Republic
- "tca": "796", # Turks and Caicos Isl.
- "tcd": "148", # Chad
- "tgo": "768", # Togo
- "tha": "764", # Thailand
- "tjk": "762", # Tajikistan
- "tkl": "772", # Tokelau
- "tkm": "795", # Turkmenistan
- "tmp": "626", # East Timor
- "ton": "776", # Tonga
- "tto": "780", # Trinidad and Tobago
- "tun": "788", # Tunisia
- "tur": "792", # Turkey
- "tuv": "798", # Tuvalu
- "tza": "834", # Tanzania
- "uga": "800", # Uganda
- "ukr": "804", # Ukraine
- "umi": "581", # United States Minor Outlying I
- "uns": "898", # Unspecified
- "ury": "858", # Uruguay
- "usa": "840", # United States
- "usp": "849", # Us Msc.Pac.I
- "uzb": "860", # Uzbekistan
- "vat": "336", # Holy See
- "vct": "670", # St. Vincent and the Grenadines
- "ven": "862", # Venezuela
- "vgb": "092", # British Virgin Islands
- "vnm": "704", # Vietnam
- "vut": "548", # Vanuatu
- "wld": "000", # World
- "wlf": "876", # Wallis and Futura Isl.
- "wsm": "882", # Samoa
- "ydr": "720", # Yemen Democratic
- "yem": "887", # Yemen
- "yug": "890", # Yugoslavia,FR(Serbia/Montenegr
- "zaf": "710", # South Africa
- "zar": "180", # Congo, Dem. Rep.
- "zmb": "894", # Zambia
- "zwe": "716", # Zimbabwe
-}
diff --git a/fincept-qt/scripts/yfinance_data.py b/fincept-qt/scripts/yfinance_data.py
index 26b47cb6f..17de028e1 100644
--- a/fincept-qt/scripts/yfinance_data.py
+++ b/fincept-qt/scripts/yfinance_data.py
@@ -4,6 +4,7 @@ Fetches real-time stock quotes and historical data using yfinance
Returns JSON output for Qt/C++ integration
"""
+import os
import sys
import json
import re
@@ -11,6 +12,67 @@ import yfinance as yf
import pandas as pd
from datetime import datetime
+# Safe JSON output boundary. `json.dumps` defaults to allow_nan=True and emits
+# the bare tokens NaN / Infinity / -Infinity, none of which are valid JSON.
+# QJsonDocument::fromJson() on the C++ side does not repair them — it returns a
+# *null document*, so the host throws away the ENTIRE payload, not just the
+# offending field. One halted bar inside a 250-row series is enough to blank a
+# whole chart with no error shown. Every print/frame boundary in this file goes
+# through fincept_json.
+try:
+ import fincept_json
+except ImportError: # defensive: scripts dir not on sys.path (unusual launcher)
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
+ import fincept_json
+
+# Per-HTTP-request budget for every yfinance call reachable from the daemon.
+# run_daemon() is a strictly serial read -> dispatch -> write loop, so a single
+# unbounded Yahoo request blocks every request queued behind it — quotes,
+# sparklines, history, search and financials all stall together. yfinance's own
+# default is 10s but it is applied per underlying HTTP call and silently
+# inherited; pin it explicitly so the budget is visible and tunable.
+# Override with FINCEPT_YF_TIMEOUT (seconds).
+try:
+ _NET_TIMEOUT = float(os.environ.get("FINCEPT_YF_TIMEOUT", "15"))
+except (TypeError, ValueError):
+ _NET_TIMEOUT = 15.0
+
+
+def _num(value, digits=2):
+ """`round(float(value), digits)`, or None when the cell is NaN / NA / None.
+
+ yfinance returns NaN cells routinely: halted sessions, missing intraday
+ bars, thinly-traded tickers, futures roll gaps. `round(float(nan), 2)` is
+ still nan and nan is not valid JSON (see the fincept_json note above), so
+ an unguarded conversion voids the whole response.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ return round(float(value), digits)
+ except (TypeError, ValueError):
+ return None
+
+
+def _int(value, default=None):
+ """`int(value)`, or `default` when the cell is NaN / NA / None.
+
+ Distinct from _num because `int(nan)` does not merely produce a bad number,
+ it raises ValueError — which is how one missing volume cell used to abort
+ the whole loop and turn an entire price series into {"error": ...}.
+ """
+ if value is None:
+ return default
+ try:
+ if pd.isna(value):
+ return default
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
def get_quote(symbol):
"""Fetch real-time quote for a single symbol"""
try:
@@ -19,7 +81,7 @@ def get_quote(symbol):
_buf = io.StringIO()
with contextlib.redirect_stdout(_buf):
info = ticker.info
- hist = ticker.history(period="1d")
+ hist = ticker.history(period="1d", timeout=_NET_TIMEOUT)
if hist.empty:
return {"error": "No data available", "symbol": symbol}
@@ -62,22 +124,28 @@ def get_historical(symbol, start_date, end_date, interval='1d'):
ticker = yf.Ticker(symbol)
_buf = io.StringIO()
with contextlib.redirect_stdout(_buf):
- hist = ticker.history(start=start_date, end=end_date, interval=interval)
+ hist = ticker.history(start=start_date, end=end_date, interval=interval,
+ timeout=_NET_TIMEOUT)
if hist.empty:
return []
historical_data = []
for index, row in hist.iterrows():
+ # Guard every conversion the way get_batch_quotes already does — a
+ # single NaN bar must not take the whole series with it.
+ close = _num(row['Close'])
+ if close is None:
+ continue # a bar with no close is not a price point
historical_data.append({
"symbol": symbol,
"timestamp": int(index.timestamp()),
- "open": round(float(row['Open']), 2),
- "high": round(float(row['High']), 2),
- "low": round(float(row['Low']), 2),
- "close": round(float(row['Close']), 2),
- "volume": int(row['Volume']),
- "adj_close": round(float(row['Close']), 2)
+ "open": _num(row['Open']),
+ "high": _num(row['High']),
+ "low": _num(row['Low']),
+ "close": close,
+ "volume": _int(row['Volume'], 0),
+ "adj_close": close
})
return historical_data
@@ -105,7 +173,8 @@ def get_historical_price(symbol, target_date):
end = target + timedelta(days=1)
ticker = yf.Ticker(symbol)
- hist = ticker.history(start=start.strftime('%Y-%m-%d'), end=end.strftime('%Y-%m-%d'), interval='1d')
+ hist = ticker.history(start=start.strftime('%Y-%m-%d'), end=end.strftime('%Y-%m-%d'), interval='1d',
+ timeout=_NET_TIMEOUT)
if hist.empty:
return {"found": False, "error": "No data available for this date range", "symbol": symbol}
@@ -251,7 +320,8 @@ def get_batch_quotes(symbols):
_buf = io.StringIO()
with contextlib.redirect_stdout(_buf):
# Use 5d period to guarantee at least 2 trading days for futures/commodities
- data = yf.download(symbols, period="5d", group_by='ticker', progress=False, threads=True, auto_adjust=True)
+ data = yf.download(symbols, period="5d", group_by='ticker', progress=False, threads=True,
+ auto_adjust=True, timeout=_NET_TIMEOUT)
if data is None or data.empty:
return []
@@ -385,7 +455,8 @@ def get_batch_sparklines(symbols, period="5d", interval="1h"):
_buf = io.StringIO()
with contextlib.redirect_stdout(_buf):
data = yf.download(symbols, period=period, interval=interval,
- group_by='ticker', progress=False, threads=True, auto_adjust=True)
+ group_by='ticker', progress=False, threads=True, auto_adjust=True,
+ timeout=_NET_TIMEOUT)
if data is None or data.empty:
return {"error": "No data"}
@@ -735,6 +806,7 @@ def _resolve_for_history(symbols, period):
auto_adjust=True,
progress=False,
threads=True,
+ timeout=_NET_TIMEOUT,
)
finally:
yf_logger.setLevel(prev_level)
@@ -980,20 +1052,25 @@ def get_historical_period(symbol, period='6mo', interval='1d'):
ticker = yf.Ticker(symbol)
_buf = io.StringIO()
with contextlib.redirect_stdout(_buf):
- hist = ticker.history(period=period, interval=interval)
+ hist = ticker.history(period=period, interval=interval, timeout=_NET_TIMEOUT)
if hist.empty:
return []
historical_data = []
for index, row in hist.iterrows():
+ # Same NaN guard as get_historical — this is the chart path, where
+ # one halted bar previously blanked the entire series.
+ close = _num(row['Close'])
+ if close is None:
+ continue
historical_data.append({
"timestamp": int(index.timestamp()),
- "open": round(float(row['Open']), 2),
- "high": round(float(row['High']), 2),
- "low": round(float(row['Low']), 2),
- "close": round(float(row['Close']), 2),
- "volume": int(row['Volume'])
+ "open": _num(row['Open']),
+ "high": _num(row['High']),
+ "low": _num(row['Low']),
+ "close": close,
+ "volume": _int(row['Volume'], 0)
})
return historical_data
@@ -1021,7 +1098,7 @@ def resolve_symbol(symbol):
if '.' in symbol or symbol.startswith('^') or '-' in symbol or '=' in symbol:
try:
ticker = yf.Ticker(symbol)
- hist = ticker.history(period="5d")
+ hist = ticker.history(period="5d", timeout=_NET_TIMEOUT)
exchange = ticker.info.get("exchange", "") if hasattr(ticker, 'info') else ""
if not hist.empty:
return {"resolved_symbol": symbol, "original_symbol": symbol, "exchange": exchange, "found": True}
@@ -1035,7 +1112,7 @@ def resolve_symbol(symbol):
candidate = symbol + suffix
try:
ticker = yf.Ticker(candidate)
- hist = ticker.history(period="5d")
+ hist = ticker.history(period="5d", timeout=_NET_TIMEOUT)
if hist is not None and not hist.empty and len(hist) >= 1:
exchange = ""
try:
@@ -1061,7 +1138,7 @@ def main(args=None):
args = sys.argv[1:]
if len(args) < 1:
- return json.dumps({"error": "Usage: python yfinance_data.py <command> <args>"})
+ return fincept_json.dumps({"error": "Usage: python yfinance_data.py <command> <args>"})
command = args[0]
@@ -1265,9 +1342,8 @@ def main(args=None):
# IMPORTANT: Do NOT use indent=2 here. The host subprocess parser
# looks for the last line starting with '{' or '[' to extract JSON.
# Pretty-printed JSON puts '{' alone on the first line, breaking parsing.
- output = json.dumps(result)
- print(output)
- return output
+ # fincept_json.emit == print(dumps(...)) with NaN/Infinity scrubbed.
+ return fincept_json.emit(result)
# ── Daemon mode ──────────────────────────────────────────────────────────────
#
@@ -1367,7 +1443,7 @@ def run_daemon():
# Ready marker so the C++ host knows imports are done and the worker is
# ready to accept requests. Uses the same framing.
try:
- ready = json.dumps({"ready": True, "pid": __import__("os").getpid()}).encode("utf-8")
+ ready = fincept_json.dumps_bytes({"ready": True, "pid": os.getpid()})
_daemon_write_frame(stdout, ready)
except Exception:
pass
@@ -1380,14 +1456,14 @@ def run_daemon():
req = json.loads(frame.decode("utf-8"))
except Exception as e:
err = {"id": 0, "ok": False, "error": f"bad request JSON: {e}"}
- _daemon_write_frame(stdout, json.dumps(err).encode("utf-8"))
+ _daemon_write_frame(stdout, fincept_json.dumps_bytes(err))
continue
req_id = req.get("id", 0)
action = req.get("action", "")
if action == "shutdown":
resp = {"id": req_id, "ok": True, "result": {"shutdown": True}}
- _daemon_write_frame(stdout, json.dumps(resp).encode("utf-8"))
+ _daemon_write_frame(stdout, fincept_json.dumps_bytes(resp))
break
try:
@@ -1395,10 +1471,21 @@ def run_daemon():
resp = {"id": req_id, "ok": True, "result": result}
except Exception as e:
resp = {"id": req_id, "ok": False, "error": str(e)}
+
+ # Encode before writing. Every request MUST get exactly one response
+ # frame: the host correlates by id and a request that never gets a
+ # frame back only ends when its deadline sweep fires. So if the result
+ # itself can't be serialised, downgrade to an error frame for that id
+ # rather than dropping it (or killing the loop).
+ try:
+ payload_bytes = fincept_json.dumps_bytes(resp)
+ except Exception as e:
+ payload_bytes = fincept_json.dumps_bytes(
+ {"id": req_id, "ok": False, "error": f"unserialisable result for {action}: {e}"})
try:
- _daemon_write_frame(stdout, json.dumps(resp).encode("utf-8"))
+ _daemon_write_frame(stdout, payload_bytes)
except Exception:
- break
+ break # stdout is gone — the host will notice the exit
if __name__ == "__main__":
diff --git a/fincept-qt/src/algo_engine/AlgoEngine.cpp b/fincept-qt/src/algo_engine/AlgoEngine.cpp
index 6987fa9f4..a848c10c6 100644
--- a/fincept-qt/src/algo_engine/AlgoEngine.cpp
+++ b/fincept-qt/src/algo_engine/AlgoEngine.cpp
@@ -6,6 +6,7 @@
#include "datahub/DataHub.h"
#include "storage/sqlite/Database.h"
#include "trading/AccountManager.h"
+#include "trading/ActionCenter.h"
#include "trading/PaperTrading.h"
#include "trading/UnifiedTrading.h"
@@ -37,6 +38,14 @@ AlgoEngine::AlgoEngine() {
// carry fno_bridge_ along. Ownership: deleted in dtor.
fno_bridge_ = new fincept::algo::fno::FnoDataBridge();
+ // Semi-Auto approval outcomes. ActionCenter lives on the main thread and this
+ // engine on engine_thread_, so these arrive queued — which is what we want:
+ // the runner bookkeeping then runs on the runner's own thread.
+ connect(&fincept::trading::ActionCenter::instance(), &fincept::trading::ActionCenter::order_approved, this,
+ &AlgoEngine::on_approval_approved);
+ connect(&fincept::trading::ActionCenter::instance(), &fincept::trading::ActionCenter::order_rejected, this,
+ &AlgoEngine::on_approval_rejected);
+
engine_thread_.setObjectName(QStringLiteral("AlgoEngineThread"));
engine_thread_.start();
moveToThread(&engine_thread_);
@@ -54,6 +63,7 @@ void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployme
const services::algo::AlgoStrategy& strategy) {
QMutexLocker lock(&mutex_);
if (runners_.contains(deployment.id)) {
+ lock.unlock(); // never emit under the (non-recursive) lock — a direct slot would deadlock
emit error_occurred(deployment.id, QStringLiteral("Deployment already running"));
return;
}
@@ -70,7 +80,9 @@ void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployme
connect(runner, &DeploymentRunner::status_changed, this, [this](const QString& id, const QString& status) {
if (status == "stopped" || status == "error") {
QMutexLocker lock(&mutex_);
- if (auto* r = runners_.take(id)) {
+ auto* r = runners_.take(id);
+ lock.unlock(); // never emit under the (non-recursive) lock — a direct slot would deadlock
+ if (r) {
r->deleteLater();
emit deployment_stopped(id);
}
@@ -163,6 +175,34 @@ void AlgoEngine::on_order_requested(const AlgoOrderSignal& signal) {
execute_order(signal);
}
+void AlgoEngine::on_approval_approved(const QString& pending_id, const QString& broker_order_id) {
+ QMutexLocker lock(&mutex_);
+ const QString dep_id = approvals_.take(pending_id);
+ if (dep_id.isEmpty())
+ return; // not one of ours (another screen queued it)
+ auto* runner = runners_.value(dep_id, nullptr);
+ lock.unlock();
+ if (!runner)
+ return; // deployment stopped while the order sat in the queue
+ LOG_INFO("AlgoEngine", QString("Deployment %1: queued order %2 approved -> broker order %3")
+ .arg(dep_id, pending_id, broker_order_id));
+ runner->on_approval_resolved(pending_id, true, broker_order_id, QString());
+}
+
+void AlgoEngine::on_approval_rejected(const QString& pending_id, const QString& reason) {
+ QMutexLocker lock(&mutex_);
+ const QString dep_id = approvals_.take(pending_id);
+ if (dep_id.isEmpty())
+ return;
+ auto* runner = runners_.value(dep_id, nullptr);
+ lock.unlock();
+ if (!runner)
+ return;
+ LOG_WARN("AlgoEngine",
+ QString("Deployment %1: queued order %2 rejected: %3").arg(dep_id, pending_id, reason));
+ runner->on_approval_resolved(pending_id, false, QString(), reason);
+}
+
void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
// Multi-leg F&O basket → dedicated path (paper portfolio / live broker basket).
if (!signal.legs.isEmpty()) {
@@ -216,6 +256,39 @@ void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
const QString account_id = signal.account_id;
+ // ── Semi-Auto approval gate ─────────────────────────────────────────────────
+ // Every other live-order path opts into this (MCP live tools, workflow order
+ // nodes, the equity screen, basket/broadcast dialogs). Without it an account
+ // set to "Semi-Auto — require approval" still had algo deployments firing
+ // unattended orders on it. Mirrors mcp/tools/LiveTradingTools.cpp and
+ // services/workflow/adapters/ServiceBridges.cpp: queue, don't send.
+ if (fincept::trading::ActionCenter::instance().should_queue(account_id, QStringLiteral("placeorder"))) {
+ const QString pending_id = fincept::trading::ActionCenter::instance().queue_order(
+ account_id, QStringLiteral("placeorder"),
+ fincept::trading::ActionCenter::serialize_unified_order(order));
+
+ QMutexLocker lock(&mutex_);
+ auto* runner = runners_.value(dep_id, nullptr);
+ if (pending_id.isEmpty()) {
+ lock.unlock();
+ LOG_ERROR("AlgoEngine",
+ QString("Deployment %1: Semi-Auto queue failed — order dropped (NOT sent)").arg(dep_id));
+ if (runner)
+ runner->on_order_rejected(QString(), QStringLiteral("Semi-Auto: failed to queue for approval"));
+ emit error_occurred(dep_id, QStringLiteral("Order could not be queued for approval"));
+ return;
+ }
+ approvals_.insert(pending_id, dep_id);
+ lock.unlock();
+ // Keeps the runner's in-flight guard held until the user acts, so the
+ // deployment cannot stack one approval request per tick.
+ if (runner)
+ runner->on_order_queued_for_approval(pending_id);
+ LOG_WARN("AlgoEngine", QString("Deployment %1: account %2 is in Semi-Auto — order queued for approval (%3)")
+ .arg(dep_id, account_id, pending_id));
+ return;
+ }
+
(void)QtConcurrent::run([self, dep_id, account_id, order, submitted_price]() {
auto response = fincept::trading::UnifiedTrading::instance().place_order(account_id, order);
diff --git a/fincept-qt/src/algo_engine/AlgoEngine.h b/fincept-qt/src/algo_engine/AlgoEngine.h
index bfbf45629..824e3fe4b 100644
--- a/fincept-qt/src/algo_engine/AlgoEngine.h
+++ b/fincept-qt/src/algo_engine/AlgoEngine.h
@@ -59,6 +59,11 @@ class AlgoEngine : public QObject {
private slots:
void on_order_requested(const fincept::algo::AlgoOrderSignal& signal);
+ // Semi-Auto approval outcomes from ActionCenter, routed back to the runner
+ // that raised the order so its in-flight guard and position bookkeeping stay
+ // correct. Both are no-ops for pending ids this engine did not queue.
+ void on_approval_approved(const QString& pending_id, const QString& broker_order_id);
+ void on_approval_rejected(const QString& pending_id, const QString& reason);
private:
AlgoEngine();
@@ -86,6 +91,9 @@ class AlgoEngine : public QObject {
QThread engine_thread_;
mutable QMutex mutex_;
QHash<QString, DeploymentRunner*> runners_;
+ // ActionCenter pending id → deployment id, for orders this engine parked in
+ // the Semi-Auto approval queue. Guarded by mutex_.
+ QHash<QString, QString> approvals_;
fincept::algo::fno::FnoDataBridge* fno_bridge_ = nullptr;
};
diff --git a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
index 8d845892f..1ae2adbd7 100644
--- a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
+++ b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
@@ -13,6 +13,14 @@ using services::algo::ConditionDef;
namespace {
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
+// A non-finite operand must fail every condition. std::isnan alone is not enough:
+// std::isnan(inf) is false, so an ±inf indicator value (e.g. a % change against a
+// zero reference price) satisfied `inf > threshold` and fired live entries. Every
+// guard below tests this instead of std::isnan.
+inline bool cond_non_finite(double v) {
+ return !std::isfinite(v);
+}
+
bool op_needs_prev(const QString& op) {
return op == "crosses_above" || op == "crosses_below" || op == "rising" || op == "falling" ||
// "==" is a level *touch*: it needs the previous sample to detect the
@@ -43,7 +51,7 @@ bool ConditionEvaluator::is_group_node(const QJsonObject& node) {
}
bool ConditionEvaluator::apply_comparison(double lhs, const QString& op, double rhs) {
- if (std::isnan(lhs) || std::isnan(rhs))
+ if (cond_non_finite(lhs) || cond_non_finite(rhs))
return false;
if (op == ">")
return lhs > rhs;
@@ -60,7 +68,8 @@ bool ConditionEvaluator::apply_comparison(double lhs, const QString& op, double
bool ConditionEvaluator::apply_crossing(double curr, double prev, double target_curr, double target_prev,
const QString& op) {
- if (std::isnan(curr) || std::isnan(prev) || std::isnan(target_curr) || std::isnan(target_prev))
+ if (cond_non_finite(curr) || cond_non_finite(prev) || cond_non_finite(target_curr) ||
+ cond_non_finite(target_prev))
return false;
if (op == "crosses_above")
return prev <= target_prev && curr > target_curr;
@@ -88,7 +97,16 @@ double ConditionEvaluator::operand_value(const QString& indicator, const QJsonOb
*error = r.error;
return kNaN;
}
- return r.current.value(field, kNaN);
+ // Single choke point for every operand: a non-finite indicator value is a data
+ // defect, not a tradeable level. Normalise it to NaN + an error so no operator
+ // downstream can compare against ±inf.
+ const double v = r.current.value(field, kNaN);
+ if (cond_non_finite(v)) {
+ if (error)
+ *error = QStringLiteral("%1 produced a non-finite value").arg(indicator);
+ return kNaN;
+ }
+ return v;
}
ConditionResult ConditionEvaluator::evaluate_single(const ConditionDef& condition,
@@ -135,11 +153,11 @@ ConditionResult ConditionEvaluator::evaluate_single(const ConditionDef& conditio
if (condition.op == "crosses_above" || condition.op == "crosses_below") {
result.met = apply_crossing(lhs_curr, lhs_prev, rhs_curr, rhs_prev, condition.op);
} else if (condition.op == "rising") {
- result.met = !std::isnan(lhs_curr) && !std::isnan(lhs_prev) && lhs_curr > lhs_prev;
+ result.met = !cond_non_finite(lhs_curr) && !cond_non_finite(lhs_prev) && lhs_curr > lhs_prev;
} else if (condition.op == "falling") {
- result.met = !std::isnan(lhs_curr) && !std::isnan(lhs_prev) && lhs_curr < lhs_prev;
+ result.met = !cond_non_finite(lhs_curr) && !cond_non_finite(lhs_prev) && lhs_curr < lhs_prev;
} else if (condition.op == "between") {
- result.met = !std::isnan(lhs_curr) && lhs_curr >= condition.value && lhs_curr <= condition.value2;
+ result.met = !cond_non_finite(lhs_curr) && lhs_curr >= condition.value && lhs_curr <= condition.value2;
result.target_value = condition.value2;
} else if (condition.op == "==") {
// Level touch / equality cross. A live price polled every few seconds skips
@@ -152,11 +170,11 @@ ConditionResult ConditionEvaluator::evaluate_single(const ConditionDef& conditio
tol = 1e-9;
const double curr_diff = lhs_curr - rhs_curr;
const double prev_diff = lhs_prev - rhs_prev; // NaN on the first sample
- if (std::isnan(lhs_curr) || std::isnan(rhs_curr))
+ if (cond_non_finite(lhs_curr) || cond_non_finite(rhs_curr))
result.met = false;
else if (std::abs(curr_diff) <= tol)
result.met = true; // sitting on the level (within float tolerance)
- else if (!std::isnan(prev_diff) && ((prev_diff < 0) != (curr_diff < 0)))
+ else if (!cond_non_finite(prev_diff) && ((prev_diff < 0) != (curr_diff < 0)))
result.met = true; // crossed through the level since the last sample
else
result.met = false;
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.cpp b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
index 22223208e..bd02e9ed3 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.cpp
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
@@ -27,6 +27,8 @@ using fincept::Database;
#include <QVariant>
#include <QtConcurrent>
+#include <cmath>
+
namespace fincept::algo {
DeploymentRunner::DeploymentRunner(const services::algo::AlgoDeployment& deployment,
@@ -104,13 +106,36 @@ void DeploymentRunner::start() {
}
void DeploymentRunner::pause() {
+ if (!running_.load())
+ return;
paused_ = true;
+ // Note: the DB status column is deliberately left as 'running'. recover_orphaned()
+ // only resumes rows in ('running','starting','error','crashed'), so persisting
+ // 'paused' would strand the deployment permanently after a restart. Pause is an
+ // in-process state; a restart resumes the deployment.
emit status_changed(deployment_.id, QStringLiteral("paused"));
LOG_INFO("AlgoEngine", QString("Deployment %1 paused").arg(deployment_.id));
}
void DeploymentRunner::resume() {
+ if (!running_.load())
+ return;
paused_ = false;
+ // No quotes arrive while paused, so last_heartbeat_ms_ is stale — re-stamp it
+ // or the heartbeat immediately flags "no market data in 30s" and errors the
+ // deployment out.
+ last_heartbeat_ms_ = QDateTime::currentMSecsSinceEpoch();
+ // A resume is an explicit human decision to restart a halted deployment, so it
+ // also clears the daily-loss halt (which is otherwise only cleared by the day
+ // rollover in on_heartbeat). Without this, resume() cannot actually resume the
+ // one case that needs it. Logged at WARN because it grants a fresh daily loss
+ // budget for the remainder of the day.
+ if (position_mgr_->is_paused()) {
+ position_mgr_->reset_daily();
+ LOG_WARN("AlgoEngine", QString("Deployment %1: manual resume cleared the daily-loss halt — daily P&L "
+ "reset to 0 for the rest of the day")
+ .arg(deployment_.id));
+ }
emit status_changed(deployment_.id, QStringLiteral("running"));
LOG_INFO("AlgoEngine", QString("Deployment %1 resumed").arg(deployment_.id));
}
@@ -415,6 +440,23 @@ void DeploymentRunner::evaluate_entry(const QVector<OhlcvCandle>& candles) {
return;
}
+ // Order-value ceiling. The equity path below checks this per order; the
+ // basket has no single (qty × price), so sum the legs' notional and run the
+ // same limit. Without this the highest-notional orders the engine places —
+ // multi-leg NFO baskets — were the only ones with no ceiling at all. Checked
+ // before pinning so a rejected basket leaves no leg subscriptions behind.
+ double basket_notional = 0;
+ for (const auto& l : legs)
+ basket_notional += std::abs(l.price * l.quantity);
+ if (!position_mgr_->validate_order_notional(basket_notional)) {
+ LOG_WARN("AlgoEngine", QString("Deployment %1: F&O basket notional %2 (%3 legs) exceeds the max order "
+ "value, skipping entry")
+ .arg(deployment_.id)
+ .arg(basket_notional, 0, 'f', 2)
+ .arg(legs.size()));
+ return;
+ }
+
// Pin the resolved leg symbols into the live WS subscription window so
// they stay fresh for mark-to-market during the life of the position.
QStringList syms;
@@ -556,6 +598,51 @@ void DeploymentRunner::on_order_rejected(const QString& /*broker_order_id*/, con
LOG_ERROR("AlgoEngine", QString("Deployment %1: order rejected: %2").arg(deployment_.id, reason));
}
+void DeploymentRunner::on_order_queued_for_approval(const QString& approval_id) {
+ if (pending_orders_.isEmpty() || approval_id.isEmpty())
+ return;
+ pending_orders_.first().awaiting_approval = true;
+ pending_orders_.first().approval_id = approval_id;
+ LOG_WARN("AlgoEngine", QString("Deployment %1: account is in Semi-Auto — order queued for approval (%2), NOT sent")
+ .arg(deployment_.id, approval_id));
+ emit_live_snapshot(pending_orders_.first().signal.price, QStringLiteral("Awaiting approval in Action Center"));
+}
+
+void DeploymentRunner::on_approval_resolved(const QString& approval_id, bool approved, const QString& broker_order_id,
+ const QString& detail) {
+ if (approval_id.isEmpty())
+ return; // an empty id would match a normal (non-queued) in-flight order
+ int idx = -1;
+ for (int i = 0; i < pending_orders_.size(); ++i) {
+ if (pending_orders_[i].approval_id == approval_id) {
+ idx = i;
+ break;
+ }
+ }
+ if (idx < 0) {
+ // Already purged by the heartbeat (ActionCenter has expired it too). Do
+ // NOT fall through to on_order_filled/on_order_rejected — they resolve the
+ // FIRST pending order, which by now may be an unrelated later signal.
+ LOG_WARN("AlgoEngine", QString("Deployment %1: approval %2 resolved but that order is no longer in flight "
+ "— ignored")
+ .arg(deployment_.id, approval_id));
+ return;
+ }
+
+ const double price = pending_orders_[idx].signal.price;
+ const double qty = pending_orders_[idx].signal.quantity;
+ pending_orders_[idx].awaiting_approval = false;
+ pending_orders_[idx].approval_id.clear();
+
+ if (approved) {
+ // The broker filled it after approval; mark at the signal's reference price
+ // (market orders carry no price), exactly like the un-gated live path.
+ on_order_filled(broker_order_id, price, qty);
+ } else {
+ on_order_rejected(broker_order_id, detail.isEmpty() ? QStringLiteral("rejected in Action Center") : detail);
+ }
+}
+
// ── Multi-leg F&O basket fills (P3.4) ───────────────────────────────────────
// One call per leg from AlgoEngine::execute_basket. Fills accumulate in
// basket_fills_ / basket_rejected_ until the whole in-flight basket is
@@ -667,21 +754,45 @@ void DeploymentRunner::on_heartbeat() {
return;
int64_t now = QDateTime::currentMSecsSinceEpoch();
+ // Day rollover: the daily loss limit latches the runner off (is_paused()
+ // gates every entry/exit evaluation). Without this check the latch never
+ // clears, so a "daily" limit halts the deployment for the lifetime of the
+ // process. The heartbeat is the only tick that keeps running while the
+ // runner is latched, so the reset has to live here.
+ if (position_mgr_->reset_daily_if_new_day()) {
+ LOG_INFO("AlgoEngine", QString("Deployment %1: new trading day — daily P&L and the daily-loss halt were reset")
+ .arg(deployment_.id));
+ emit_live_snapshot(position_mgr_->metrics().current_price,
+ QStringLiteral("New trading day — daily loss limit reset"));
+ }
+
// Keep the DB metrics row fresh (~5s) so the summary cards and any structural
// rebuild show current values instead of stale zeros.
persist_metrics();
// Purge orders that never reported a fill/rejection so a lost ack doesn't
// permanently block new signals (the in-flight guard in emit_order_signal).
+ // An order parked in the Semi-Auto approval queue is NOT a lost ack — it is
+ // waiting on a human — so it keeps the guard until ActionCenter's own TTL
+ // (kPendingOrderTtlMinutes = 15) has certainly expired it. Purging it at 60s
+ // would let the runner re-signal and stack duplicate approval requests.
for (int i = pending_orders_.size() - 1; i >= 0; --i) {
- if (now - pending_orders_[i].submitted_ms > 60000) {
- LOG_WARN("AlgoEngine", QString("Deployment %1: pending order timed out (no fill/reject in 60s), clearing")
- .arg(deployment_.id));
+ const int64_t age = now - pending_orders_[i].submitted_ms;
+ const int64_t limit = pending_orders_[i].awaiting_approval ? 16 * 60000 : 60000;
+ if (age > limit) {
+ LOG_WARN("AlgoEngine", QString("Deployment %1: pending order timed out (no %2 in %3s), clearing")
+ .arg(deployment_.id,
+ pending_orders_[i].awaiting_approval ? QStringLiteral("approval")
+ : QStringLiteral("fill/reject"))
+ .arg(limit / 1000));
pending_orders_.removeAt(i);
}
}
- if (now - last_heartbeat_ms_ > 30000) {
+ // A paused runner drops every quote by design, so the stale-data watchdog must
+ // not treat that silence as a broker outage (it would error the deployment out
+ // 30s into any pause, and AlgoEngine tears the runner down on 'error').
+ if (!paused_.load() && now - last_heartbeat_ms_ > 30000) {
const QString msg = deployment_.broker_id.isEmpty()
? QStringLiteral("No market data in 30s — no broker is attached to this deployment.")
: QString("No market data from broker '%1' in 30s — check the broker is connected "
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.h b/fincept-qt/src/algo_engine/DeploymentRunner.h
index 09f2f7678..3f730baaf 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.h
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.h
@@ -49,6 +49,14 @@ class DeploymentRunner : public QObject {
public slots:
void on_order_filled(const QString& broker_order_id, double fill_price, double fill_qty);
void on_order_rejected(const QString& broker_order_id, const QString& reason);
+ // Semi-Auto approval gate (ActionCenter). The engine calls the first when it
+ // parks the in-flight order in the approval queue instead of sending it, and
+ // the second when the user approves or rejects it. The in-flight guard is
+ // held throughout, so a deployment cannot stack duplicate approval requests
+ // while one is waiting on a human.
+ void on_order_queued_for_approval(const QString& approval_id);
+ void on_approval_resolved(const QString& approval_id, bool approved, const QString& broker_order_id,
+ const QString& detail);
// Multi-leg F&O basket fills (P3.4). One call per leg from AlgoEngine::execute_basket.
// Fills accumulate; once every leg of the in-flight basket is accounted for, an
// entry records the basket position (record_entry_legs) and an exit realizes it
@@ -123,6 +131,11 @@ class DeploymentRunner : public QObject {
QString broker_order_id;
AlgoOrderSignal signal;
int64_t submitted_ms = 0;
+ // Set when the order was parked in the Semi-Auto approval queue instead of
+ // being sent. approval_id is ActionCenter's pending id; it keys the
+ // approve/reject callback back to this exact order.
+ bool awaiting_approval = false;
+ QString approval_id;
};
QVector<PendingOrder> pending_orders_;
diff --git a/fincept-qt/src/algo_engine/IndicatorEngine.cpp b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
index 5888e38c6..df70de5f3 100644
--- a/fincept-qt/src/algo_engine/IndicatorEngine.cpp
+++ b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
@@ -101,7 +101,14 @@ IndicatorResult IndicatorEngine::compute(const QString& name, const QVector<Ohlc
QVector<double> open, high, low, close, vol;
extract_arrays(candles, open, high, low, close, vol);
- int period = params.value("period").toInt(14);
+ // Period/window parameters are divisors *and* array offsets throughout this
+ // file (`sum / period`, `out[period - 1]`, `src[i - period]`, `2/(period+1)`).
+ // A zero or negative period from a malformed strategy therefore produces both
+ // ±inf — which is not NaN, so it survives the evaluator's guards — and
+ // out-of-bounds indexing. Clamp once here instead of in every compute_*.
+ auto at_least_one = [](int v) { return v >= 1 ? v : 1; };
+
+ int period = at_least_one(params.value("period").toInt(14));
// Moving averages
if (name == "SMA")
@@ -119,14 +126,14 @@ IndicatorResult IndicatorEngine::compute(const QString& name, const QVector<Ohlc
if (name == "RSI")
return compute_rsi(close, period);
if (name == "MACD") {
- int fast = params.value("fast").toInt(12);
- int slow = params.value("slow").toInt(26);
- int sig = params.value("signal").toInt(9);
+ int fast = at_least_one(params.value("fast").toInt(12));
+ int slow = at_least_one(params.value("slow").toInt(26));
+ int sig = at_least_one(params.value("signal").toInt(9));
return compute_macd(close, fast, slow, sig);
}
if (name == "STOCHASTIC") {
- int k = params.value("k_period").toInt(14);
- int d = params.value("d_period").toInt(3);
+ int k = at_least_one(params.value("k_period").toInt(14));
+ int d = at_least_one(params.value("d_period").toInt(3));
return compute_stochastic(high, low, close, k, d);
}
if (name == "CCI")
@@ -148,9 +155,9 @@ IndicatorResult IndicatorEngine::compute(const QString& name, const QVector<Ohlc
if (name == "AROON")
return compute_aroon(high, low, period);
if (name == "ICHIMOKU") {
- int tenkan = params.value("tenkan").toInt(9);
- int kijun = params.value("kijun").toInt(26);
- int senkou = params.value("senkou").toInt(52);
+ int tenkan = at_least_one(params.value("tenkan").toInt(9));
+ int kijun = at_least_one(params.value("kijun").toInt(26));
+ int senkou = at_least_one(params.value("senkou").toInt(52));
return compute_ichimoku(high, low, tenkan, kijun, senkou);
}
@@ -174,7 +181,7 @@ IndicatorResult IndicatorEngine::compute(const QString& name, const QVector<Ohlc
if (name == "CMF")
return compute_cmf(high, low, close, vol, period);
if (name == "VOL_WIN_CHG") {
- int window = params.value("window").toInt(10);
+ int window = at_least_one(params.value("window").toInt(10));
return compute_vol_win_chg(vol, window);
}
@@ -469,10 +476,21 @@ IndicatorResult IndicatorEngine::compute_roc(const QVector<double>& close, int p
int n = close.size();
if (n <= period)
return make_error(QStringLiteral("Insufficient data for ROC"));
- double curr = (close[n - 1] - close[n - 1 - period]) / close[n - 1 - period] * 100.0;
+ // A zero reference close (an unfilled bar, or a bad tick that reached the
+ // aggregator) makes this division ±inf. inf is not NaN, so it slips through
+ // every std::isnan guard downstream and compares true against any threshold —
+ // enough to fire a live entry. Fail the indicator instead.
+ const double base = close[n - 1 - period];
+ if (!std::isfinite(base) || std::abs(base) < 1e-10)
+ return make_error(QStringLiteral("ROC: zero/invalid reference price"));
+ double curr = (close[n - 1] - base) / base * 100.0;
double prev = curr;
- if (n > period + 1)
- prev = (close[n - 2] - close[n - 2 - period]) / close[n - 2 - period] * 100.0;
+ if (n > period + 1) {
+ const double prev_base = close[n - 2 - period];
+ prev = (std::isfinite(prev_base) && std::abs(prev_base) >= 1e-10)
+ ? (close[n - 2] - prev_base) / prev_base * 100.0
+ : std::numeric_limits<double>::quiet_NaN();
+ }
return make_result(curr, prev);
}
diff --git a/fincept-qt/src/algo_engine/PositionManager.cpp b/fincept-qt/src/algo_engine/PositionManager.cpp
index 47ee04e2e..d72bb93ff 100644
--- a/fincept-qt/src/algo_engine/PositionManager.cpp
+++ b/fincept-qt/src/algo_engine/PositionManager.cpp
@@ -1,6 +1,7 @@
// src/algo_engine/PositionManager.cpp
#include "algo_engine/PositionManager.h"
+#include <QDate>
#include <QDateTime>
#include <QMutexLocker>
#include <QUuid>
@@ -252,9 +253,13 @@ bool PositionManager::is_paused() const {
}
bool PositionManager::validate_order_value(double qty, double price) const {
+ return validate_order_notional(qty * price);
+}
+
+bool PositionManager::validate_order_notional(double notional) const {
if (max_order_value_ <= 0)
return true;
- return (qty * price) <= max_order_value_;
+ return std::abs(notional) <= max_order_value_;
}
AlgoPosition PositionManager::position() const {
@@ -272,13 +277,35 @@ RiskState PositionManager::risk_state() const {
return risk_;
}
-void PositionManager::reset_daily() {
- QMutexLocker lock(&mutex_);
+void PositionManager::reset_daily_locked() {
risk_.daily_pnl = 0;
risk_.paused_by_loss_limit = false;
risk_.day_start_epoch = QDateTime::currentMSecsSinceEpoch();
}
+void PositionManager::reset_daily() {
+ QMutexLocker lock(&mutex_);
+ reset_daily_locked();
+}
+
+bool PositionManager::reset_daily_if_new_day() {
+ QMutexLocker lock(&mutex_);
+ if (risk_.day_start_epoch <= 0) {
+ // Never stamped (restored state / defensive) — adopt today as day one.
+ risk_.day_start_epoch = QDateTime::currentMSecsSinceEpoch();
+ return false;
+ }
+ // day_start_epoch is stamped with currentMSecsSinceEpoch(), so the matching
+ // trading date is the LOCAL date of that instant. Compare dates, not a fixed
+ // 24h window, so the reset lands on the day boundary regardless of when the
+ // deployment was started.
+ const QDate start_day = QDateTime::fromMSecsSinceEpoch(risk_.day_start_epoch).date();
+ if (start_day >= QDate::currentDate())
+ return false;
+ reset_daily_locked();
+ return true;
+}
+
// ── Multi-leg basket methods (P3) ───────────────────────────────────────────
void PositionManager::record_entry_legs(const QVector<fincept::algo::AlgoLegPosition>& legs, int64_t time_ms) {
diff --git a/fincept-qt/src/algo_engine/PositionManager.h b/fincept-qt/src/algo_engine/PositionManager.h
index c53b3e311..3360b12a2 100644
--- a/fincept-qt/src/algo_engine/PositionManager.h
+++ b/fincept-qt/src/algo_engine/PositionManager.h
@@ -26,12 +26,22 @@ class PositionManager {
bool has_position() const;
bool is_paused() const;
bool validate_order_value(double qty, double price) const;
+ // Same ceiling as validate_order_value, for a pre-computed notional. The
+ // multi-leg F&O basket path has no single (qty × price) — its notional is a
+ // sum over the legs — so it checks the limit through here.
+ bool validate_order_notional(double notional) const;
AlgoPosition position() const;
AlgoMetrics metrics() const;
RiskState risk_state() const;
void update_price(double price);
void reset_daily();
+ // Clears the daily P&L and the loss-limit latch once the local trading date
+ // has moved past day_start_epoch; returns true when that rollover happened.
+ // Without a caller for this the "daily" loss limit latches for the lifetime
+ // of the process — a lifetime limit, not a daily one. The date is taken in
+ // local time, matching how day_start_epoch is stamped in the constructor.
+ bool reset_daily_if_new_day();
// Multi-leg (F&O basket) mode — parallel to the single-position equity path.
void record_entry_legs(const QVector<fincept::algo::AlgoLegPosition>& legs, int64_t time_ms);
@@ -42,6 +52,9 @@ class PositionManager {
private:
void update_drawdown();
+ // Body of reset_daily(); assumes mutex_ is already held (QMutex is not
+ // recursive, so reset_daily_if_new_day() cannot call reset_daily()).
+ void reset_daily_locked();
QString deployment_id_;
AlgoPosition position_;
diff --git a/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp b/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp
index f82f5d7bd..2c26149eb 100644
--- a/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp
+++ b/fincept-qt/src/algo_engine/RealtimeScanRunner.cpp
@@ -120,6 +120,13 @@ void RealtimeScanRunner::on_quote(const QString& symbol, const fincept::trading:
auto it = states_.find(symbol);
if (it == states_.end())
return;
+ // A zero/negative LTP (feed placeholder, pre-open snapshot, malformed tick) must
+ // never reach the candle buffer: a 0 close poisons every ratio indicator, and a
+ // division by it yields ±inf, which is not NaN and so passes the evaluator's
+ // guards. The sweep below already refuses to evaluate at last_price <= 0 — this
+ // closes the same hole one line earlier, at the buffer.
+ if (!(q.ltp > 0))
+ return;
SymbolState* st = it.value();
const int64_t ts = q.timestamp > 0 ? q.timestamp : QDateTime::currentMSecsSinceEpoch();
st->agg->on_tick(q.ltp, q.volume, ts);
diff --git a/fincept-qt/src/algo_engine/ScanMonitor.cpp b/fincept-qt/src/algo_engine/ScanMonitor.cpp
index 57ba1ef38..b0a6fb217 100644
--- a/fincept-qt/src/algo_engine/ScanMonitor.cpp
+++ b/fincept-qt/src/algo_engine/ScanMonitor.cpp
@@ -30,6 +30,19 @@ ScanMonitor& ScanMonitor::instance() {
return s;
}
+ScanMonitor::~ScanMonitor() {
+ // stop_watch() stops the poll timer and posts stop()+deleteLater() to each
+ // realtime runner on scan_thread_; the thread drains those before finishing.
+ // keys() is a copy, so taking entries out of runners_ while iterating is safe.
+ const auto ids = runners_.keys();
+ for (const QString& id : ids)
+ stop_watch(id);
+ if (scan_thread_) {
+ scan_thread_->quit();
+ scan_thread_->wait(3000);
+ }
+}
+
void ScanMonitor::start() {
auto r = ScanWatchRepository::instance().list_active();
if (r.is_err()) {
@@ -59,7 +72,13 @@ void ScanMonitor::start_watch(const ScanWatch& w) {
connect(run->timer, &QTimer::timeout, this, [this, id]() { poll(id); });
runners_.insert(id, run);
run->timer->start();
- poll(id); // evaluate immediately on (re)start
+ // Evaluate on (re)start, but on the next event-loop turn rather than inline:
+ // poll() goes straight to CandleDataFetcher (broker REST / Yahoo) for up to 50
+ // symbols, and start() runs on the pre-window boot path in main.cpp — doing
+ // that work inline delays the first paint. `this` as the context object means
+ // the callback is dropped if the monitor goes away, and poll() re-checks that
+ // the watch still exists.
+ QTimer::singleShot(0, this, [this, id]() { poll(id); });
}
void ScanMonitor::stop_watch(const QString& id) {
diff --git a/fincept-qt/src/algo_engine/ScanMonitor.h b/fincept-qt/src/algo_engine/ScanMonitor.h
index db74bfad1..427e90ff1 100644
--- a/fincept-qt/src/algo_engine/ScanMonitor.h
+++ b/fincept-qt/src/algo_engine/ScanMonitor.h
@@ -37,6 +37,11 @@ class ScanMonitor : public QObject {
private:
ScanMonitor() = default;
+ // Required: scan_thread_ is a running QThread owned by this object. Deleting a
+ // running QThread is qFatal in Qt 6, and this singleton is destroyed after
+ // QApplication unwinds — so without an explicit quit()+wait() every exit that
+ // had a realtime watch running aborted with a crash dialog.
+ ~ScanMonitor() override;
Q_DISABLE_COPY(ScanMonitor)
struct SymState {
diff --git a/fincept-qt/src/app/ScreenSmokeTest.cpp b/fincept-qt/src/app/ScreenSmokeTest.cpp
index f868a3137..f5d3b4457 100644
--- a/fincept-qt/src/app/ScreenSmokeTest.cpp
+++ b/fincept-qt/src/app/ScreenSmokeTest.cpp
@@ -24,6 +24,32 @@ void spin(int ms) {
while (t.elapsed() < ms)
QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
}
+
+// Upper bound on how long one screen may take to materialise before we call it
+// a failure. Generous on purpose: this is a "did it build at all" check, not a
+// performance budget, and it gates releases on shared CI runners.
+constexpr int kConstructDeadlineMs = 8000;
+
+// Settle time after the widget appears, so showEvent-driven child construction
+// runs before we move on. Short because the deadline loop already did the wait.
+constexpr int kSettleMs = 120;
+
+// Wait until `id`'s widget exists, or the deadline expires. Returns the elapsed
+// milliseconds so a slow-but-passing screen can still be reported.
+//
+// A fixed spin() budget was the previous approach and it made this test lie: on
+// a machine under memory pressure, 8 unrelated screens were reported as "did not
+// construct" purely because deferred materialisation had not been serviced yet,
+// and the same binary passed on the next run. Polling costs nothing when things
+// are healthy — it returns on the first iteration — and stops the test failing
+// a release for being busy rather than broken.
+int wait_for_construction(DockScreenRouter* router, const QString& id) {
+ QElapsedTimer t;
+ t.start();
+ while (!router->screen_widget(id) && t.elapsed() < kConstructDeadlineMs)
+ QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
+ return static_cast<int>(t.elapsed());
+}
} // namespace
int run_screen_smoke_test(DockScreenRouter* router) {
@@ -75,12 +101,25 @@ int run_screen_smoke_test(DockScreenRouter* router) {
// ever-growing set → O(n^2) and a multi-minute walk). We only need each
// screen open long enough to construct + fire showEvent.
router->navigate(id, /*exclusive=*/true);
- spin(300);
+ const int waited_ms = wait_for_construction(router, id);
if (!router->screen_widget(id)) {
failures << id;
- std::fprintf(stderr, "[Smoke] !!! %s did not construct\n", qUtf8Printable(id));
+ std::fprintf(stderr, "[Smoke] !!! %s did not construct within %d ms\n", qUtf8Printable(id),
+ kConstructDeadlineMs);
+ std::fflush(stderr);
+ continue;
+ }
+
+ // Let showEvent-driven child construction run before moving on.
+ spin(kSettleMs);
+
+ // Surface slow screens without failing them — a screen that needs seconds
+ // to build is a real finding, just not this test's verdict to make.
+ if (waited_ms > 1000) {
+ std::fprintf(stderr, "[Smoke] ... %s took %d ms to construct\n", qUtf8Printable(id), waited_ms);
std::fflush(stderr);
+ LOG_WARN("Smoke", QString("%1 took %2 ms to construct").arg(id).arg(waited_ms));
}
}
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index b51407cd2..373e7509f 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -97,6 +97,7 @@
#include "ui/navigation/ToolBar.h"
#include "ui/pushpins/PushpinBar.h"
#include "ui/theme/Theme.h"
+#include "ui/widgets/EnterprisePromo.h"
#include "ui/workspace/LayoutOpenDialog.h"
#include "ui/workspace/LayoutSaveAsDialog.h"
@@ -104,6 +105,7 @@
#include <QCloseEvent>
#include <QDateTime>
#include <QDir>
+#include <QEvent>
#include <QFile>
#include <QFileDialog>
#include <QInputDialog>
@@ -112,10 +114,12 @@
#include <QJsonValue>
#include <QMessageBox>
#include <QPalette>
+#include <QPointer>
#include <QScreen>
#include <QSet>
#include <QShortcut>
#include <QStatusBar>
+#include <QTimer>
#include <QToolBar>
#include <QVBoxLayout>
#include <QWindow>
@@ -127,6 +131,51 @@
#include <algorithm>
namespace fincept {
+
+namespace {
+
+/// Binds a QTimer's run state to its host widget's visibility (§P3).
+///
+/// The rule is "start in showEvent, stop in hideEvent", but WindowFrame's header
+/// is shared with the multi-window shell and declares no show/hide overrides, so
+/// the same contract is enforced from an installed event filter instead. Minimise
+/// is covered too: on Windows a minimised top-level gets WindowStateChange, not
+/// Hide, and a minimised window has no reason to keep polling.
+class VisibilityTimerGate final : public QObject {
+ public:
+ VisibilityTimerGate(QTimer* timer, QObject* parent) : QObject(parent), timer_(timer) {}
+
+ protected:
+ bool eventFilter(QObject* watched, QEvent* event) override {
+ if (timer_) {
+ switch (event->type()) {
+ case QEvent::Show:
+ timer_->start();
+ break;
+ case QEvent::Hide:
+ timer_->stop();
+ break;
+ case QEvent::WindowStateChange:
+ if (auto* w = qobject_cast<QWidget*>(watched)) {
+ if (w->isMinimized())
+ timer_->stop();
+ else if (w->isVisible())
+ timer_->start();
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ return QObject::eventFilter(watched, event);
+ }
+
+ private:
+ QPointer<QTimer> timer_;
+};
+
+} // namespace
+
int WindowFrame::next_window_id() {
// Seed from the max of (persisted window IDs, live window IDs) so a new
// window never reuses an ID that already owns saved geometry/dock layout.
@@ -435,7 +484,7 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
});
// MCP navigation tool → dock_router (cross-thread safe)
- EventBus::instance().subscribe("nav.switch_screen", [this](const QVariantMap& nav_data) {
+ EventBus::instance().subscribe(this, "nav.switch_screen", [this](const QVariantMap& nav_data) {
QString screen_id = nav_data["screen_id"].toString();
// Optional: callers that want a clean "take me there" switch (replace the
// current view) rather than the default auto-tiled split set exclusive=true.
@@ -454,7 +503,7 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
// leaving Research. We materialise the trading screen (hidden — no tab switch)
// if it doesn't exist yet, then open its app-modal ticket, which pops over the
// current tab. The trading screen owns the form + the paper/live placement path.
- EventBus::instance().subscribe("equity.open_order_ticket", [this](const QVariantMap& d) {
+ EventBus::instance().subscribe(this, "equity.open_order_ticket", [this](const QVariantMap& d) {
const QString symbol = d.value("symbol").toString();
if (symbol.isEmpty())
return;
@@ -773,6 +822,9 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
auth_stack_->setCurrentIndex(3); // PricingScreen
});
+ // Toolbar UPGRADE → Enterprise (the private edition) promo dialog.
+ connect(toolbar, &ui::ToolBar::upgrade_clicked, this, [this]() { ui::UpgradeDialog::show_now(this); });
+
// Auth state
connect(&auth::AuthManager::instance(), &auth::AuthManager::auth_state_changed, this,
&WindowFrame::on_auth_state_changed);
@@ -929,18 +981,44 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
}
tab_bar_->set_active(last);
}
- // Remaining visible panels on the next tick so the active
- // panel's paint completes before we block again.
- QTimer::singleShot(0, this, [this, last]() {
- if (!dock_router_ || !dock_manager_)
- return;
- for (const auto& entry : dock_manager_->dockWidgetsMap().toStdMap()) {
- if (entry.first == last)
- continue;
- if (entry.second && !entry.second->isClosed())
- dock_router_->materialize_now(entry.first);
+
+ // Remaining visible panels — ONE PER EVENT-LOOP TURN. Doing the
+ // whole loop in a single tick re-froze the window the instant
+ // the first panel painted: a 4-panel layout constructed three
+ // heavy screens back to back with no chance to repaint between
+ // them. Snapshot the ids first so the walk is stable while the
+ // dock map changes underneath it.
+ QStringList pending;
+ for (const auto& entry : dock_manager_->dockWidgetsMap().toStdMap()) {
+ if (entry.first == last)
+ continue;
+ if (entry.second && !entry.second->isClosed())
+ pending << entry.first;
+ }
+ if (pending.isEmpty())
+ return;
+
+ // Copyable, self-rescheduling functor: materialise the head,
+ // then post itself again with the tail. QPointer + the `frame`
+ // context object mean a closed window simply drops the rest.
+ struct MaterialiseWalk {
+ QPointer<WindowFrame> frame;
+ QStringList todo;
+ void operator()() const {
+ if (!frame || todo.isEmpty())
+ return;
+ auto* router = frame->dock_router();
+ if (!router)
+ return;
+ // The user may have closed this panel on an earlier tick.
+ if (auto* dw = router->find_dock_widget(todo.front()); dw && !dw->isClosed())
+ router->materialize_now(todo.front());
+ const QStringList rest = todo.mid(1);
+ if (!rest.isEmpty())
+ QTimer::singleShot(0, frame.data(), MaterialiseWalk{frame, rest});
}
- });
+ };
+ QTimer::singleShot(0, this, MaterialiseWalk{this, pending});
});
}
} else {
@@ -950,8 +1028,7 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
// Periodic refresh of user credits/plan (every 3 minutes). Skip while
// the terminal is locked — we shouldn't be making authenticated API
// calls behind the back of the PIN gate, and the user can't see the
- // refreshed data anyway. The timer keeps running (cheap) but the
- // callback short-circuits.
+ // refreshed data anyway.
user_refresh_timer_ = new QTimer(this);
user_refresh_timer_->setInterval(3 * 60 * 1000);
connect(user_refresh_timer_, &QTimer::timeout, this, []() {
@@ -962,7 +1039,14 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
return;
auth.refresh_user_data();
});
- user_refresh_timer_->start();
+ // §P3: no timer->start() in a constructor. Starting it here made every
+ // window fire an authenticated network refresh every 3 minutes for the
+ // whole process lifetime — including windows that were minimised or never
+ // shown. WindowFrame's header is shared with the multi-window shell, so
+ // rather than add showEvent/hideEvent overrides to it we gate the timer
+ // with an event filter that owns exactly the same lifecycle (and also
+ // covers minimise, which sends WindowStateChange rather than Hide).
+ installEventFilter(new VisibilityTimerGate(user_refresh_timer_, this));
// Confetti overlay (parented to central widget so it covers the whole app)
// Refresh user data when app regains focus (updates toolbar credits/plan)
diff --git a/fincept-qt/src/app/WindowFrame_Setup.cpp b/fincept-qt/src/app/WindowFrame_Setup.cpp
index b6964cd7d..7d7ca1bca 100644
--- a/fincept-qt/src/app/WindowFrame_Setup.cpp
+++ b/fincept-qt/src/app/WindowFrame_Setup.cpp
@@ -293,12 +293,18 @@ void WindowFrame::setup_dock_screens() {
dock_router_->register_factory("trade_viz", []() { return new screens::TradeVizScreen; });
dock_router_->register_factory("docs", []() { return new screens::DocsScreen; });
- // Info/legal pages: static content, safe to construct eagerly.
- dock_router_->register_screen("contact", new screens::ContactScreen);
- dock_router_->register_screen("terms", new screens::TermsScreen);
- dock_router_->register_screen("privacy", new screens::PrivacyScreen);
- dock_router_->register_screen("trademarks", new screens::TrademarksScreen);
- dock_router_->register_screen("help", new screens::HelpScreen);
+ // Info/legal pages. Static content, but "static" is not "free": setup_auth_screens()
+ // above already builds one of each for info_stack_, so register_screen() here made
+ // a SECOND instance of all five per window, none of them visible at startup.
+ // HelpScreen::build_page() alone is ~110-130 widgets each carrying an inline
+ // setStyleSheet — roughly 1,100 widgets and 1,100 CSS parses per window, paid on
+ // the cold-start path. Factories make the dock copies cost nothing until the user
+ // actually opens the panel; the auth-stack copies stay the only eager instances.
+ dock_router_->register_factory("contact", []() { return new screens::ContactScreen; });
+ dock_router_->register_factory("terms", []() { return new screens::TermsScreen; });
+ dock_router_->register_factory("privacy", []() { return new screens::PrivacyScreen; });
+ dock_router_->register_factory("trademarks", []() { return new screens::TrademarksScreen; });
+ dock_router_->register_factory("help", []() { return new screens::HelpScreen; });
}
} // namespace fincept
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 8aa22d1e4..4d19d1eef 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -32,7 +32,9 @@
#include "mcp/McpInit.h"
#include "mcp/ToolSelfTest.h"
#include "network/http/HttpClient.h"
+#include "python/OptionGreeksWorker.h"
#include "python/PythonSetupManager.h"
+#include "python/PythonWorker.h"
#include "screens/launchpad/LaunchpadScreen.h"
#include "screens/recovery/CrashRecoveryDialog.h"
#include "screens/setup/SetupScreen.h"
@@ -85,6 +87,7 @@
#include "services/wallet/TreasuryService.h"
#include "services/wallet/WalletService.h"
#include "storage/HistoricalDataStore.h"
+#include "storage/StorageManager.h"
#include "storage/repositories/NewsArticleRepository.h"
#include "storage/repositories/SettingsRepository.h"
#include "storage/sqlite/CacheDatabase.h"
@@ -104,12 +107,14 @@
#include "ui/tables/LiveTableSelftest.h"
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
+#include "ui/widgets/EnterprisePromo.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QGuiApplication>
#include <QLibrary>
+#include <QMessageBox>
#include <QPointer>
#include <QSqlDatabase>
#include <QSqlQuery>
@@ -119,13 +124,33 @@
#include <QUuid>
#include <algorithm>
+#include <cstddef>
#include <cstdio>
+#include <functional>
#include <memory>
+#include <utility>
+#include <vector>
#ifdef Q_OS_WIN
# include <Windows.h>
#endif
+// Run `steps` one per event-loop turn, in order. A single QTimer::singleShot(0)
+// that does everything is still one uninterruptible main-thread block — the
+// window is frozen for its full duration whether it lands just before or just
+// after the first paint, and that freeze is what users read as "slow startup".
+// Chaining lets the event loop breathe (repaint, input, queued hub deliveries)
+// between groups. Steps must be independent of each other's completion within a
+// turn; only their relative ORDER is guaranteed.
+static void post_chain(std::vector<std::function<void()>> steps, std::size_t i = 0) {
+ if (i >= steps.size())
+ return;
+ QTimer::singleShot(0, qApp, [steps = std::move(steps), i]() mutable {
+ steps[i]();
+ post_chain(std::move(steps), i + 1);
+ });
+}
+
// Wire the two app-level lifecycle handlers that fire after the primary
// window exists: InstanceLock::message_received (a re-launch of the exe
// asks us to bring the running instance to the front — args ignored, the
@@ -319,7 +344,37 @@ int main(int argc, char* argv[]) {
// Must run BEFORE any service init so future phases that lift services
// into the shell can rely on it being present.
fincept::TerminalShell::instance().initialise();
- QObject::connect(&app, &QCoreApplication::aboutToQuit, []() { fincept::TerminalShell::instance().shutdown(); });
+ QObject::connect(&app, &QCoreApplication::aboutToQuit, []() {
+ // MCP first, shell second — deliberate ordering.
+ //
+ // shutdown_mcp() stops TerminalMcpBridge and then every external MCP
+ // server child process (npx/uvx/python). It had ZERO call sites, so
+ // those children were orphaned on every exit and kept running as the
+ // user. It is idempotent, so calling it here is safe even if some other
+ // teardown path reaches it too.
+ //
+ // It must run BEFORE TerminalShell::shutdown() because the shell
+ // teardown closes the workspace DB and deletes CrashRecovery /
+ // WorkspaceSnapshotRing, while MCP's workspace/dashboard tool handlers
+ // read exactly those. Draining MCP first guarantees no tool call is
+ // in flight against a half-torn-down shell.
+ fincept::mcp::shutdown_mcp();
+
+ // Stop the Python daemons before the shell tears anything down.
+ //
+ // Both own a QProcess plus repeating QTimers (PythonWorker gained a
+ // deadline-sweep timer that can call proc_->kill()). Neither had a
+ // shutdown call site: they are singletons, so their destructors run at
+ // STATIC destruction — after QApplication is gone and after the crash
+ // handler is unregistered. A timer or process callback firing in that
+ // window crashes with no minidump and no log line, which is exactly the
+ // kind of exit failure that is near-impossible to diagnose after the
+ // fact. stop() is idempotent on both.
+ fincept::python::PythonWorker::instance().stop();
+ fincept::python::OptionGreeksWorker::instance().stop();
+
+ fincept::TerminalShell::instance().shutdown();
+ });
// Register DataHub payload meta-types (QuoteData, HistoryPoint, InfoData,
// NewsArticle, EconomicsResult) so they can flow through QVariant-keyed
@@ -413,7 +468,17 @@ int main(int argc, char* argv[]) {
// 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, []() {
+ //
+ // Split into three groups run one per event-loop turn (post_chain above).
+ // As a single lambda this was ~180 lines of uninterruptible main-thread
+ // work — 20 hub registrations, prediction-adapter construction with
+ // SecureStorage credential loads, 12 cloud adapters plus a network
+ // refresh_all(), 15 policy patterns, wallet restore, and a live broker
+ // ping sweep — and the window stayed frozen for all of it. Order WITHIN a
+ // group is preserved; the groups only touch their own singletons.
+
+ // ── Group 1: DataHub producer registrations ─────────────────────────────
+ auto init_hub_producers = []() {
// 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();
@@ -463,18 +528,17 @@ int main(int argc, char* argv[]) {
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();
// Algo Engine — `algo:metrics:*`, `algo:trade:*`, `algo:state:*`.
fincept::algo::AlgoEngineProducer::instance().ensure_registered_with_hub();
-
- // Fincept Cloud sync — drains the durable outbox (push) + pulls cloud→local.
- // NOT a DataHub producer; reads stay on the local repo cache. Adapters are
- // registered before initialize(). See fincept-qt/CLOUD_SYNC_PLAN.md.
+ };
+
+ // ── Group 2: Fincept Cloud sync ─────────────────────────────────────────
+ auto init_cloud_sync = []() {
+ // Drains the durable outbox (push) + pulls cloud→local. NOT a DataHub
+ // producer; reads stay on the local repo cache. Every adapter must be
+ // registered before initialize(), which is why they share one group.
+ // See fincept-qt/CLOUD_SYNC_PLAN.md.
fincept::services::cloud::CloudSyncEngine::instance().register_adapter(
&fincept::services::cloud::WatchlistCloudAdapter::instance());
fincept::services::cloud::CloudSyncEngine::instance().register_adapter(
@@ -498,6 +562,15 @@ int main(int argc, char* argv[]) {
fincept::services::cloud::CloudSyncEngine::instance().register_adapter(
&fincept::services::cloud::NotebookCloudAdapter::instance());
fincept::services::cloud::CloudSyncEngine::instance().initialize();
+ };
+
+ // ── Group 3: wallet / treasury / billing + broker session monitor ───────
+ auto init_wallet_treasury_and_monitors = []() {
+ // 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).
{
@@ -591,7 +664,9 @@ int main(int argc, char* argv[]) {
historify_timer->start();
LOG_INFO("App", "Deferred service init complete");
- });
+ };
+
+ post_chain({init_hub_producers, init_cloud_sync, init_wallet_treasury_and_monitors});
// Create all application directories under %LOCALAPPDATA%/com.fincept.terminal
fincept::AppPaths::ensure_all();
@@ -755,13 +830,39 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v048();
fincept::register_migration_v049();
fincept::register_migration_v050();
+ fincept::register_migration_v051();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
auto db_result = fincept::Database::instance().open(db_path);
if (db_result.is_err()) {
- LOG_ERROR("App", "Failed to open database: " + QString::fromStdString(db_result.error()));
- // DB unavailable — apply theme with built-in defaults so the UI is at least styled
+ const std::string db_err = db_result.error();
+ LOG_ERROR("App", "Failed to open database: " + QString::fromStdString(db_err));
+
+ // A FAILED migration is fatal. Booting on regardless produced the worst
+ // possible outcome: a terminal that looks fully functional but is wired
+ // to a half-migrated database, so every repository silently reads and
+ // writes a shape that is neither the old nor the new one. The message
+ // already carries the backup path and the remediation text, so surface
+ // it verbatim and stop.
+ //
+ // A newer-than-build schema never reaches here: MigrationRunner::run()
+ // warns and returns ok() for that case, so the DB opens normally.
+ if (fincept::MigrationRunner::is_fatal_error(db_err)) {
+ QMessageBox::critical(nullptr, QObject::tr("Fincept Terminal — database error"),
+ QString::fromStdString(db_err));
+ // Returning from main() never reaches exec(), so aboutToQuit never
+ // fires and the shell's clean-shutdown marker would never be
+ // written — the next launch would greet the user with a spurious
+ // crash-recovery dialog on top of the database error. shutdown() is
+ // idempotent (it clears initialised_), so calling it here is safe.
+ fincept::TerminalShell::instance().shutdown();
+ return 1; // do NOT continue into the UI
+ }
+
+ // Non-fatal (e.g. the file could not be opened at all) — the app can
+ // still run in a degraded, DB-less state. Apply theme with built-in
+ // defaults so the UI is at least styled.
fincept::ui::apply_global_stylesheet();
} else {
// Load broker accounts now that the DB is open. The AccountManager
@@ -785,6 +886,32 @@ int main(int argc, char* argv[]) {
});
}
+ // Retention sweeper for the append-only tables that had NO reader and NO
+ // retention policy, so they grew for the life of the install:
+ // workflow_audit_log (>90d), telemetry_events (>30d), sync_outbox rows
+ // dead-lettered after 20 failed attempts, and expired unified_cache —
+ // which was previously swept once at startup only, so a terminal left
+ // open for days never reclaimed anything. Runs once now and every ~15
+ // minutes thereafter; idempotent, so a second call creates no second
+ // timer. Started here (inside the DB-open branch) because every policy
+ // is a DELETE against the main DB.
+ //
+ // NOT in --smoke-test / --selftest-* runs: those are short headless
+ // processes that construct screens and exit. Background maintenance has
+ // no value there, and a sweep still in flight when the process tears the
+ // databases down is a shutdown crash with no dump (the crash handler is
+ // already gone by static-destruction time). Detected by scanning argv
+ // because smoke_mode is not computed until much later in main().
+ const bool headless_run = [argc, argv]() {
+ for (int i = 1; i < argc; ++i) {
+ if (qstrcmp(argv[i], "--smoke-test") == 0 || qstrncmp(argv[i], "--selftest", 10) == 0)
+ return true;
+ }
+ return false;
+ }();
+ if (!headless_run)
+ fincept::StorageManager::instance().start_retention_sweeper();
+
// Load persisted font settings and apply before any window is shown
// — eliminates flash/wrong-font-on-startup. Theme is always Obsidian.
{
@@ -906,36 +1033,71 @@ int main(int argc, char* argv[]) {
// Initialize MCP tool system — registers all internal tools and starts
// external MCP servers in the background (non-blocking).
- fincept::mcp::initialize_all_tools();
+ //
+ // ~925 tools across 38 modules, each building nested QJsonObject schemas.
+ // Nothing on the first frame consumes any of it, so it is deferred to the
+ // first event-loop turn — EXCEPT for --selftest-tools / --dump-tools, which
+ // read the registry synchronously and early-return below without ever
+ // reaching QApplication::exec(). Those two must have it up front.
+ {
+ bool tools_needed_synchronously = false;
+ for (int i = 1; i < argc; ++i) {
+ if (qstrcmp(argv[i], "--selftest-tools") == 0 || qstrcmp(argv[i], "--dump-tools") == 0)
+ tools_needed_synchronously = true;
+ }
+ if (tools_needed_synchronously)
+ fincept::mcp::initialize_all_tools();
+ else
+ QTimer::singleShot(0, qApp, []() { fincept::mcp::initialize_all_tools(); });
+ }
// ── Headless tool-system self-test / catalog dump ────────────────────────
// Runs after the real tool registration above but before any window or
// network init, so it exercises exactly what ships. Exits without starting
// the GUI — used by the dev loop and CI to measure tool retrieval recall
// and registry integrity (no LLM / API key required).
+ // Single source of truth for the headless self-test suites. The dispatch below
+ // AND --selftest-list both read this table, so CI enumerates the suites at
+ // runtime instead of hard-coding them.
+ //
+ // A hand-maintained list is exactly how --selftest-live-table came to be
+ // dispatched here while running in no workflow at all: main.cpp had 10 flags,
+ // the CI loop listed 9, and nothing connected the two. Add a suite here and it
+ // is picked up by every job automatically.
+ //
+ // --dump-tools is deliberately NOT in this table: it is a diagnostic dump, not
+ // a pass/fail suite, and CI must not run it as one.
+ struct SelftestSuite {
+ const char* flag;
+ int (*run)();
+ };
+ static constexpr SelftestSuite kSelftestSuites[] = {
+ {"--selftest-tools", &fincept::mcp::run_tool_selftest},
+ {"--selftest-feeds", &fincept::feeds::run_feed_selftest},
+ {"--selftest-dock-layout", &fincept::layout::run_dock_layout_selftest},
+ {"--selftest-live-table", &fincept::ui::run_live_table_selftest},
+ {"--selftest-fno-algo", &fincept::algo::fno::run_fno_algo_selftest},
+ {"--selftest-universe-scan", &fincept::algo::run_universe_scan_selftest},
+ {"--selftest-paper", &fincept::trading::run_paper_trading_selftest},
+ {"--selftest-portfolio-monitor", &fincept::trading::run_portfolio_monitor_selftest},
+ {"--selftest-portfolio-replication", &fincept::trading::replication::run_portfolio_replication_selftest},
+ {"--selftest-arena", &fincept::arena::run_arena_selftest},
+ };
+
for (int i = 1; i < argc; ++i) {
- if (qstrcmp(argv[i], "--selftest-tools") == 0)
- return fincept::mcp::run_tool_selftest();
+ // Machine-readable suite enumeration for CI: one flag per line, exit 0.
+ if (qstrcmp(argv[i], "--selftest-list") == 0) {
+ for (const auto& suite : kSelftestSuites)
+ std::printf("%s\n", suite.flag);
+ std::fflush(stdout);
+ return 0;
+ }
if (qstrcmp(argv[i], "--dump-tools") == 0)
return fincept::mcp::dump_tools_json();
- if (qstrcmp(argv[i], "--selftest-feeds") == 0)
- return fincept::feeds::run_feed_selftest();
- if (qstrcmp(argv[i], "--selftest-dock-layout") == 0)
- return fincept::layout::run_dock_layout_selftest();
- if (qstrcmp(argv[i], "--selftest-live-table") == 0)
- return fincept::ui::run_live_table_selftest();
- if (qstrcmp(argv[i], "--selftest-fno-algo") == 0)
- return fincept::algo::fno::run_fno_algo_selftest();
- if (qstrcmp(argv[i], "--selftest-universe-scan") == 0)
- return fincept::algo::run_universe_scan_selftest();
- if (qstrcmp(argv[i], "--selftest-paper") == 0)
- return fincept::trading::run_paper_trading_selftest();
- if (qstrcmp(argv[i], "--selftest-portfolio-monitor") == 0)
- return fincept::trading::run_portfolio_monitor_selftest();
- if (qstrcmp(argv[i], "--selftest-portfolio-replication") == 0)
- return fincept::trading::replication::run_portfolio_replication_selftest();
- if (qstrcmp(argv[i], "--selftest-arena") == 0)
- return fincept::arena::run_arena_selftest();
+ for (const auto& suite : kSelftestSuites) {
+ if (qstrcmp(argv[i], suite.flag) == 0)
+ return suite.run();
+ }
}
// Start the scan-watch background service. Runs after Database::open() (which
@@ -952,7 +1114,12 @@ int main(int argc, char* argv[]) {
// resting limit/stop/SL-TP orders fill continuously — not only while the
// Equity tab is focused. Placed alongside ScanMonitor (after the self-test
// early-returns, so it stays off in headless --selftest runs).
- fincept::trading::PaperMarkService::instance().start();
+ //
+ // Deferred: start() calls resync() inline, which runs pt_get_positions()
+ // (SQLite) once per active paper account — pre-window main-thread work with
+ // nothing on the first frame depending on it. The singleShot still sits
+ // after the self-test early-returns, so the headless guard is preserved.
+ QTimer::singleShot(0, qApp, []() { fincept::trading::PaperMarkService::instance().start(); });
// Native desktop notifications (Win toast / macOS Notification Center / Linux
// libnotify) via a tray icon — also surfaces every in-app ToastService toast.
@@ -1026,6 +1193,14 @@ int main(int argc, char* argv[]) {
auto* window = new fincept::WindowFrame(primary_id);
window->setAttribute(Qt::WA_DeleteOnClose);
window->show();
+
+ // Enterprise promo, once the frame has painted. Self-
+ // suppresses when the user ticked "Don't show this again"
+ // and when the platform has no window system.
+ QPointer<fincept::WindowFrame> promo_target = window;
+ QTimer::singleShot(1200, &app, [promo_target]() {
+ fincept::ui::UpgradeDialog::maybe_show_at_startup(promo_target.data());
+ });
}
// Wire new-window handler + Launchpad surface now that the
@@ -1086,6 +1261,15 @@ int main(int argc, char* argv[]) {
// runtime (DLL, plugin, or data file like QtWebEngineProcess.exe) shows
// up as a hard process abort or a non-constructing screen here — exactly
// the class of failure the static dependency gate cannot detect.
+ // Enterprise promo, once the frame has painted. Never in --smoke-test:
+ // that run walks every screen headlessly and a modal would block it.
+ if (!smoke_mode) {
+ QPointer<fincept::WindowFrame> promo_target = primary;
+ QTimer::singleShot(1200, &app, [promo_target]() {
+ fincept::ui::UpgradeDialog::maybe_show_at_startup(promo_target.data());
+ });
+ }
+
if (smoke_mode) {
QPointer<fincept::WindowFrame> w = primary;
QTimer::singleShot(2500, &app, [w]() {
@@ -1119,8 +1303,18 @@ int main(int argc, char* argv[]) {
mgr.run_setup();
}
- if (!fincept::ai_chat::LlmService::instance().is_configured())
- LOG_WARN("App", "LLM provider not configured — AI chat will prompt user to configure Settings → LLM Config");
+ // Deferred, and NOT just to save a few ms: is_configured() runs
+ // LlmService::ensure_config(), which on its FIRST call bakes the MCP
+ // tool-category discovery hint into the system prompt and caches it in a
+ // function-local static for the process lifetime. Tool registration is now
+ // deferred (see the initialize_all_tools singleShot above), so calling this
+ // inline would permanently cache a hint built against an empty registry.
+ // Posting it here keeps it strictly after that turn.
+ QTimer::singleShot(0, &app, []() {
+ if (!fincept::ai_chat::LlmService::instance().is_configured())
+ LOG_WARN("App",
+ "LLM provider not configured — AI chat will prompt user to configure Settings → LLM Config");
+ });
// Warm the agent discovery cache on startup. This populates
// AgentService::cached_agents() so any screen that lists agents
diff --git a/fincept-qt/src/auth/AuthApi.cpp b/fincept-qt/src/auth/AuthApi.cpp
index 4abb775dd..2445b72d3 100644
--- a/fincept-qt/src/auth/AuthApi.cpp
+++ b/fincept-qt/src/auth/AuthApi.cpp
@@ -63,20 +63,27 @@ static QString parse_422_detail(const QJsonDocument& doc) {
return msgs.join("\n");
}
-void AuthApi::request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb) {
+void AuthApi::request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb,
+ const QObject* context) {
auto& http = fincept::HttpClient::instance();
auto handle = [cb, endpoint](fincept::Result<QJsonDocument> result) {
- // ── No body / network error path ─────────────────────────────────────
- // HttpClient returns err() only when there is NO parseable JSON body.
- // In that case we fall back to status-based messages.
+ // ── HTTP error / transport error path ────────────────────────────────
+ // Any non-2xx is err(). HttpClient carries the server's own wording in
+ // the error string ("HTTP_<status>: <message>") — prefer it, since that
+ // is where the specific registration/verification failures live. Fall
+ // back to a friendly status-specific message when the body had none.
if (result.is_err()) {
- QString err = QString::fromStdString(result.error());
- int status = 0;
- if (err.startsWith("HTTP_"))
- status = err.mid(5).toInt();
+ const int status = fincept::HttpClient::status_from_error(result.error());
+ // 401/403 are deliberately message-free (HttpClient keeps them a
+ // bare "HTTP_<status>" for session-expiry detection), so they land
+ // in the switch below and get our own wording.
+ QString msg = status > 0 ? fincept::HttpClient::message_from_error(result.error()) : QString{};
+ if (!msg.isEmpty()) {
+ cb({false, {}, msg, status});
+ return;
+ }
- QString msg;
switch (status) {
case 400:
msg = "Bad request. Please check your input.";
@@ -113,13 +120,12 @@ void AuthApi::request(const QString& method, const QString& endpoint, const QJso
return;
}
- // ── JSON body path (covers both success and all HTTP error responses) ─
+ // ── 2xx body path ────────────────────────────────────────────────────
+ // The backend reports most business-logic failures with HTTP 200 and a
+ // {"success": false, ...} envelope, so the checks below still matter.
auto doc = result.value();
auto obj = doc.object();
- // Infer HTTP status from body when available (HttpClient doesn't pass status with ok())
- // We detect error bodies by absence of positive signals below.
-
// 1. Pydantic 422 field-level validation errors: {"detail": [{loc, msg, type}, ...]}
if (obj.contains("detail") && obj["detail"].isArray()) {
QString detail_msg = parse_422_detail(doc);
@@ -162,75 +168,80 @@ void AuthApi::request(const QString& method, const QString& endpoint, const QJso
cb({true, obj, {}, 200});
};
+ // Forward `context` so HttpClient auto-disconnects the handler if the caller
+ // is destroyed mid-flight. Dropping it scoped every callback to the AuthApi
+ // singleton instead of the caller — including PricingScreen's checkout-token
+ // call, which spans a payment-provider round trip (the longest-latency call
+ // in the app, and exactly when a user is likely to close the window).
if (method == "GET")
- http.get(endpoint, handle);
+ http.get(endpoint, handle, context);
else if (method == "POST")
- http.post(endpoint, body, handle);
+ http.post(endpoint, body, handle, context);
else if (method == "PUT")
- http.put(endpoint, body, handle);
+ http.put(endpoint, body, handle, context);
else if (method == "DELETE")
- http.del(endpoint, handle);
+ http.del(endpoint, handle, context);
}
// ── Unauthenticated auth endpoints ───────────────────────────────────────────
-void AuthApi::login(const LoginRequest& req, Callback cb) {
- request("POST", "/user/login", req.to_json(), cb);
+void AuthApi::login(const LoginRequest& req, Callback cb, const QObject* context) {
+ request("POST", "/user/login", req.to_json(), cb, context);
}
-void AuthApi::register_user(const RegisterRequest& req, Callback cb) {
- request("POST", "/user/register", req.to_json(), cb);
+void AuthApi::register_user(const RegisterRequest& req, Callback cb, const QObject* context) {
+ request("POST", "/user/register", req.to_json(), cb, context);
}
-void AuthApi::verify_otp(const VerifyOtpRequest& req, Callback cb) {
- request("POST", "/user/verify-otp", req.to_json(), cb);
+void AuthApi::verify_otp(const VerifyOtpRequest& req, Callback cb, const QObject* context) {
+ request("POST", "/user/verify-otp", req.to_json(), cb, context);
}
-void AuthApi::forgot_password(const ForgotPasswordRequest& req, Callback cb) {
- request("POST", "/user/forgot-password", req.to_json(), cb);
+void AuthApi::forgot_password(const ForgotPasswordRequest& req, Callback cb, const QObject* context) {
+ request("POST", "/user/forgot-password", req.to_json(), cb, context);
}
-void AuthApi::reset_password(const ResetPasswordRequest& req, Callback cb) {
- request("POST", "/user/reset-password", req.to_json(), cb);
+void AuthApi::reset_password(const ResetPasswordRequest& req, Callback cb, const QObject* context) {
+ request("POST", "/user/reset-password", req.to_json(), cb, context);
}
-void AuthApi::verify_mfa(const QString& email, const QString& otp, Callback cb) {
+void AuthApi::verify_mfa(const QString& email, const QString& otp, Callback cb, const QObject* context) {
QJsonObject body;
body["email"] = email;
body["otp"] = otp;
- request("POST", "/user/verify-mfa", body, cb);
+ request("POST", "/user/verify-mfa", body, cb, context);
}
-void AuthApi::redeem_desktop_handoff(const QString& code, Callback cb) {
+void AuthApi::redeem_desktop_handoff(const QString& code, Callback cb, const QObject* context) {
QJsonObject body;
body["token"] = code;
- request("POST", "/user/auth/desktop-handoff/redeem", body, cb);
+ request("POST", "/user/auth/desktop-handoff/redeem", body, cb, context);
}
// ── Authenticated endpoints (HttpClient carries X-API-Key + X-Session-Token) ─
-void AuthApi::logout(Callback cb) {
- request("POST", "/user/logout", {}, cb);
+void AuthApi::logout(Callback cb, const QObject* context) {
+ request("POST", "/user/logout", {}, cb, context);
}
-void AuthApi::session_pulse(Callback cb) {
- request("GET", "/user/session-pulse", {}, cb);
+void AuthApi::session_pulse(Callback cb, const QObject* context) {
+ request("GET", "/user/session-pulse", {}, cb, context);
}
-void AuthApi::get_user_profile(Callback cb) {
- request("GET", "/user/profile", {}, cb);
+void AuthApi::get_user_profile(Callback cb, const QObject* context) {
+ request("GET", "/user/profile", {}, cb, context);
}
// ── Subscription / payment ────────────────────────────────────────────────────
-void AuthApi::get_subscription_plans(Callback cb) {
- request("GET", "/cashfree/plans", {}, cb);
+void AuthApi::get_subscription_plans(Callback cb, const QObject* context) {
+ request("GET", "/cashfree/plans", {}, cb, context);
}
-void AuthApi::generate_checkout_token(const QString& plan_id, Callback cb) {
+void AuthApi::generate_checkout_token(const QString& plan_id, Callback cb, const QObject* context) {
QJsonObject body;
body["plan_id"] = plan_id;
- request("POST", "/user/generate-checkout-token", body, cb);
+ request("POST", "/user/generate-checkout-token", body, cb, context);
}
} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/AuthApi.h b/fincept-qt/src/auth/AuthApi.h
index 41ba4cc7a..6ed94554a 100644
--- a/fincept-qt/src/auth/AuthApi.h
+++ b/fincept-qt/src/auth/AuthApi.h
@@ -16,31 +16,39 @@ class AuthApi : public QObject {
static AuthApi& instance();
+ /// Every method takes an optional `context` that is forwarded to HttpClient,
+ /// which auto-disconnects the reply handler when that object is destroyed.
+ /// Pass `this` from any screen or widget — omitting it scopes the callback
+ /// to the AuthApi singleton, i.e. to the whole app lifetime, so a callback
+ /// fires into a destroyed screen. nullptr is correct only for callers that
+ /// live as long as the app (AuthManager, SessionGuard).
+
// Auth (unauthenticated — no API key needed)
- void login(const LoginRequest& req, Callback cb);
- void register_user(const RegisterRequest& req, Callback cb);
- void verify_otp(const VerifyOtpRequest& req, Callback cb);
- void forgot_password(const ForgotPasswordRequest& req, Callback cb);
- void reset_password(const ResetPasswordRequest& req, Callback cb);
- void verify_mfa(const QString& email, const QString& otp, Callback cb);
+ void login(const LoginRequest& req, Callback cb, const QObject* context = nullptr);
+ void register_user(const RegisterRequest& req, Callback cb, const QObject* context = nullptr);
+ void verify_otp(const VerifyOtpRequest& req, Callback cb, const QObject* context = nullptr);
+ void forgot_password(const ForgotPasswordRequest& req, Callback cb, const QObject* context = nullptr);
+ void reset_password(const ResetPasswordRequest& req, Callback cb, const QObject* context = nullptr);
+ void verify_mfa(const QString& email, const QString& otp, Callback cb, const QObject* context = nullptr);
// Desktop Google login: exchange a one-time handoff code (from the browser
// loopback redirect) for a real session. Unauthenticated.
- void redeem_desktop_handoff(const QString& code, Callback cb);
+ void redeem_desktop_handoff(const QString& code, Callback cb, const QObject* context = nullptr);
// Authenticated (uses api_key stored on HttpClient)
- void logout(Callback cb);
- void session_pulse(Callback cb);
- void get_user_profile(Callback cb);
+ void logout(Callback cb, const QObject* context = nullptr);
+ void session_pulse(Callback cb, const QObject* context = nullptr);
+ void get_user_profile(Callback cb, const QObject* context = nullptr);
// Subscription / payment
- void get_subscription_plans(Callback cb);
- void generate_checkout_token(const QString& plan_id, Callback cb);
+ void get_subscription_plans(Callback cb, const QObject* context = nullptr);
+ void generate_checkout_token(const QString& plan_id, Callback cb, const QObject* context = nullptr);
private:
AuthApi() = default;
- void request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb);
+ void request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb,
+ const QObject* context = nullptr);
};
} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/AuthManager.cpp b/fincept-qt/src/auth/AuthManager.cpp
index 91585c9c0..2b5d2dd62 100644
--- a/fincept-qt/src/auth/AuthManager.cpp
+++ b/fincept-qt/src/auth/AuthManager.cpp
@@ -132,35 +132,55 @@ void AuthManager::load_session() {
void AuthManager::migrate_legacy_plaintext_credentials() {
auto& settings = fincept::SettingsRepository::instance();
auto& secure = fincept::SecureStorage::instance();
- bool migrated = false;
+
+ // Two independent sources, tracked separately: each one only authorises the
+ // purge of the row it actually read. Collapsing them into a single
+ // `migrated` flag let a secret found in the session blob authorise deleting
+ // the *plaintext key row we never managed to read* — one transient DB error
+ // then destroyed the user's only copy of the API key, irrecoverably.
+ bool blob_secrets_migrated = false; // source 1: "fincept_session"
+ bool legacy_row_migrated = false; // source 2: "fincept_api_key"
// 1. Secrets that came in via the legacy plaintext "fincept_session" blob.
if (!session_.api_key.isEmpty()) {
secure.store("api_key", session_.api_key);
- migrated = true;
+ blob_secrets_migrated = true;
}
if (!session_.session_token.isEmpty()) {
secure.store("session_token", session_.session_token);
- migrated = true;
+ blob_secrets_migrated = true;
}
// 2. The standalone plaintext "fincept_api_key" row written by older builds.
+ // A read error is NOT "the row is absent" — the row may still hold the
+ // only copy of the key, so the removal below stays gated on a successful
+ // read.
auto legacy_key = settings.get("fincept_api_key");
- if (legacy_key.is_ok() && !legacy_key.value().isEmpty()) {
+ if (legacy_key.is_err()) {
+ LOG_ERROR("Auth",
+ QString("settings read failed for 'fincept_api_key' — leaving the legacy plaintext row untouched "
+ "(it may hold the only copy of the key): %1")
+ .arg(QString::fromStdString(legacy_key.error())));
+ } else if (!legacy_key.value().isEmpty()) {
if (session_.api_key.isEmpty())
session_.api_key = legacy_key.value();
secure.store("api_key", legacy_key.value());
- migrated = true;
+ legacy_row_migrated = true;
}
- if (migrated) {
- // Rewrite fincept_session without secrets and drop the plaintext key row
- // so the cleartext copies no longer exist on disk for this install.
+ // Rewrite fincept_session without secrets only when the blob actually
+ // carried some — a source-2-only migration has nothing to scrub there, and
+ // writing a session we may have failed to load would drop its non-secret
+ // fields too.
+ if (blob_secrets_migrated) {
QJsonDocument doc(session_.to_persisted_json());
settings.set("fincept_session", QString::fromUtf8(doc.toJson(QJsonDocument::Compact)), "auth");
+ }
+ if (legacy_row_migrated)
settings.remove("fincept_api_key");
+
+ if (blob_secrets_migrated || legacy_row_migrated)
LOG_INFO("Auth", "Migrated legacy plaintext credentials into SecureStorage and purged settings rows");
- }
}
QString AuthManager::fincept_api_key() const {
diff --git a/fincept-qt/src/auth/ConstantTime.h b/fincept-qt/src/auth/ConstantTime.h
new file mode 100644
index 000000000..398143d37
--- /dev/null
+++ b/fincept-qt/src/auth/ConstantTime.h
@@ -0,0 +1,38 @@
+#pragma once
+// Constant-time comparison helpers for secrets.
+//
+// Any comparison of a user- or network-supplied value against a secret (PIN
+// hash, bridge token, OAuth state nonce) must not short-circuit on the first
+// differing byte: the timing difference leaks how many leading bytes were
+// correct, which turns an infeasible guess into a byte-at-a-time search.
+//
+// Header-only so the loopback HTTP bridges (services/wallet/*, mcp/*) and the
+// auth layer share one implementation instead of each rolling their own.
+
+#include <QByteArray>
+#include <QString>
+
+namespace fincept::auth {
+
+/// Returns true iff `a` and `b` are the same length AND every byte matches.
+/// The XOR-accumulate loop touches every byte even on mismatch so execution
+/// time does not reveal the first differing index.
+///
+/// Length is compared first and therefore still observable — that is inherent
+/// and harmless for the fixed-width secrets we compare.
+inline bool constant_time_equals(const QByteArray& a, const QByteArray& b) {
+ if (a.size() != b.size())
+ return false;
+ unsigned char diff = 0;
+ const qsizetype n = a.size();
+ for (qsizetype i = 0; i < n; ++i)
+ diff |= static_cast<unsigned char>(a[i]) ^ static_cast<unsigned char>(b[i]);
+ return diff == 0;
+}
+
+/// UTF-8 overload for QString secrets (tokens, nonces).
+inline bool constant_time_equals(const QString& a, const QString& b) {
+ return constant_time_equals(a.toUtf8(), b.toUtf8());
+}
+
+} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/GoogleDesktopLogin.cpp b/fincept-qt/src/auth/GoogleDesktopLogin.cpp
index f2611f3d0..3cad475e6 100644
--- a/fincept-qt/src/auth/GoogleDesktopLogin.cpp
+++ b/fincept-qt/src/auth/GoogleDesktopLogin.cpp
@@ -1,11 +1,14 @@
#include "auth/GoogleDesktopLogin.h"
+#include "auth/ConstantTime.h"
+#include "auth/LoopbackGuard.h"
#include "core/config/AppConfig.h"
#include "core/logging/Logger.h"
#include <QByteArray>
#include <QDesktopServices>
#include <QHostAddress>
+#include <QRandomGenerator>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
@@ -16,6 +19,17 @@
namespace fincept::auth {
+namespace {
+// 128 bits from the OS CSPRNG. QRandomGenerator::system() — the plain
+// QRandomGenerator is deterministically seeded and unusable for a nonce.
+QString make_state_nonce() {
+ quint32 words[4];
+ QRandomGenerator::system()->fillRange(words);
+ const QByteArray raw(reinterpret_cast<const char*>(words), static_cast<qsizetype>(sizeof(words)));
+ return QString::fromLatin1(raw.toHex());
+}
+} // namespace
+
GoogleDesktopLogin::GoogleDesktopLogin(QObject* parent) : QObject(parent) {}
GoogleDesktopLogin::~GoogleDesktopLogin() = default;
@@ -25,14 +39,19 @@ void GoogleDesktopLogin::start() {
connect(server_, &QTcpServer::newConnection, this, &GoogleDesktopLogin::on_new_connection);
// Loopback only, ephemeral port — the website's open-redirect guard accepts
- // exactly 127.0.0.1 / localhost / [::1].
+ // exactly 127.0.0.1 / localhost / [::1]. Do not widen this bind.
if (!server_->listen(QHostAddress::LocalHost, 0)) {
finish_error(tr("Could not start the local login listener."));
return;
}
- const quint16 port = server_->serverPort();
- const QString callback = QString("http://127.0.0.1:%1").arg(port);
+ port_ = server_->serverPort();
+ state_ = make_state_nonce();
+ // Carry the CSRF nonce on the callback URL itself. The API appends
+ // ?code=... to desktop_cb, so a correct implementation preserves an
+ // existing query and echoes state back to us. Verified in
+ // on_new_connection(); see the note there about the tolerant fallback.
+ const QString callback = QString("http://127.0.0.1:%1/?state=%2").arg(port_).arg(state_);
// Open the API's server-side OAuth start endpoint (it redirects to Google and
// does the token exchange). Same base as HttpClient so dev/staging overrides
@@ -50,7 +69,8 @@ void GoogleDesktopLogin::start() {
connect(timeout_, &QTimer::timeout, this, [this]() { finish_error(tr("Login timed out. Please try again.")); });
timeout_->start(kTimeoutMs);
- LOG_INFO("GoogleLogin", QString("Loopback listening on %1; opening browser").arg(callback));
+ // Log the port only — `callback` carries the state nonce.
+ LOG_INFO("GoogleLogin", QString("Loopback listening on 127.0.0.1:%1; opening browser").arg(port_));
if (!QDesktopServices::openUrl(start_url))
finish_error(tr("Could not open the browser for Google sign-in."));
@@ -66,21 +86,78 @@ void GoogleDesktopLogin::on_new_connection() {
connect(sock, &QTcpSocket::readyRead, this, [this, sock, buffer]() {
buffer->append(sock->readAll());
- // We only need the request line: "GET /?code=<code> HTTP/1.1".
- const int line_end = buffer->indexOf("\r\n");
- if (line_end < 0)
- return; // wait for the full request line
+ // Wait for the whole header block — the guards below read headers, not
+ // just the request line.
+ if (buffer->indexOf("\r\n\r\n") < 0 && buffer->indexOf("\n\n") < 0) {
+ if (buffer->size() < 16384)
+ return;
+ send_page(sock, tr("Fincept"), tr("Malformed request."));
+ sock->disconnectFromHost();
+ return;
+ }
- const QByteArray request_line = buffer->left(line_end);
+ const qsizetype line_end = buffer->indexOf('\n');
+ QByteArray request_line = buffer->left(line_end);
+ if (request_line.endsWith('\r'))
+ request_line.chop(1);
const QList<QByteArray> parts = request_line.split(' ');
- if (parts.size() < 2) {
+ if (parts.size() < 2 || parts.at(0) != "GET") {
send_page(sock, tr("Fincept"), tr("Malformed request."));
sock->disconnectFromHost();
return;
}
- const QUrl url(QStringLiteral("http://127.0.0.1") + QString::fromUtf8(parts[1]));
- const QString code = QUrlQuery(url).queryItemValue("code");
+ // Host + fetch-metadata guard: rejects DNS rebinding and any
+ // cross-origin subresource injection (an `<img src>` / `fetch()` from
+ // some other page the user has open). See auth/LoopbackGuard.h.
+ const auto check = fincept::auth::check_loopback_request(*buffer, port_);
+ if (!check.allowed) {
+ LOG_WARN("GoogleLogin", "Rejected loopback callback: " + check.reason);
+ send_page(sock, tr("Fincept"), tr("Request rejected."));
+ sock->disconnectFromHost();
+ return;
+ }
+
+ // desktop_cb now carries `?state=<nonce>`, so the API may end up
+ // appending its own `?code=...` instead of `&code=...`. Normalise any
+ // second '?' to '&' before parsing so a naive concatenation on the
+ // server side still yields a readable `code`.
+ QByteArray target = parts[1];
+ const qsizetype qmark = target.indexOf('?');
+ if (qmark >= 0) {
+ for (qsizetype i = qmark + 1; i < target.size(); ++i) {
+ if (target[i] == '?')
+ target[i] = '&';
+ }
+ }
+
+ const QUrl url(QStringLiteral("http://127.0.0.1") + QString::fromUtf8(target));
+ const QUrlQuery query(url);
+ const QString code = query.queryItemValue("code");
+
+ // CSRF state check. A cross-site *navigation* to this port is
+ // header-indistinguishable from the real callback, so the nonce is the
+ // only gate that stops it.
+ //
+ // Tolerant when the nonce is absent rather than hard-failing: the API
+ // owns the desktop_cb → redirect construction, and if it rebuilds the
+ // URL instead of appending to it, `state` never comes back and a strict
+ // check would lock every user out of Google sign-in. The warning below
+ // fires on the very first login if that happens — once the round trip
+ // is confirmed in production, delete the `echoed.isEmpty()` branch and
+ // make a missing state a rejection.
+ if (!code.isEmpty()) {
+ const QString echoed = query.queryItemValue("state");
+ if (echoed.isEmpty()) {
+ LOG_WARN("GoogleLogin", "Callback carried no state nonce — the API is not echoing desktop_cb's "
+ "query back. CSRF protection is degraded until it does.");
+ } else if (!fincept::auth::constant_time_equals(echoed, state_)) {
+ LOG_WARN("GoogleLogin", "Rejected loopback callback: state nonce mismatch");
+ send_page(sock, tr("Fincept"), tr("Request rejected."));
+ sock->disconnectFromHost();
+ return;
+ }
+ }
if (code.isEmpty()) {
// Secondary request (e.g. /favicon.ico) or callback without a code.
diff --git a/fincept-qt/src/auth/GoogleDesktopLogin.h b/fincept-qt/src/auth/GoogleDesktopLogin.h
index a8cf8ec3f..3d9192328 100644
--- a/fincept-qt/src/auth/GoogleDesktopLogin.h
+++ b/fincept-qt/src/auth/GoogleDesktopLogin.h
@@ -39,6 +39,10 @@ class GoogleDesktopLogin : public QObject {
QTcpServer* server_ = nullptr;
QTimer* timeout_ = nullptr;
bool done_ = false;
+ quint16 port_ = 0;
+ // Per-attempt CSRF nonce. Sent to the API as part of desktop_cb's query and
+ // verified when the callback echoes it back. See on_new_connection().
+ QString state_;
// ~5 min: a new Google user is detoured through the website /complete-profile
// form before the loopback code is issued, so the wait can be well over 2 min.
diff --git a/fincept-qt/src/auth/LoopbackGuard.h b/fincept-qt/src/auth/LoopbackGuard.h
new file mode 100644
index 000000000..10b3be50a
--- /dev/null
+++ b/fincept-qt/src/auth/LoopbackGuard.h
@@ -0,0 +1,143 @@
+#pragma once
+// Request-origin validation for the terminal's loopback HTTP listeners.
+//
+// Five servers in this codebase bind 127.0.0.1 and hand out or accept something
+// sensitive: the broker OAuth redirect catcher (trading/auth/RedirectServer),
+// the Google desktop-login catcher (auth/GoogleDesktopLogin), the wallet
+// connect bridge and the wallet transaction bridge (services/wallet/*), and the
+// agent MCP bridge (mcp/TerminalMcpBridge). Binding loopback keeps other hosts
+// out, but it does NOT keep out the user's own browser — and that is the actual
+// attacker here:
+//
+// * Any web page the user has open can issue a cross-origin subresource
+// request to http://127.0.0.1:<port>/... An `<img src>` or a no-cors
+// `fetch()` is a CORS *simple* request: the page cannot read the response,
+// but the request still arrives and is still acted on. Against a fixed,
+// guessable port (5010 / 5011) that is enough to feed an attacker-chosen
+// OAuth token into the terminal, or to race the real redirect.
+// * A page can also point a hostname it controls at 127.0.0.1 (DNS
+// rebinding) and then talk to the listener as same-origin, defeating any
+// origin check that only looks at the socket address.
+//
+// Two header checks close both holes, and neither costs anything legitimate:
+//
+// Host — must be our own loopback authority. A rebound request carries
+// the attacker's hostname, so this rejects it outright.
+// Sec-Fetch-* — sent by every current browser and not forgeable by page JS.
+// A genuine OAuth redirect or a wallet return trip is a top-level
+// navigation (`Sec-Fetch-Mode: navigate`). An injected `<img>`,
+// `<script>`, `fetch()` or XHR is not. Rejecting cross-site
+// non-navigations kills the injection while leaving the real
+// flows untouched. Requests from our own served page are
+// `Sec-Fetch-Site: same-origin` and always pass.
+//
+// A non-browser client (curl, a local script, an older browser) sends no
+// Sec-Fetch-* headers at all. Those requests are allowed through: the header
+// set is a browser-only signal and every listener still has its own token /
+// nonce / single-use gate behind this. This is defence in depth, not the only
+// lock on the door.
+//
+// Header-only so all five listeners can share it without a new translation
+// unit.
+
+#include <QByteArray>
+#include <QString>
+
+namespace fincept::auth {
+
+/// Case-insensitive lookup of an HTTP header value in a raw request buffer.
+/// `raw_request` may be the whole request or just the head; parsing stops at
+/// the blank line that ends the header block. Returns an empty QByteArray when
+/// the header is absent.
+inline QByteArray http_header_value(const QByteArray& raw_request, const char* name) {
+ const QByteArray needle = QByteArray(name).toLower();
+ qsizetype pos = raw_request.indexOf('\n');
+ if (pos < 0)
+ return {};
+ ++pos; // skip the request line
+ while (pos < raw_request.size()) {
+ qsizetype eol = raw_request.indexOf('\n', pos);
+ if (eol < 0)
+ eol = raw_request.size();
+ QByteArray line = raw_request.mid(pos, eol - pos);
+ if (line.endsWith('\r'))
+ line.chop(1);
+ if (line.isEmpty())
+ break; // end of header block
+ const qsizetype colon = line.indexOf(':');
+ if (colon > 0 && line.left(colon).trimmed().toLower() == needle)
+ return line.mid(colon + 1).trimmed();
+ pos = eol + 1;
+ }
+ return {};
+}
+
+/// True when `authority` is one of our own loopback authorities for `port`.
+inline bool is_loopback_authority(const QByteArray& authority, quint16 port) {
+ if (authority.isEmpty())
+ return false;
+ const QByteArray suffix = ':' + QByteArray::number(port);
+ if (!authority.endsWith(suffix))
+ return false;
+ const QByteArray host = authority.left(authority.size() - suffix.size()).toLower();
+ return host == "127.0.0.1" || host == "localhost" || host == "[::1]";
+}
+
+/// True when `origin` is one of our own loopback origins for `port`.
+/// An absent origin, or the opaque `null` origin, is not our origin.
+inline bool is_own_loopback_origin(const QByteArray& origin, quint16 port) {
+ QByteArray o = origin.trimmed();
+ if (o.isEmpty() || o.toLower() == "null")
+ return false;
+ if (o.startsWith("http://"))
+ o = o.mid(7);
+ else if (o.startsWith("https://"))
+ o = o.mid(8);
+ else
+ return false;
+ return is_loopback_authority(o, port);
+}
+
+struct LoopbackCheck {
+ bool allowed = true;
+ QString reason; ///< populated only when allowed == false; safe to log
+};
+
+/// Validate a raw HTTP request against the two browser-facing threats above.
+///
+/// `port` is the port this listener is actually bound to.
+/// `allow_cross_site_navigation` must be true for the OAuth / wallet callbacks,
+/// which legitimately arrive as a top-level navigation from a third-party site.
+/// Set it false for a listener that should only ever be talked to by the page
+/// it served itself.
+inline LoopbackCheck check_loopback_request(const QByteArray& raw_request, quint16 port,
+ bool allow_cross_site_navigation = true) {
+ // ── Host: blocks DNS rebinding ──────────────────────────────────────────
+ const QByteArray host = http_header_value(raw_request, "Host");
+ if (host.isEmpty())
+ return {false, QStringLiteral("missing Host header")};
+ if (!is_loopback_authority(host, port))
+ return {false, QStringLiteral("unexpected Host '%1'").arg(QString::fromLatin1(host))};
+
+ // ── Fetch metadata: blocks cross-origin subresource injection ───────────
+ const QByteArray site = http_header_value(raw_request, "Sec-Fetch-Site").toLower();
+ if (!site.isEmpty() && site != "same-origin" && site != "none") {
+ const QByteArray mode = http_header_value(raw_request, "Sec-Fetch-Mode").toLower();
+ if (!(allow_cross_site_navigation && mode == "navigate")) {
+ return {false, QStringLiteral("cross-site request (Sec-Fetch-Site: %1, Sec-Fetch-Mode: %2)")
+ .arg(QString::fromLatin1(site), QString::fromLatin1(mode))};
+ }
+ }
+
+ // ── Origin: a cross-origin CORS request never belongs here ──────────────
+ // Top-level GET navigations send no Origin at all, so the real callbacks
+ // are unaffected. Anything that DOES send one must be our own page.
+ const QByteArray origin = http_header_value(raw_request, "Origin");
+ if (!origin.isEmpty() && origin.toLower() != "null" && !is_own_loopback_origin(origin, port)) {
+ return {false, QStringLiteral("cross-origin request from '%1'").arg(QString::fromLatin1(origin))};
+ }
+
+ return {true, {}};
+}
+
+} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/PinManager.cpp b/fincept-qt/src/auth/PinManager.cpp
index 7b3c4d83f..a9f5ee84c 100644
--- a/fincept-qt/src/auth/PinManager.cpp
+++ b/fincept-qt/src/auth/PinManager.cpp
@@ -1,5 +1,6 @@
#include "auth/PinManager.h"
+#include "auth/ConstantTime.h"
#include "auth/SecurityAuditLog.h"
#include "core/logging/Logger.h"
#include "storage/secure/SecureStorage.h"
@@ -13,18 +14,10 @@ namespace fincept::auth {
namespace {
-// Constant-time byte comparison. Returns true iff a and b are the same length
-// AND every byte matches. The XOR-accumulate loop touches every byte even on
-// mismatch so execution time does not reveal the first differing index.
-bool constant_time_equals(const QByteArray& a, const QByteArray& b) {
- if (a.size() != b.size())
- return false;
- unsigned char diff = 0;
- const int n = a.size();
- for (int i = 0; i < n; ++i)
- diff |= static_cast<unsigned char>(a[i]) ^ static_cast<unsigned char>(b[i]);
- return diff == 0;
-}
+// constant_time_equals now lives in auth/ConstantTime.h so the loopback HTTP
+// bridges share one implementation. Keeping a second copy in this anonymous
+// namespace would make the unqualified call below ambiguous the moment a
+// unity-build batch pulls both into the same translation unit.
// Reject trivially weak 6-digit PINs. Returns an error message or empty string
// if the PIN is acceptable. Centralized here (not in UI) so every caller —
diff --git a/fincept-qt/src/auth/UserApi.cpp b/fincept-qt/src/auth/UserApi.cpp
index acaadee90..2f9f09cf7 100644
--- a/fincept-qt/src/auth/UserApi.cpp
+++ b/fincept-qt/src/auth/UserApi.cpp
@@ -12,16 +12,22 @@ UserApi& UserApi::instance() {
return s;
}
-void UserApi::request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb) {
+void UserApi::request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb,
+ const QObject* context) {
auto& http = fincept::HttpClient::instance();
auto handle = [cb](fincept::Result<QJsonDocument> result) {
if (result.is_err()) {
- QString err = QString::fromStdString(result.error());
- int status = 0;
- if (err.startsWith("HTTP_"))
- status = err.mid(5).toInt();
- QString msg;
+ const int status = fincept::HttpClient::status_from_error(result.error());
+ // Prefer the server's own wording — HttpClient carries it in the
+ // error string ("HTTP_<status>: <message>") rather than handing the
+ // error body back as ok(). 401/403 stay message-free by design and
+ // fall through to our own wording below.
+ QString msg = status > 0 ? fincept::HttpClient::message_from_error(result.error()) : QString{};
+ if (!msg.isEmpty()) {
+ cb({false, {}, msg, status});
+ return;
+ }
switch (status) {
case 401:
msg = "Session expired. Please log in again.";
@@ -56,107 +62,112 @@ void UserApi::request(const QString& method, const QString& endpoint, const QJso
cb({true, obj, {}, 200});
};
+ // Forward `context` so HttpClient auto-disconnects the handler if the caller
+ // is destroyed mid-flight. Dropping it scoped every callback to the UserApi
+ // singleton instead, i.e. to the whole app lifetime — which is the opposite
+ // of what HttpClient's `context` parameter exists for.
if (method == "GET")
- http.get(endpoint, handle);
+ http.get(endpoint, handle, context);
else if (method == "POST")
- http.post(endpoint, body, handle);
+ http.post(endpoint, body, handle, context);
else if (method == "PUT")
- http.put(endpoint, body, handle);
+ http.put(endpoint, body, handle, context);
else if (method == "DELETE") {
if (body.isEmpty())
- http.del(endpoint, handle);
+ http.del(endpoint, handle, context);
else
- http.del(endpoint, body, handle);
+ http.del(endpoint, body, handle, context);
}
}
// ── Profile ──────────────────────────────────────────────────────────────────
-void UserApi::get_user_profile(Callback cb) {
- request("GET", "/user/profile", {}, cb);
+void UserApi::get_user_profile(Callback cb, const QObject* context) {
+ request("GET", "/user/profile", {}, cb, context);
}
-void UserApi::update_user_profile(const QJsonObject& data, Callback cb) {
- request("PUT", "/user/profile", data, cb);
+void UserApi::update_user_profile(const QJsonObject& data, Callback cb, const QObject* context) {
+ request("PUT", "/user/profile", data, cb, context);
}
-void UserApi::regenerate_api_key(Callback cb) {
- request("POST", "/user/regenerate-api-key", {}, cb);
+void UserApi::regenerate_api_key(Callback cb, const QObject* context) {
+ request("POST", "/user/regenerate-api-key", {}, cb, context);
}
-void UserApi::get_user_credits(Callback cb) {
- request("GET", "/user/credits", {}, cb);
+void UserApi::get_user_credits(Callback cb, const QObject* context) {
+ request("GET", "/user/credits", {}, cb, context);
}
-void UserApi::delete_user_account(const QString& confirm_email, const QString& password, Callback cb) {
+void UserApi::delete_user_account(const QString& confirm_email, const QString& password, Callback cb,
+ const QObject* context) {
QJsonObject body;
body.insert("confirm", true);
body.insert("email", confirm_email);
body.insert("password", password);
- request("DELETE", "/user/account", body, cb);
+ request("DELETE", "/user/account", body, cb, context);
}
-void UserApi::get_user_usage(int days, Callback cb) {
- request("GET", QString("/user/usage?days=%1").arg(days), {}, cb);
+void UserApi::get_user_usage(int days, Callback cb, const QObject* context) {
+ request("GET", QString("/user/usage?days=%1").arg(days), {}, cb, context);
}
// ── Login history ────────────────────────────────────────────────────────────
-void UserApi::get_login_history(int limit, int offset, Callback cb) {
- request("GET", QString("/user/login-history?limit=%1&offset=%2").arg(limit).arg(offset), {}, cb);
+void UserApi::get_login_history(int limit, int offset, Callback cb, const QObject* context) {
+ request("GET", QString("/user/login-history?limit=%1&offset=%2").arg(limit).arg(offset), {}, cb, context);
}
// ── MFA ──────────────────────────────────────────────────────────────────────
-void UserApi::enable_mfa(Callback cb) {
- request("POST", "/user/mfa/enable", {}, cb);
+void UserApi::enable_mfa(Callback cb, const QObject* context) {
+ request("POST", "/user/mfa/enable", {}, cb, context);
}
-void UserApi::disable_mfa(Callback cb) {
- request("POST", "/user/mfa/disable", {}, cb);
+void UserApi::disable_mfa(Callback cb, const QObject* context) {
+ request("POST", "/user/mfa/disable", {}, cb, context);
}
// ── Subscriptions ────────────────────────────────────────────────────────────
-void UserApi::get_user_subscription(Callback cb) {
- request("GET", "/user/subscriptions", {}, cb);
+void UserApi::get_user_subscription(Callback cb, const QObject* context) {
+ request("GET", "/user/subscriptions", {}, cb, context);
}
// ── Payment ──────────────────────────────────────────────────────────────────
-void UserApi::get_payment_history(int page, int limit, Callback cb) {
- request("GET", QString("/user/transactions?page=%1&limit=%2").arg(page).arg(limit), {}, cb);
+void UserApi::get_payment_history(int page, int limit, Callback cb, const QObject* context) {
+ request("GET", QString("/user/transactions?page=%1&limit=%2").arg(page).arg(limit), {}, cb, context);
}
// ── Support ──────────────────────────────────────────────────────────────────
-void UserApi::get_tickets(Callback cb) {
- request("GET", "/support/tickets", {}, cb);
+void UserApi::get_tickets(Callback cb, const QObject* context) {
+ request("GET", "/support/tickets", {}, cb, context);
}
-void UserApi::get_ticket_details(int ticket_id, Callback cb) {
- request("GET", QString("/support/tickets/%1").arg(ticket_id), {}, cb);
+void UserApi::get_ticket_details(int ticket_id, Callback cb, const QObject* context) {
+ request("GET", QString("/support/tickets/%1").arg(ticket_id), {}, cb, context);
}
void UserApi::create_ticket(const QString& subject, const QString& description, const QString& category,
- const QString& priority, Callback cb) {
+ const QString& priority, Callback cb, const QObject* context) {
QJsonObject body;
body["subject"] = subject;
body["description"] = description;
body["category"] = category;
body["priority"] = priority;
- request("POST", "/support/tickets", body, cb);
+ request("POST", "/support/tickets", body, cb, context);
}
-void UserApi::add_ticket_message(int ticket_id, const QString& message, Callback cb) {
+void UserApi::add_ticket_message(int ticket_id, const QString& message, Callback cb, const QObject* context) {
QJsonObject body;
body["message"] = message;
- request("POST", QString("/support/tickets/%1/messages").arg(ticket_id), body, cb);
+ request("POST", QString("/support/tickets/%1/messages").arg(ticket_id), body, cb, context);
}
-void UserApi::update_ticket_status(int ticket_id, const QString& status, Callback cb) {
+void UserApi::update_ticket_status(int ticket_id, const QString& status, Callback cb, const QObject* context) {
QJsonObject body;
body["status"] = status;
- request("PUT", QString("/support/tickets/%1").arg(ticket_id), body, cb);
+ request("PUT", QString("/support/tickets/%1").arg(ticket_id), body, cb, context);
}
-void UserApi::get_support_categories(Callback cb) {
- request("GET", "/support/categories", {}, cb);
+void UserApi::get_support_categories(Callback cb, const QObject* context) {
+ request("GET", "/support/categories", {}, cb, context);
}
} // namespace fincept::auth
diff --git a/fincept-qt/src/auth/UserApi.h b/fincept-qt/src/auth/UserApi.h
index d30dcc46e..68a951e8c 100644
--- a/fincept-qt/src/auth/UserApi.h
+++ b/fincept-qt/src/auth/UserApi.h
@@ -16,40 +16,49 @@ class UserApi : public QObject {
static UserApi& instance();
+ /// Every method takes an optional `context` that is forwarded to HttpClient,
+ /// which auto-disconnects the reply handler when that object is destroyed.
+ /// Pass `this` from any screen or widget — omitting it scopes the callback
+ /// to the UserApi singleton, i.e. to the whole app lifetime, so a callback
+ /// fires into a destroyed screen. nullptr is correct only for callers that
+ /// live as long as the app (AuthManager, SessionGuard).
+
// Profile
- void get_user_profile(Callback cb);
- void update_user_profile(const QJsonObject& data, Callback cb);
- void regenerate_api_key(Callback cb);
- void get_user_usage(int days, Callback cb);
- void get_user_credits(Callback cb);
- void delete_user_account(const QString& confirm_email, const QString& password, Callback cb);
+ void get_user_profile(Callback cb, const QObject* context = nullptr);
+ void update_user_profile(const QJsonObject& data, Callback cb, const QObject* context = nullptr);
+ void regenerate_api_key(Callback cb, const QObject* context = nullptr);
+ void get_user_usage(int days, Callback cb, const QObject* context = nullptr);
+ void get_user_credits(Callback cb, const QObject* context = nullptr);
+ void delete_user_account(const QString& confirm_email, const QString& password, Callback cb,
+ const QObject* context = nullptr);
// Login history
- void get_login_history(int limit, int offset, Callback cb);
+ void get_login_history(int limit, int offset, Callback cb, const QObject* context = nullptr);
// MFA
- void enable_mfa(Callback cb);
- void disable_mfa(Callback cb);
+ void enable_mfa(Callback cb, const QObject* context = nullptr);
+ void disable_mfa(Callback cb, const QObject* context = nullptr);
// Subscriptions
- void get_user_subscription(Callback cb);
+ void get_user_subscription(Callback cb, const QObject* context = nullptr);
// Payment
- void get_payment_history(int page, int limit, Callback cb);
+ void get_payment_history(int page, int limit, Callback cb, const QObject* context = nullptr);
// Support
- void get_tickets(Callback cb);
- void get_ticket_details(int ticket_id, Callback cb);
+ void get_tickets(Callback cb, const QObject* context = nullptr);
+ void get_ticket_details(int ticket_id, Callback cb, const QObject* context = nullptr);
void create_ticket(const QString& subject, const QString& description, const QString& category,
- const QString& priority, Callback cb);
- void add_ticket_message(int ticket_id, const QString& message, Callback cb);
- void update_ticket_status(int ticket_id, const QString& status, Callback cb);
- void get_support_categories(Callback cb);
+ const QString& priority, Callback cb, const QObject* context = nullptr);
+ void add_ticket_message(int ticket_id, const QString& message, Callback cb, const QObject* context = nullptr);
+ void update_ticket_status(int ticket_id, const QString& status, Callback cb, const QObject* context = nullptr);
+ void get_support_categories(Callback cb, const QObject* context = nullptr);
private:
UserApi() = default;
- void request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb);
+ void request(const QString& method, const QString& endpoint, const QJsonObject& body, Callback cb,
+ const QObject* context = nullptr);
};
} // namespace fincept::auth
diff --git a/fincept-qt/src/core/events/EventBus.cpp b/fincept-qt/src/core/events/EventBus.cpp
index 7a49fb92b..c120933b7 100644
--- a/fincept-qt/src/core/events/EventBus.cpp
+++ b/fincept-qt/src/core/events/EventBus.cpp
@@ -1,5 +1,7 @@
#include "core/events/EventBus.h"
+#include "core/logging/Logger.h"
+
#include <QMutexLocker>
namespace fincept {
@@ -9,10 +11,26 @@ EventBus& EventBus::instance() {
return s;
}
-EventBus::HandlerId EventBus::subscribe(const QString& event, Handler handler) {
- QMutexLocker lock(&mutex_);
- HandlerId id = next_id_++;
- subscriptions_.append({id, event, std::move(handler)});
+EventBus::HandlerId EventBus::subscribe(QObject* owner, const QString& event, Handler handler) {
+ if (!owner) {
+ LOG_ERROR("EventBus", QString("subscribe('%1') called with a null owner — ignored").arg(event));
+ return 0;
+ }
+
+ HandlerId id = 0;
+ {
+ QMutexLocker lock(&mutex_);
+ id = next_id_++;
+ subscriptions_.append({id, event, std::move(handler), owner});
+ }
+
+ // Connected outside the lock: destroyed() can fire on the owner's thread
+ // while we hold mutex_, and unsubscribe() would then deadlock on it.
+ // Qt::DirectConnection is deliberate — by the time a queued slot ran, the
+ // owner would already be gone and a publish() in between would call the
+ // dangling handler, which is the bug this whole overload exists to prevent.
+ QObject::connect(owner, &QObject::destroyed, this, [this, id]() { unsubscribe(id); },
+ Qt::DirectConnection);
return id;
}
@@ -21,6 +39,13 @@ void EventBus::unsubscribe(HandlerId id) {
subscriptions_.removeIf([id](const Subscription& s) { return s.id == id; });
}
+void EventBus::unsubscribe_owner(QObject* owner) {
+ if (!owner)
+ return;
+ QMutexLocker lock(&mutex_);
+ subscriptions_.removeIf([owner](const Subscription& s) { return s.owner == owner; });
+}
+
void EventBus::publish(const QString& event, const QVariantMap& data) {
emit eventPublished(event, data);
diff --git a/fincept-qt/src/core/events/EventBus.h b/fincept-qt/src/core/events/EventBus.h
index 84e1a92a6..ff3a3f5e2 100644
--- a/fincept-qt/src/core/events/EventBus.h
+++ b/fincept-qt/src/core/events/EventBus.h
@@ -19,8 +19,23 @@ class EventBus : public QObject {
using Handler = std::function<void(const QVariantMap&)>;
using HandlerId = int;
- HandlerId subscribe(const QString& event, Handler handler);
+ /// Subscribe for as long as `owner` lives.
+ ///
+ /// `owner` is mandatory: handlers capture their owner, and the bus is a
+ /// process-lifetime singleton, so a handler outliving its owner is a
+ /// use-after-free the next time anyone publishes that event. The
+ /// destroyed() connection makes that impossible by construction — there is
+ /// deliberately no ownerless overload, because every previous caller
+ /// discarded the returned id and never unsubscribed.
+ HandlerId subscribe(QObject* owner, const QString& event, Handler handler);
+
+ /// Explicit early unsubscribe. Rarely needed — owner destruction is
+ /// already handled — but useful to stop listening while staying alive.
void unsubscribe(HandlerId id);
+
+ /// Drop every subscription owned by `owner`. Safe to call more than once.
+ void unsubscribe_owner(QObject* owner);
+
void publish(const QString& event, const QVariantMap& data = {});
signals:
@@ -33,6 +48,7 @@ class EventBus : public QObject {
HandlerId id;
QString event;
Handler handler;
+ QObject* owner = nullptr; // not owned; only compared, never dereferenced
};
QList<Subscription> subscriptions_;
diff --git a/fincept-qt/src/core/events/TypedEvents.h b/fincept-qt/src/core/events/TypedEvents.h
deleted file mode 100644
index f24f883a7..000000000
--- a/fincept-qt/src/core/events/TypedEvents.h
+++ /dev/null
@@ -1,70 +0,0 @@
-#pragma once
-// Phase 10 scaffolding — typed event manifest over the stringly-typed EventBus.
-//
-// The string-keyed EventBus has 39 callsites today. Misspellings, dead
-// publishes, and missing subscribers are silent bugs. `TypedEvents` adds a
-// compile-time layer that keeps the runtime bus intact:
-//
-// - One canonical name per event, defined here in `event_name()`.
-// - One typed payload struct per event.
-// - `publish<E>(payload)` and `on<E>(owner, slot)` enforce the right shape.
-//
-// The runtime bus is unchanged, so existing string-keyed `publish/subscribe`
-// callsites continue working. Migration is opportunistic — touched code
-// upgrades to the typed API.
-
-#include "core/events/EventBus.h"
-
-#include <QObject>
-#include <QString>
-#include <QVariantMap>
-
-#include <functional>
-#include <utility>
-
-namespace fincept::events {
-
-// ── Event payloads ───────────────────────────────────────────────────────────
-
-struct NavSwitchScreen {
- QString screen_id;
- QVariantMap to_map() const { return {{"screen_id", screen_id}}; }
- static NavSwitchScreen from_map(const QVariantMap& m) { return {m.value(QStringLiteral("screen_id")).toString()}; }
- static constexpr const char* name() { return "nav.switch_screen"; }
-};
-
-struct EquityResearchLoadSymbol {
- QString symbol;
- QString exchange;
- QVariantMap to_map() const { return {{"symbol", symbol}, {"exchange", exchange}}; }
- static EquityResearchLoadSymbol from_map(const QVariantMap& m) {
- return {m.value(QStringLiteral("symbol")).toString(), m.value(QStringLiteral("exchange")).toString()};
- }
- static constexpr const char* name() { return "equity_research.load_symbol"; }
-};
-
-// ── Typed API ────────────────────────────────────────────────────────────────
-
-/// Publish a typed event. Delegates to the existing string bus.
-template <typename E>
-inline void publish(const E& e) {
- EventBus::instance().publish(QString::fromUtf8(E::name()), e.to_map());
-}
-
-/// Subscribe to a typed event. The owner controls lifetime — when the owner is
-/// destroyed, the subscription auto-cancels via `QObject::destroyed`.
-///
-/// Returns the underlying `HandlerId` for explicit unsubscribe; callers usually
-/// rely on owner-destruction.
-template <typename E, typename Slot>
-inline EventBus::HandlerId on(QObject* owner, Slot slot) {
- auto& bus = EventBus::instance();
- auto handler = [slot = std::forward<Slot>(slot)](const QVariantMap& m) { slot(E::from_map(m)); };
- EventBus::HandlerId id = bus.subscribe(QString::fromUtf8(E::name()), std::move(handler));
- if (owner) {
- QObject::connect(owner, &QObject::destroyed, &bus, [id] { EventBus::instance().unsubscribe(id); });
- }
- return id;
-}
-
-} // namespace fincept::events
diff --git a/fincept-qt/src/core/i18n/LanguageManager.cpp b/fincept-qt/src/core/i18n/LanguageManager.cpp
index 941bf9a63..87769b294 100644
--- a/fincept-qt/src/core/i18n/LanguageManager.cpp
+++ b/fincept-qt/src/core/i18n/LanguageManager.cpp
@@ -12,6 +12,13 @@ namespace fincept::i18n {
namespace {
constexpr const char* kSettingsKey = "general.language";
constexpr const char* kDefaultCode = "en";
+
+/// Set only for the duration of the startup set_language() call that follows a
+/// *failed* read of the persisted preference. The detected/default language is
+/// then applied for this session but never written back, so a transient DB
+/// error cannot overwrite the user's real saved language. Explicit switches
+/// (LanguageSwitcher, GeneralSection) always run with this false and persist.
+bool g_suppress_language_persist = false;
} // namespace
LanguageManager& LanguageManager::instance() {
@@ -61,20 +68,30 @@ void LanguageManager::initialize() {
// Read the persisted preference. If it's set (even to "en"), respect it
// — the user has made an explicit choice we should not override.
const auto r = SettingsRepository::instance().get(QString::fromLatin1(kSettingsKey), QString());
- QString code = r.is_ok() ? r.value() : QString();
+ // A read error is not "no preference" — the stored language is unknown, so
+ // whatever we fall back to must stay session-local.
+ const bool read_failed = r.is_err();
+ if (read_failed) {
+ LOG_ERROR("i18n", QString("settings read failed for '%1' — applying the detected language for this session "
+ "only, leaving the stored value untouched: %2")
+ .arg(QString::fromLatin1(kSettingsKey), QString::fromStdString(r.error())));
+ }
+ QString code = read_failed ? QString() : r.value();
if (code.isEmpty()) {
// No saved preference — try the OS locale. The Settings save in
// set_language() will record whatever we picked, so subsequent runs
// skip this detection and honour the explicit value.
code = detect_system_language();
- if (!code.isEmpty())
+ if (!code.isEmpty() && !read_failed)
LOG_INFO("i18n", QStringLiteral("First launch — detected system language: %1").arg(code));
}
if (code.isEmpty())
code = QString::fromLatin1(kDefaultCode);
+ g_suppress_language_persist = read_failed;
set_language(code);
+ g_suppress_language_persist = false;
}
QString LanguageManager::detect_system_language() {
@@ -153,7 +170,11 @@ void LanguageManager::set_language(const QString& code) {
// Persist the choice. The repository call is cheap; we accept the small
// overhead on startup so the value is always in sync with what's running.
- SettingsRepository::instance().set(QString::fromLatin1(kSettingsKey), code, QStringLiteral("general"));
+ // Suppressed only when initialize() is falling back after a failed read —
+ // set() is an INSERT OR REPLACE, so writing a guess there would destroy the
+ // language the user actually chose.
+ if (!g_suppress_language_persist)
+ SettingsRepository::instance().set(QString::fromLatin1(kSettingsKey), code, QStringLiteral("general"));
emit language_changed(code);
}
diff --git a/fincept-qt/src/core/logging/LogTags.h b/fincept-qt/src/core/logging/LogTags.h
deleted file mode 100644
index 67c176034..000000000
--- a/fincept-qt/src/core/logging/LogTags.h
+++ /dev/null
@@ -1,40 +0,0 @@
-#pragma once
-
-// Canonical tag names used by the logging system.
-//
-// Usage:
-// LOG_INFO(fincept::log::kApp, "starting up");
-//
-// This header is purely additive — existing call sites that pass
-// string literals (e.g. LOG_INFO("App", "...")) continue to work
-// unchanged. Prefer these constants for new code so tag names
-// stay consistent across the codebase (no drift between "Auth"
-// vs "auth" vs "AUTH").
-
-namespace fincept::log {
-
-inline constexpr const char* kApp = "App";
-inline constexpr const char* kAuth = "Auth";
-inline constexpr const char* kDb = "DB";
-inline constexpr const char* kCacheDb = "CacheDB";
-inline constexpr const char* kHttp = "HTTP";
-inline constexpr const char* kWebSocket = "WebSocket";
-inline constexpr const char* kPython = "Python";
-inline constexpr const char* kTheme = "ThemeManager";
-inline constexpr const char* kMainWindow =
- "WindowFrame"; // legacy name kept as kMainWindow for one release; new code can use kWindowFrame
-inline constexpr const char* kWindowFrame = "WindowFrame";
-inline constexpr const char* kRouter = "ScreenRouter";
-inline constexpr const char* kMarketData = "MarketData";
-inline constexpr const char* kNews = "News";
-inline constexpr const char* kExchange = "Exchange";
-inline constexpr const char* kBroker = "Broker";
-inline constexpr const char* kMcp = "MCP";
-inline constexpr const char* kAiChat = "AiChat";
-inline constexpr const char* kUpdater = "UpdateService";
-inline constexpr const char* kWorkspace = "Workspace";
-inline constexpr const char* kWorkflow = "Workflow";
-inline constexpr const char* kDataHub = "DataHub";
-inline constexpr const char* kProfile = "ProfileManager";
-
-} // namespace fincept::log
diff --git a/fincept-qt/src/datahub/DataHub.cpp b/fincept-qt/src/datahub/DataHub.cpp
index 6f5aac9ee..4ec6eb0e2 100644
--- a/fincept-qt/src/datahub/DataHub.cpp
+++ b/fincept-qt/src/datahub/DataHub.cpp
@@ -1010,6 +1010,14 @@ void DataHub::scheduler_body() {
++it;
}
+ // Release cached payloads for topics nobody is watching any more.
+ // Runs on its own cadence — see kIdleSweepEveryTicks. Placed here so
+ // it can never race the in_flight marking done in phase 2 below.
+ if (++sweep_tick_counter_ >= kIdleSweepEveryTicks) {
+ sweep_tick_counter_ = 0;
+ sweep_idle_topics(t);
+ }
+
// Phase 1 — collect eligible topics by producer (no rate-limit
// gate yet). The per-producer rate limit applies to refresh()
// *calls*, not to topic enrolment; one refresh() carries the
@@ -1080,6 +1088,112 @@ void DataHub::scheduler_body() {
}
}
+bool DataHub::has_live_subscribers(const QString& topic) const {
+ // Caller holds mutex_. A destroyed owner leaves a null QPointer behind
+ // until on_owner_destroyed() runs, so presence in the vector is not
+ // enough — the owner has to still be alive.
+ if (auto it = subscriptions_.constFind(topic); it != subscriptions_.constEnd()) {
+ for (const auto& sub : it.value())
+ if (sub.owner)
+ return true;
+ }
+ // Wildcard subscribers (e.g. "option:chain:*", "ws:kraken:*") never appear
+ // under the concrete key, so they must be matched explicitly. Missing this
+ // would evict state out from under a live pattern consumer.
+ for (auto it = pattern_subscriptions_.constBegin(); it != pattern_subscriptions_.constEnd(); ++it) {
+ if (!pattern_matches(it.key(), topic))
+ continue;
+ for (const auto& sub : it.value())
+ if (sub.owner)
+ return true;
+ }
+ // Error-only consumers keep the topic alive too — they're cheap to check
+ // and a topic being watched for failures is not an idle topic.
+ if (auto it = error_subscriptions_.constFind(topic); it != error_subscriptions_.constEnd()) {
+ for (const auto& sub : it.value())
+ if (sub.owner)
+ return true;
+ }
+ for (auto it = error_pattern_subscriptions_.constBegin(); it != error_pattern_subscriptions_.constEnd(); ++it) {
+ if (!pattern_matches(it.key(), topic))
+ continue;
+ for (const auto& sub : it.value())
+ if (sub.owner)
+ return true;
+ }
+ return false;
+}
+
+void DataHub::sweep_idle_topics(qint64 now) {
+ // Caller holds mutex_. Conservative by construction — every one of these
+ // gates must pass before a TopicState is dropped.
+ int evicted = 0;
+ for (auto it = topics_.begin(); it != topics_.end();) {
+ const auto& st = it.value();
+
+ // A producer has an outstanding refresh() for this topic; its
+ // publish() would resurrect the state anyway and the in_flight /
+ // last_refresh_request_ms bookkeeping still matters for the timeout
+ // pre-pass.
+ if (st.in_flight) {
+ ++it;
+ continue;
+ }
+ // A deferred fan-out is armed — do_coalesced_flush() still needs
+ // coalesce_latest.
+ if (st.coalesce_pending) {
+ ++it;
+ continue;
+ }
+ // Never evict a topic somebody is still watching.
+ if (has_live_subscribers(it.key())) {
+ ++it;
+ continue;
+ }
+
+ // Age is measured from the last time the topic was touched at all, so
+ // a state created by a peek() or a subscribe that never received data
+ // ages out too. A state that has never been touched (both zero) is
+ // left alone rather than guessed at.
+ const qint64 last_touch = std::max(st.last_publish_ms, st.last_refresh_request_ms);
+ if (last_touch <= 0) {
+ ++it;
+ continue;
+ }
+
+ // push_only families ignore ttl_ms for scheduling, but the value is
+ // still a sane "how often does this normally move" figure, which is
+ // exactly what we want to scale the idle window by.
+ const qint64 window = std::max(static_cast<qint64>(effective_ttl_ms(st)) * kIdleEvictTtlMultiple,
+ kIdleEvictMinAgeMs);
+ if ((now - last_touch) < window) {
+ ++it;
+ continue;
+ }
+
+ // set_policy() stores the explicit per-topic policy *inside* the
+ // TopicState, so a full erase would silently downgrade the topic to
+ // its pattern policy — or to the 30s/5s defaults — the next time it
+ // was touched. Those states release their payload instead and keep
+ // their configuration and counters. The QVariant is the memory; the
+ // rest of the struct is a few dozen bytes.
+ if (it->policy_explicit) {
+ if (it->value.isValid()) {
+ it->value = QVariant();
+ it->coalesce_latest = QVariant();
+ ++evicted;
+ }
+ ++it;
+ continue;
+ }
+
+ it = topics_.erase(it);
+ ++evicted;
+ }
+ if (evicted > 0)
+ LOG_DEBUG("DataHub", QString("Evicted %1 idle topic state(s); %2 retained").arg(evicted).arg(topics_.size()));
+}
+
void DataHub::tick_scheduler() {
scheduler_body();
}
diff --git a/fincept-qt/src/datahub/DataHub.h b/fincept-qt/src/datahub/DataHub.h
index 624350184..8a2bf95fd 100644
--- a/fincept-qt/src/datahub/DataHub.h
+++ b/fincept-qt/src/datahub/DataHub.h
@@ -269,6 +269,43 @@ class DataHub : public QObject {
void do_coalesced_flush(const QString& topic);
void scheduler_body();
+ // ── Idle-topic eviction ─────────────────────────────────────────────────
+ //
+ // `topics_` was a process-lifetime cache: `state_for()` inserts a
+ // TopicState retaining the full last-published QVariant on every
+ // publish/subscribe/peek, and the only automatic erase sites are gated on
+ // `policy.drop_on_idle` — which defaults false and is set true by exactly
+ // two producers. `ttl_ms` is a freshness *test*; it never releases the
+ // payload. So memory scaled with the total breadth browsed since launch,
+ // monotonically, and the heavy families are the wide ones:
+ // `market:history:<sym>:<period>:<interval>` holds full OHLC vectors,
+ // `news:symbol:<sym>` article bodies, `dbnomics:series:*` whole
+ // observation series.
+ //
+ // The sweep below is the conservative counterpart, modelled on
+ // `mcp::ResultStore::sweep_locked()`: it only ever touches topics with
+ // **zero live subscribers**, no in-flight refresh, and no armed coalesce
+ // flush, and only once they are far past their freshness window. A
+ // re-show inside the window is still a cache hit.
+
+ /// True if any concrete or wildcard subscription with a live owner
+ /// currently covers `topic`. Caller holds mutex_.
+ bool has_live_subscribers(const QString& topic) const;
+ /// Erase idle, long-stale, unsubscribed TopicStates. Caller holds mutex_.
+ void sweep_idle_topics(qint64 now);
+
+ /// A topic is only evictable once it is this many freshness windows
+ /// stale. Generous on purpose — the point is to release payloads nobody
+ /// came back for, not to fight the cache.
+ static constexpr int kIdleEvictTtlMultiple = 10;
+ /// Floor on the above, so short-TTL families (1 s quote topics) aren't
+ /// evicted seconds after the user tabs away.
+ static constexpr qint64 kIdleEvictMinAgeMs = 5 * 60 * 1000;
+ /// Sweep cadence in scheduler ticks (1 s each) — the walk is O(topics_)
+ /// so it doesn't belong on the per-second path.
+ static constexpr int kIdleSweepEveryTicks = 60;
+ int sweep_tick_counter_ = 0;
+
// ── State ───────────────────────────────────────────────────────────────
mutable QMutex mutex_;
diff --git a/fincept-qt/src/mcp/McpClient.cpp b/fincept-qt/src/mcp/McpClient.cpp
index d44d47c0d..b85be487b 100644
--- a/fincept-qt/src/mcp/McpClient.cpp
+++ b/fincept-qt/src/mcp/McpClient.cpp
@@ -5,11 +5,13 @@
#include "core/logging/Logger.h"
#include "python/PythonSetupManager.h"
+#include <QCoreApplication>
#include <QElapsedTimer>
#include <QFileInfo>
#include <QJsonDocument>
#include <QMetaObject>
#include <QProcessEnvironment>
+#include <QThread>
namespace fincept::mcp {
@@ -26,6 +28,18 @@ McpClient::~McpClient() {
// ============================================================================
Result<void> McpClient::start() {
+ // Invariant (also documented on McpClient.h:start and at the
+ // BlockingQueuedConnection below): never the UI thread. This blocks for up
+ // to 60 s in waitForStarted, and initialize() straight after adds another
+ // 120 s of blocking JSON-RPC. Q_ASSERT compiles out in release builds, so
+ // log it too — a violation is a UI freeze, not a crash, and freezes get
+ // misattributed for weeks.
+ Q_ASSERT(QThread::currentThread() != qApp->thread());
+ if (qApp && QThread::currentThread() == qApp->thread()) {
+ LOG_ERROR(TAG, "McpClient::start() called on the UI thread — this blocks for up to 180 s. "
+ "Wrap the caller in QtConcurrent::run.");
+ }
+
if (running_)
return Result<void>::ok();
@@ -123,9 +137,14 @@ void McpClient::cleanup_process() {
}
void McpClient::stop() {
- if (!running_)
- return;
- running_ = false;
+ // Teardown is UNCONDITIONAL. The old `if (!running_) return;` guard looked
+ // like an idempotency check but was a resource leak: on_finished() sets
+ // running_ = false the moment the child process dies, so a stop() after a
+ // crash returned immediately and orphaned a parentless QThread still
+ // spinning an event loop plus its QProcess. McpManager restarts dead
+ // servers and resets the attempt budget on every success, so that leaked
+ // pair accumulated without bound. Only the terminate() is conditional now.
+ const bool was_running = running_.exchange(false);
// Wake any pending requests with an error
{
@@ -137,28 +156,53 @@ void McpClient::stop() {
rpc_cond_.wakeAll();
}
- if (process_) {
- // Ask the worker thread to terminate the process, then quit its event loop.
- // We use QueuedConnection so the worker thread handles terminate() in its
- // own event loop — no BlockingQueuedConnection deadlock risk.
- // After quit(), wait() drains the thread and the process dies with it.
- QMetaObject::invokeMethod(process_, [this]() { process_->terminate(); }, Qt::QueuedConnection);
+ // Kill and delete the QProcess ON ITS OWN THREAD. The old code called
+ // process_->kill() from the caller's thread (a cross-thread QProcess
+ // access) and then `delete worker_thread_` BEFORE cleanup_process()
+ // deleted process_ — destroying a QObject whose thread affinity pointed at
+ // an already-freed QThread. Modelled on trading/ExchangeSession::stop_ws.
+ const bool worker_alive =
+ worker_thread_ && worker_thread_->isRunning() && QThread::currentThread() != worker_thread_;
+ if (process_ && worker_alive) {
+ QMetaObject::invokeMethod(
+ process_,
+ [this, was_running]() {
+ if (!process_)
+ return;
+ if (process_->state() != QProcess::NotRunning) {
+ if (was_running)
+ process_->terminate();
+ if (!process_->waitForFinished(2000)) {
+ process_->kill();
+ process_->waitForFinished(1000);
+ }
+ }
+ delete process_;
+ process_ = nullptr;
+ },
+ Qt::BlockingQueuedConnection);
}
if (worker_thread_) {
worker_thread_->quit();
- // Wait up to 4s for the worker to drain terminate() and exit cleanly.
- // If it hangs, kill the process directly before giving up.
- if (!worker_thread_->wait(4000) && process_) {
- process_->kill();
- worker_thread_->wait(1000);
+ if (worker_thread_->wait(3000)) {
+ delete worker_thread_;
+ } else {
+ // Deleting a still-running QThread is a crash, not a leak. The
+ // process is already gone by here, so a stuck event loop is a bug
+ // worth logging and leaking rather than aborting on during teardown.
+ LOG_ERROR(TAG, "Worker thread for " + config_.name + " did not exit — leaking it instead of crashing");
}
- delete worker_thread_;
worker_thread_ = nullptr;
}
+ // No-op when the lambda above already deleted it; covers the paths where
+ // the worker thread was never started or had already exited (in which case
+ // there is no other thread with an affinity claim on process_).
cleanup_process();
- LOG_INFO(TAG, "Stopped MCP server: " + config_.name);
+
+ if (was_running)
+ LOG_INFO(TAG, "Stopped MCP server: " + config_.name);
}
bool McpClient::is_running() const {
diff --git a/fincept-qt/src/mcp/McpClient.h b/fincept-qt/src/mcp/McpClient.h
index 322826323..10e45180d 100644
--- a/fincept-qt/src/mcp/McpClient.h
+++ b/fincept-qt/src/mcp/McpClient.h
@@ -41,8 +41,15 @@ class McpClient : public QObject {
~McpClient() override;
// Lifecycle
- // NOTE: start() must only be called from a background thread, never the UI thread.
+ // NOTE: start() must only be called from a background thread, never the UI
+ // thread — it blocks for up to 60 s in waitForStarted and the caller
+ // normally follows with initialize()'s 120 s JSON-RPC wait. Enforced by a
+ // Q_ASSERT + LOG_ERROR at the top of start().
Result<void> start();
+
+ /// Idempotent and unconditional: safe to call after the child process has
+ /// already died (which is exactly when the old `if (!running_) return;`
+ /// guard leaked the worker thread + QProcess).
void stop();
bool is_running() const;
diff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cpp
index fbac077b1..b043d741c 100644
--- a/fincept-qt/src/mcp/McpInit.cpp
+++ b/fincept-qt/src/mcp/McpInit.cpp
@@ -5,6 +5,7 @@
#include "core/logging/Logger.h"
#include "mcp/McpProvider.h"
#include "mcp/McpService.h"
+#include "mcp/TerminalMcpBridge.h"
#include "mcp/tools/AgenticMemoryTools.h"
#include "mcp/tools/AgentsTools.h"
#include "mcp/tools/AiChatTools.h"
@@ -42,8 +43,12 @@
#include "mcp/tools/WatchlistTools.h"
#include "mcp/tools/WorkspaceTools.h"
+#include <QCoreApplication>
#include <QJsonDocument>
+#include <algorithm>
+#include <atomic>
+
namespace fincept::mcp {
static constexpr const char* TAG = "McpInit";
@@ -55,9 +60,20 @@ static constexpr const char* TAG = "McpInit";
// multiplies across every LLM turn that includes the tool.
//
// Logs at INFO if all schemas are within budget; logs WARN with offenders
-// (sorted largest-first) otherwise. Runs once at startup; cheap.
+// (sorted largest-first) otherwise.
+//
+// NOT cheap, despite the old comment: it re-serialises every registered tool
+// schema with QJsonDocument::toJson purely to produce a log line, on the
+// pre-window boot path — hundreds of KB of JSON the app then throws away.
+// Opt-in only: pass --audit-tools, or turn the McpInit tag up to Debug.
static constexpr int kSchemaSizeWarnBytes = 2048;
+static bool schema_audit_requested() {
+ if (Logger::instance().is_enabled(LogLevel::Debug, QString::fromLatin1(TAG)))
+ return true;
+ return qApp && qApp->arguments().contains(QStringLiteral("--audit-tools"));
+}
+
static void audit_tool_schema_sizes() {
const auto tools = McpProvider::instance().list_all_tools();
struct Offender {
@@ -203,15 +219,35 @@ void initialize_all_tools() {
LOG_INFO(TAG, QString("Registered %1 internal MCP tools").arg(provider.tool_count()));
- // Audit schema sizes once after registration — surfaces bloated tools
- // before they bleed prompt tokens on every turn.
- audit_tool_schema_sizes();
+ // Audit schema sizes after registration — surfaces bloated tools before
+ // they bleed prompt tokens on every turn. Opt-in: it re-serialises every
+ // schema and this is the pre-window boot path.
+ if (schema_audit_requested())
+ audit_tool_schema_sizes();
// Initialize unified service (starts external servers in background)
McpService::instance().initialize();
}
void shutdown_mcp() {
+ // Idempotent: teardown may be reached from an aboutToQuit handler, a test
+ // harness, and a destructor in the same run. Running McpManager::shutdown()
+ // twice would stop already-deleted clients.
+ static std::atomic<bool> s_done{false};
+ bool expected = false;
+ if (!s_done.compare_exchange_strong(expected, true)) {
+ LOG_DEBUG(TAG, "shutdown_mcp() already ran — ignoring");
+ return;
+ }
+
+ // Close the local agent bridge first so no new tool call can arrive while
+ // the provider registry is being cleared out from under it.
+ TerminalMcpBridge::instance().stop();
+
+ // Stops the health-check timer, then every external server process.
+ // Without this the child processes (npx/uvx/python MCP servers) outlive the
+ // terminal — see the CROSS-FILE note about main.cpp's aboutToQuit handler,
+ // which is what makes this function reachable at all.
McpService::instance().shutdown();
LOG_INFO(TAG, "MCP system shut down");
}
diff --git a/fincept-qt/src/mcp/McpManager.cpp b/fincept-qt/src/mcp/McpManager.cpp
index d1179f64b..2bc0689e1 100644
--- a/fincept-qt/src/mcp/McpManager.cpp
+++ b/fincept-qt/src/mcp/McpManager.cpp
@@ -222,20 +222,28 @@ Result<void> McpManager::start_server(const QString& id) {
}
Result<void> McpManager::stop_server(const QString& id) {
- QMutexLocker lock(&mutex_);
-
- if (!clients_.contains(id))
- return Result<void>::ok();
-
- clients_[id]->stop();
- clients_.remove(id);
- tool_cache_.remove(id);
-
- if (configs_.contains(id))
- configs_[id].status = ServerStatus::Stopped;
+ // Take the shared_ptr under the lock, drop the map entry, then UNLOCK
+ // before stopping. McpClient::stop() blocks for up to ~5 s (terminate →
+ // wait → kill → thread join) and this is called straight from UI click
+ // handlers, so holding mutex_ across it stalled every concurrent
+ // call_external_tool / get_servers / health tick behind a UI button.
+ // The shared_ptr copy keeps the client alive after the map entry is gone.
+ std::shared_ptr<McpClient> client;
+ {
+ QMutexLocker lock(&mutex_);
+ auto it = clients_.find(id);
+ if (it == clients_.end())
+ return Result<void>::ok();
+ client = it.value();
+ clients_.erase(it);
+ tool_cache_.remove(id);
+ if (configs_.contains(id))
+ configs_[id].status = ServerStatus::Stopped;
+ }
- McpServerRepository::instance().set_status(id, "stopped");
- lock.unlock();
+ McpServerRepository::instance().set_status(id, "stopped"); // DB I/O — also off the lock
+ if (client)
+ client->stop();
emit servers_changed();
LOG_INFO(TAG, "MCP server stopped: " + id);
@@ -334,8 +342,14 @@ void McpManager::do_health_check() {
}
void McpManager::on_health_result(const QString& id, bool ok) {
- // Runs on the main thread: safe to restart (QProcess) and touch
- // restart_attempts_ (only mutated here).
+ // Runs on the main thread so restart_attempts_ (only mutated here) needs no
+ // lock. The RESTART itself must not: restart_server → start_server →
+ // McpClient::start() → waitForStarted(60000) behind a
+ // Qt::BlockingQueuedConnection, then initialize() → send_request(…, 120000)
+ // blocking on rpc_cond_. A dead server therefore froze the whole UI for up
+ // to 180 s, three times over (MAX_RESTART_ATTEMPTS) — the ping was already
+ // offloaded for exactly this reason, and marshalling the follow-up back
+ // here undid it.
if (ok) {
restart_attempts_.remove(id); // reset on success
return;
@@ -346,7 +360,12 @@ void McpManager::on_health_result(const QString& id, bool ok) {
restart_attempts_[id] = attempts + 1;
LOG_INFO(TAG,
QString("Restarting server %1 (attempt %2/%3)").arg(id).arg(attempts + 1).arg(MAX_RESTART_ATTEMPTS));
- restart_server(id);
+ QPointer<McpManager> self = this;
+ const QString sid = id;
+ (void)QtConcurrent::run([self, sid]() {
+ if (self)
+ self->restart_server(sid);
+ });
} else {
LOG_ERROR(TAG, "Server " + id + " exceeded max restart attempts — giving up");
McpServerRepository::instance().set_status(id, "error");
@@ -399,11 +418,17 @@ QStringList McpManager::get_logs(const QString& id) const {
}
void McpManager::refresh_tools_for(const QString& id) {
- QMutexLocker lock(&mutex_);
- McpClient* client = get_client(id);
- if (!client)
- return;
- lock.unlock();
+ // shared_ptr copy, same reasoning as call_external_tool: list_tools()
+ // blocks on JSON-RPC with the lock released, and stop_server() can erase
+ // the map entry meanwhile — a raw pointer would outlive its McpClient.
+ std::shared_ptr<McpClient> client;
+ {
+ QMutexLocker lock(&mutex_);
+ auto it = clients_.find(id);
+ if (it == clients_.end() || !it.value())
+ return;
+ client = it.value();
+ }
auto result = client->list_tools();
if (result.is_err()) {
diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cpp
index 5326a0b94..02b990dba 100644
--- a/fincept-qt/src/mcp/McpProvider.cpp
+++ b/fincept-qt/src/mcp/McpProvider.cpp
@@ -2,9 +2,11 @@
#include "mcp/McpProvider.h"
+#include "core/config/AppConfig.h"
#include "core/logging/Logger.h"
#include "mcp/JobRegistry.h"
#include "mcp/SchemaValidator.h"
+#include "mcp/TerminalMcpBridge.h"
#include <QCoreApplication>
#include <QFutureWatcher>
@@ -530,21 +532,73 @@ void McpProvider::set_auth_checker(AuthChecker checker) {
auth_checker_ = std::move(checker);
}
+namespace {
+// Session-level destructive grant. -1 = not yet read from settings, 0 = denied,
+// 1 = granted. Atomic because tool calls dispatch from pool threads.
+std::atomic<int> s_destructive_session_grant{-1};
+
+constexpr const char* kDestructiveSettingKey = "mcp/allow_destructive_tools";
+} // namespace
+
+void McpProvider::set_destructive_allowed(bool allowed) {
+ s_destructive_session_grant.store(allowed ? 1 : 0, std::memory_order_relaxed);
+ AppConfig::instance().set(QString::fromLatin1(kDestructiveSettingKey), allowed);
+ LOG_WARN(TAG, QString("Destructive MCP tools are now %1 for this session")
+ .arg(allowed ? "ENABLED (tools may mutate state and write files)" : "disabled"));
+}
+
+bool McpProvider::destructive_allowed() {
+ // 1. Per-call capability token — the agent bridge sets a thread_local flag
+ // for the duration of a call that presented the destructive token.
+ // Reusing that mechanism rather than adding a parallel one.
+ if (TerminalMcpBridge::is_destructive_allowed())
+ return true;
+
+ // 2. Session grant, seeded once from the persisted setting.
+ int v = s_destructive_session_grant.load(std::memory_order_relaxed);
+ if (v < 0) {
+ v = AppConfig::instance().get(QString::fromLatin1(kDestructiveSettingKey), QVariant(false)).toBool() ? 1 : 0;
+ s_destructive_session_grant.store(v, std::memory_order_relaxed);
+ }
+ return v == 1;
+}
+
std::optional<ToolResult> McpProvider::check_authorization(const QString& name, AuthLevel auth_required,
- bool is_destructive) const {
+ bool is_destructive, bool destructive_declared) const {
// We don't import AuthManager here to avoid pulling auth headers into
// McpTypes.h consumers — instead we expose a hook that the app installs
// at startup.
//
- // No-checker semantics:
- // • AuthLevel <= Authenticated and is_destructive flag → log + pass
- // (the flag is a hint for the Phase 6.12 modal; not a hard gate
- // until that UI lands)
- // • AuthLevel >= Verified → fail closed (genuine privilege escalation
- // that must not happen unauthenticated)
+ // Order of checks:
+ // 1. Nothing declared → pass immediately.
+ // 2. Declared destructive without capability → REFUSE (fail closed, all
+ // callers). This runs ahead of the checker because the checker can
+ // only distinguish agent calls, and the chat path is the one that was
+ // unguarded.
+ // 3. Installed checker → its verdict wins for everything else.
+ // 4. No checker + AuthLevel >= Verified → fail closed (genuine privilege
+ // escalation that must not happen unauthenticated).
if (auth_required == AuthLevel::None && !is_destructive)
return std::nullopt;
+ // ── Fail-closed destructive gate ─────────────────────────────────────
+ // Runs BEFORE the caller-installed checker and applies to every caller,
+ // because the checker could only ever see agent-originated calls (it keys
+ // off TerminalMcpBridge::is_call_in_progress()) and the interactive chat
+ // tool loop never sets that flag. See the header for the two ways to grant
+ // the capability. Note this is deliberately caller-agnostic: "which caller
+ // is this" is exactly the distinction that made the old gate a no-op.
+ if (destructive_declared && is_destructive && !destructive_allowed()) {
+ LOG_WARN(TAG, QString("Tool '%1' refused: destructive tools are disabled (auth_required=%2). "
+ "Grant the capability to allow it.")
+ .arg(name, auth_level_str(auth_required)));
+ return ToolResult::fail(
+ QString("Tool '%1' changes state or writes to disk and is disabled by default. To allow it, "
+ "the USER must enable destructive tools in Settings (`%2`). Do not retry this tool "
+ "until they confirm they have; tell them what you were trying to do and why.")
+ .arg(name, QString::fromLatin1(kDestructiveSettingKey)));
+ }
+
AuthChecker checker;
{
QMutexLocker lock(&mutex_);
@@ -564,13 +618,11 @@ std::optional<ToolResult> McpProvider::check_authorization(const QString& name,
.arg(name, auth_level_str(auth_required)));
return ToolResult::fail("Tool requires user confirmation but no authorisation hook is installed");
} else if (is_destructive) {
- // Advisory log only — the modal that prompts on this flag is
- // Phase 6.12 work. Tools tagged Authenticated+destructive still
- // run today; once the modal ships, install the checker and the
- // upper branch starts gating them.
- LOG_INFO(TAG,
- QString("Tool '%1' is destructive (flag is advisory; install McpProvider::set_auth_checker to gate)")
- .arg(name));
+ // Reaching here means the capability gate above already passed — the
+ // user granted it for the session, or the caller presented the agent
+ // destructive token. Record it: a destructive tool running is worth an
+ // audit line even when it was authorised.
+ LOG_WARN(TAG, QString("Destructive tool '%1' authorised and running").arg(name));
}
return std::nullopt;
}
diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.h
index 7edac7c16..b3f962215 100644
--- a/fincept-qt/src/mcp/McpProvider.h
+++ b/fincept-qt/src/mcp/McpProvider.h
@@ -130,6 +130,37 @@ class McpProvider {
using AuthChecker = std::function<bool(AuthLevel required, bool is_destructive)>;
void set_auth_checker(AuthChecker checker);
+ // ── Destructive-tool capability (fail-closed) ─────────────────────────
+ //
+ // `is_destructive` used to gate nothing on the chat path. The only consumer
+ // was the AuthChecker installed by AgentService, which denies a destructive
+ // tool ONLY when TerminalMcpBridge::is_call_in_progress() is true. The
+ // interactive LLM tool loop calls McpService::execute_openai_function with
+ // no ScopedCallFlags, so that flag was false and every destructive tool
+ // below AuthLevel::Verified executed with no prompt of any kind.
+ //
+ // The gate now fails closed: a tool that declares `is_destructive` is
+ // refused unless destructive capability has been granted for the current
+ // context. Two ways to grant it, and both are explicit:
+ // 1. Per call — the agent bridge's destructive capability token
+ // (TerminalMcpBridge::destructive_token(), echoed back as
+ // X-MCP-Allow-Destructive and surfaced via is_destructive_allowed()).
+ // Reused as-is; this is not a second mechanism.
+ // 2. Per session — set_destructive_allowed(true), persisted as
+ // `mcp/allow_destructive_tools`. Defaults to false.
+ //
+ // AuthLevel::ExplicitConfirm tools additionally trip the >= Verified
+ // fail-closed branch below and stay refused even with the grant, until the
+ // confirmation modal lands.
+
+ /// Grant/revoke destructive-tool capability for this session. Persists to
+ /// `mcp/allow_destructive_tools` so the choice survives a restart.
+ static void set_destructive_allowed(bool allowed);
+
+ /// True when destructive tools may run in the CURRENT context — i.e. the
+ /// per-call capability token is present, or the session grant is on.
+ static bool destructive_allowed();
+
/// Run the Phase 6.3 authorization gate for one call WITHOUT executing
/// anything. Returns std::nullopt when the call may proceed, or a
/// ready-to-return failure ToolResult when blocked. Shared by
@@ -137,8 +168,15 @@ class McpProvider {
/// (external tools, gated destructive-by-default) so both paths apply
/// identical auth/destructive-confirmation rules. `name` is used for
/// logging and error messages only.
- std::optional<ToolResult> check_authorization(const QString& name, AuthLevel auth_required,
- bool is_destructive) const;
+ ///
+ /// `destructive_declared` — true when `is_destructive` comes from the
+ /// tool's own ToolDef. Pass false when the caller is merely applying a
+ /// conservative default to a tool that carries no destructiveness metadata
+ /// (external MCP servers over the wire). Only DECLARED destructive tools
+ /// hit the fail-closed capability gate; undeclared ones stay on the
+ /// checker-only path so user-configured external servers keep working.
+ std::optional<ToolResult> check_authorization(const QString& name, AuthLevel auth_required, bool is_destructive,
+ bool destructive_declared = true) const;
// ── LLM Integration ────────────────────────────────────────────────────
diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cpp
index 894bb19e6..5556c7115 100644
--- a/fincept-qt/src/mcp/McpService.cpp
+++ b/fincept-qt/src/mcp/McpService.cpp
@@ -428,8 +428,16 @@ ToolResult McpService::execute_tool(const QString& server_id, const QString& too
// metadata, so external tools are gated destructive-by-default: the
// installed checker must approve them exactly like a destructive internal
// tool (agent-originated calls are denied unless the agent opts in).
+ // `destructive_declared=false`: the `true` above is OUR conservative
+ // assumption, not something the external tool declared. Marking it as
+ // undeclared keeps these on the checker-only path instead of the
+ // fail-closed capability gate, so a user who configured a Notion/Postgres
+ // server in the MCP Servers tab does not have to also flip the destructive
+ // switch. Agent-originated calls are still denied by the checker unless the
+ // agent opted in with the destructive token.
if (auto denied = McpProvider::instance().check_authorization(server_id + "__" + tool_name, AuthLevel::None,
- /*is_destructive=*/true))
+ /*is_destructive=*/true,
+ /*destructive_declared=*/false))
return *denied;
auto result = McpManager::instance().call_external_tool(server_id, tool_name, args);
@@ -468,8 +476,15 @@ ToolResult McpService::execute_openai_function(const QString& function_name, con
auto [server_id, tool_name] = McpProvider::parse_openai_function_name(function_name);
if (server_id.isEmpty() || tool_name.isEmpty()) {
- LOG_WARN(TAG, "Invalid function name format: " + function_name);
- return ToolResult::fail("Invalid function name format: " + function_name);
+ // parse_openai_function_name only fails to resolve when NO registered
+ // tool matches, so this is "no such tool", not a syntax problem. Saying
+ // "invalid format" sent models off re-spelling a name that simply does
+ // not exist — one turn retried a hallucinated create_workbook/add_tab
+ // API repeatedly instead of concluding the tools weren't there.
+ LOG_WARN(TAG, "No such tool: " + function_name);
+ return ToolResult::fail("No tool named '" + function_name +
+ "' exists. Do not retry this name. Call tool_list with a description of what you "
+ "want to do to find the tools that actually exist.");
}
LOG_INFO(TAG, QString("Dispatch: %1 -> server=%2 tool=%3").arg(function_name, server_id, tool_name));
@@ -490,8 +505,10 @@ QFuture<ToolResult> McpService::execute_openai_function_async(const QString& fun
};
if (server_id.isEmpty() || tool_name.isEmpty()) {
- LOG_WARN(TAG, "Invalid function name format: " + function_name);
- return fail_now("Invalid function name format: " + function_name);
+ LOG_WARN(TAG, "No such tool: " + function_name);
+ return fail_now("No tool named '" + function_name +
+ "' exists. Do not retry this name. Call tool_list with a description of what you want to "
+ "do to find the tools that actually exist.");
}
LOG_INFO(TAG, QString("Async dispatch: %1 -> server=%2 tool=%3").arg(function_name, server_id, tool_name));
diff --git a/fincept-qt/src/mcp/SchemaValidator.cpp b/fincept-qt/src/mcp/SchemaValidator.cpp
index f1a450023..7e8568d00 100644
--- a/fincept-qt/src/mcp/SchemaValidator.cpp
+++ b/fincept-qt/src/mcp/SchemaValidator.cpp
@@ -144,6 +144,35 @@ Result<void> validate_args(const ToolSchema& schema, QJsonObject& args) {
return Result<void>::err(("Missing required parameter: " + key).toStdString());
}
+ // ── Step 2.2: reject arguments the schema doesn't declare ────────────
+ // Unknown keys used to be dropped silently, which let a call written
+ // against an imagined API look like it worked: recalculate_excel_sheet
+ // received {"workbook_name": …, "tab_name": …}, had both ignored, fell back
+ // to sheet_index=-1 (the active sheet) and reported success — so a model
+ // that had invented a whole workbook API got a green light for it.
+ //
+ // Only enforced for tools with a structured schema; legacy `properties`-only
+ // tools keep the permissive behaviour. Underscore-prefixed keys are protocol
+ // metadata (_meta and friends), not tool arguments.
+ if (!schema.params.isEmpty()) {
+ QStringList unknown;
+ for (const QString& key : args.keys()) {
+ if (key.startsWith(QLatin1Char('_')))
+ continue;
+ if (schema.params.contains(key) || schema.properties.contains(key))
+ continue;
+ unknown.append(key);
+ }
+ if (!unknown.isEmpty()) {
+ QStringList accepted = schema.params.keys();
+ accepted.sort();
+ return Result<void>::err(("Unknown parameter(s): " + unknown.join(", ") +
+ ". This tool accepts only: " + accepted.join(", ") +
+ ". Call tool_describe for its schema before calling it again.")
+ .toStdString());
+ }
+ }
+
// ── Step 2.5: coerce stringified primitives, objects, arrays ─────────
// Two common LLM mistakes:
// - emit nested JSON as an escaped string ("config": "{\"a\":1}")
diff --git a/fincept-qt/src/mcp/TerminalMcpBridge.cpp b/fincept-qt/src/mcp/TerminalMcpBridge.cpp
index cd59d7799..05cb64b82 100644
--- a/fincept-qt/src/mcp/TerminalMcpBridge.cpp
+++ b/fincept-qt/src/mcp/TerminalMcpBridge.cpp
@@ -7,19 +7,27 @@
#include "mcp/TerminalMcpBridge.h"
+#include "auth/ConstantTime.h"
+#include "auth/LoopbackGuard.h"
#include "core/logging/Logger.h"
#include "mcp/McpManager.h"
#include "mcp/McpProvider.h"
#include "mcp/McpService.h"
+#include <QDateTime>
#include <QFutureWatcher>
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPointer>
+#include <QPromise>
+#include <QRegularExpression>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUuid>
+#include <QtConcurrent/QtConcurrent>
+
+#include <memory>
namespace fincept::mcp {
@@ -31,6 +39,14 @@ static constexpr const char* TAG = "TerminalMcpBridge";
static constexpr int kMaxHeaderBytes = 16 * 1024;
static constexpr int kMaxBodyBytes = 4 * 1024 * 1024; // 4 MB
+// Run-scope bounds. A caller that forgets end_run() leaves its scope behind;
+// that is fail-safe (the run's policy simply stays enforced for a token nobody
+// holds any more) but must not accumulate for the session. Both limits are far
+// beyond any real agent run — a finagent process is driven by an LLM loop with
+// an 85 s per-tool timeout, and concurrency is a handful of runs at most.
+static constexpr qint64 kRunScopeMaxLifetimeMs = 6LL * 60 * 60 * 1000; // 6 h
+static constexpr int kMaxLiveRunScopes = 256;
+
// Per-thread flags: set by the bridge across the synchronous portion of
// McpProvider::call_tool_async (where auth runs). The McpProvider auth
// checker reads these to distinguish agent-originated calls from chat-path
@@ -47,6 +63,66 @@ bool TerminalMcpBridge::is_destructive_allowed() {
}
namespace {
+
+// Categories an agent may never dispatch, regardless of what its catalog says.
+// Mirrors the default `exclude_categories` AgentService applies when it builds
+// `terminal_tools` — UI-driving tools ("navigation"/"system"/"settings"),
+// recursive chat tools ("ai-chat"), and the tool-discovery meta tools.
+// Excludes a specific agent adds on top of these are enforced per run, via the
+// run scope opened by begin_run() (see filter_excludes below).
+const QStringList& never_dispatchable_categories() {
+ static const QStringList kCats = {QStringLiteral("navigation"), QStringLiteral("system"),
+ QStringLiteral("settings"), QStringLiteral("ai-chat"), QStringLiteral("meta")};
+ return kCats;
+}
+
+// True when `filter` would have kept this tool OUT of the catalog it built, in
+// which case dispatching it must be refused too. Predicates mirror
+// McpService::apply_tool_filter exactly (category include/exclude, then name
+// regex include/exclude) so the catalog an agent sees and the calls the bridge
+// honours cannot disagree.
+//
+// `filter.max_tools` is deliberately NOT applied: it caps how large a catalog
+// the agent is shown, not which tools are permitted. Enforcing a count here
+// would make a call's fate depend on how many other tools happened to sort
+// ahead of it — a different rule wearing the same name.
+//
+// `category` is empty for tools on external MCP servers; that is the same value
+// apply_tool_filter sees for them, so a whitelist filter excludes them there and
+// here alike.
+bool filter_excludes(const ToolFilter& filter, const QString& tool_name, const QString& category, QString* reason) {
+ auto deny = [reason](const QString& why) {
+ if (reason)
+ *reason = why;
+ return true;
+ };
+
+ if (!filter.categories.isEmpty() && (category.isEmpty() || !filter.categories.contains(category)))
+ return deny(QStringLiteral("category '%1' is not in this agent's allowed categories").arg(category));
+
+ if (!filter.exclude_categories.isEmpty() && filter.exclude_categories.contains(category))
+ return deny(QStringLiteral("category '%1' is excluded by this agent's configuration").arg(category));
+
+ if (!filter.name_patterns.isEmpty()) {
+ bool any_match = false;
+ for (const auto& p : filter.name_patterns) {
+ if (QRegularExpression(p).match(tool_name).hasMatch()) {
+ any_match = true;
+ break;
+ }
+ }
+ if (!any_match)
+ return deny(QStringLiteral("tool name does not match this agent's allowed name patterns"));
+ }
+
+ for (const auto& p : filter.exclude_name_patterns) {
+ if (QRegularExpression(p).match(tool_name).hasMatch())
+ return deny(QStringLiteral("tool name is excluded by this agent's configuration"));
+ }
+
+ return false;
+}
+
struct CallFlagGuard {
explicit CallFlagGuard(bool destructive_ok) {
tls_call_in_progress = true;
@@ -116,6 +192,12 @@ void TerminalMcpBridge::stop() {
}
states_.clear();
+ {
+ // Run scopes die with the listener — a restart mints fresh tokens.
+ QMutexLocker lock(&runs_mutex_);
+ runs_.clear();
+ }
+
if (server_) {
server_->close();
server_->deleteLater();
@@ -130,6 +212,93 @@ QString TerminalMcpBridge::endpoint() const {
return QString("http://127.0.0.1:%1").arg(server_->serverPort());
}
+// ── Run scopes ───────────────────────────────────────────────────────────────
+
+QString TerminalMcpBridge::begin_run(const ToolFilter& filter, bool include_external) {
+ if (!active_)
+ return token_; // nothing listening — nothing to scope
+
+ RunScope scope;
+ scope.filter = filter;
+ scope.include_external = include_external;
+ scope.started_ms = QDateTime::currentMSecsSinceEpoch();
+
+ const QString run_token = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ {
+ QMutexLocker lock(&runs_mutex_);
+ sweep_runs_locked();
+ runs_.insert(run_token, scope);
+ }
+ return run_token;
+}
+
+void TerminalMcpBridge::end_run(const QString& run_token) {
+ if (run_token.isEmpty())
+ return;
+ QMutexLocker lock(&runs_mutex_);
+ runs_.remove(run_token);
+}
+
+void TerminalMcpBridge::sweep_runs_locked() {
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ int aged_out = 0;
+ for (auto it = runs_.begin(); it != runs_.end();) {
+ if (now - it.value().started_ms > kRunScopeMaxLifetimeMs) {
+ it = runs_.erase(it);
+ ++aged_out;
+ } else {
+ ++it;
+ }
+ }
+
+ // Hard ceiling as a second backstop, oldest first.
+ while (runs_.size() >= kMaxLiveRunScopes) {
+ auto oldest = runs_.begin();
+ for (auto it = runs_.begin(); it != runs_.end(); ++it) {
+ if (it.value().started_ms < oldest.value().started_ms)
+ oldest = it;
+ }
+ runs_.erase(oldest);
+ ++aged_out;
+ }
+
+ if (aged_out > 0)
+ LOG_DEBUG(TAG, QString("Swept %1 stale agent run scope(s); %2 live").arg(aged_out).arg(runs_.size()));
+}
+
+std::optional<TerminalMcpBridge::RunScope> TerminalMcpBridge::run_scope(const QString& run_token) const {
+ if (run_token.isEmpty())
+ return std::nullopt;
+ QMutexLocker lock(&runs_mutex_);
+ const auto it = runs_.constFind(run_token);
+ if (it == runs_.constEnd())
+ return std::nullopt;
+ return it.value();
+}
+
+bool TerminalMcpBridge::authenticate(const QString& supplied, QString* run_token_out) const {
+ if (run_token_out)
+ run_token_out->clear();
+ if (supplied.isEmpty() || token_.isEmpty())
+ return false;
+
+ // Constant-time throughout: `supplied` is attacker-controlled, and a
+ // short-circuiting compare leaks how many leading bytes were right, which
+ // turns a 128-bit guess into a byte-at-a-time search.
+ if (auth::constant_time_equals(supplied, token_))
+ return true;
+
+ QMutexLocker lock(&runs_mutex_);
+ for (auto it = runs_.constBegin(); it != runs_.constEnd(); ++it) {
+ if (auth::constant_time_equals(supplied, it.key())) {
+ if (run_token_out)
+ *run_token_out = it.key();
+ return true;
+ }
+ }
+ return false;
+}
+
// ── Tool catalog serialisation ───────────────────────────────────────────────
QJsonArray TerminalMcpBridge::tool_definitions(const ToolFilter& filter, bool include_external) const {
@@ -261,9 +430,34 @@ void TerminalMcpBridge::try_dispatch(QTcpSocket* sock) {
return;
RequestState& st = it.value();
- // Authn — must come before any work happens.
+ // ── Origin validation — must come before authn, and before any work ──────
+ //
+ // Binding 127.0.0.1 keeps other hosts out; it does not keep out the user's
+ // own browser. Any page they have open can POST at this port, and a page
+ // that resolves a hostname it controls to 127.0.0.1 (DNS rebinding) can talk
+ // to us as same-origin. The custom X-MCP-Token header forces a CORS
+ // preflight that this server never answers, which happens to stop a browser
+ // today — but that is a side effect of the header, not a decision, and it
+ // stops nothing that isn't a browser. Check Host and the fetch metadata
+ // explicitly, like the other four loopback listeners do.
+ //
+ // allow_cross_site_navigation=false: unlike the OAuth / wallet callbacks
+ // this endpoint is a machine-to-machine JSON API. It has no legitimate
+ // top-level navigation, so a navigate-mode request is never ours. The
+ // Python agent uses urllib and sends no Sec-Fetch-* at all, which the guard
+ // passes through to the token check below.
+ const quint16 bound_port = server_ ? static_cast<quint16>(server_->serverPort()) : 0;
+ const auto origin_check = auth::check_loopback_request(st.buffer, bound_port,
+ /*allow_cross_site_navigation=*/false);
+ if (!origin_check.allowed) {
+ LOG_WARN(TAG, QString("Rejecting request — %1 (path=%2)").arg(origin_check.reason, st.path));
+ write_error(sock, 403, "Request rejected by origin policy");
+ return;
+ }
+
+ // Authn — constant-time against the process token and every live run token.
const QString supplied = st.headers.value("x-mcp-token");
- if (supplied != token_) {
+ if (!authenticate(supplied, &st.run_token)) {
LOG_WARN(TAG, QString("Rejecting request — token mismatch (path=%1)").arg(st.path));
write_error(sock, 401, "Invalid or missing X-MCP-Token");
return;
@@ -309,36 +503,101 @@ void TerminalMcpBridge::handle_post_tool(QTcpSocket* sock, const QJsonObject& bo
LOG_INFO(TAG, QString("Tool call %1: %2 on %3").arg(call_id, tool_name, server_id));
+ auto it_state = states_.find(sock);
+ const RequestState* req = (it_state != states_.end()) ? &it_state.value() : nullptr;
+
+ auto refuse = [this, sock, call_id, &tool_name](const QString& why) {
+ LOG_WARN(TAG, QString("Refusing tool '%1' — %2").arg(tool_name, why));
+ QJsonObject refusal =
+ ToolResult::fail(QString("Tool '%1' is not available to this agent (%2).").arg(tool_name, why)).to_json();
+ if (!call_id.isEmpty())
+ refusal["id"] = call_id;
+ write_json_response(sock, 200, refusal);
+ };
+
+ // ── Tool boundary, enforced at DISPATCH ──────────────────────────────────
+ //
+ // Filters applied when `terminal_tools` was built only shape the catalog —
+ // an agent that knows a tool's name (stale catalog, guess, injected
+ // instruction) could POST it here and run an "excluded" tool anyway. Two
+ // layers, in order:
+ //
+ // 1. never_dispatchable_categories() — process-wide, non-negotiable,
+ // matches the defaults AgentService merges into every filter.
+ // 2. the caller's own run scope — the per-agent filter this run was
+ // opened with (begin_run), so an agent's own exclude_categories /
+ // exclude_name_patterns bind its calls and not just its catalog.
+ QString category; // empty for tools on external MCP servers
+ if (server_id == INTERNAL_SERVER_ID) {
+ if (const auto info = McpProvider::instance().find_tool(tool_name))
+ category = info->category;
+ if (never_dispatchable_categories().contains(category)) {
+ refuse(QString("category '%1' is not dispatchable over the agent bridge").arg(category));
+ return;
+ }
+ }
+
+ if (const auto scope = run_scope(req ? req->run_token : QString())) {
+ if (!scope->include_external && server_id != INTERNAL_SERVER_ID) {
+ refuse(QStringLiteral("external MCP tools are disabled for this agent"));
+ return;
+ }
+ QString why;
+ if (filter_excludes(scope->filter, tool_name, category, &why)) {
+ refuse(why);
+ return;
+ }
+ }
+
QPointer<TerminalMcpBridge> self = this;
QPointer<QTcpSocket> sock_guard = sock;
- // Internal vs external routing. Both shapes return QFuture<ToolResult>
- // and we resolve via QFutureWatcher so the socket write happens on the
- // main thread when the future completes — never blocks newConnection.
// The auth checker (installed by AgentService) inspects
// is_call_in_progress() and is_destructive_allowed() to apply
- // agent-specific gating. The flag scope covers only the synchronous
- // dispatch — the auth check runs there before call_tool_async returns
- // its future.
- auto it_state = states_.find(sock);
- const QString destructive_hdr =
- (it_state != states_.end()) ? it_state.value().headers.value("x-mcp-allow-destructive") : QString();
- const bool destructive_ok = !destructive_token_.isEmpty() && destructive_hdr == destructive_token_;
-
- QFuture<ToolResult> future;
- {
+ // agent-specific gating. Constant-time compare — the header is
+ // attacker-controlled and the token is a capability.
+ const QString destructive_hdr = req ? req->headers.value("x-mcp-allow-destructive") : QString();
+ const bool destructive_ok =
+ !destructive_token_.isEmpty() && auth::constant_time_equals(destructive_hdr, destructive_token_);
+
+ // Dispatch OFF the GUI thread.
+ //
+ // AgentService is constructed on the GUI thread, so this QTcpServer and
+ // every accepted socket are GUI-thread objects: readyRead → on_ready_read →
+ // try_dispatch → here, with no thread hop. Sync-shape handlers then ran
+ // inline on the GUI thread, and tools/ThreadHelper.h's run_async_wait saw
+ // `currentThread() == target->thread()` and took the branch that ends in
+ // loop.exec(ExcludeUserInputEvents) with no timeout. Because exec() keeps
+ // pumping socket events, a second concurrent tool call re-entered
+ // handle_post_tool and stacked another nested loop on top — unbounded,
+ // re-entrant, and holding the UI hostage for the duration of every agent
+ // tool call.
+ //
+ // CallFlagGuard is thread_local, so it MUST be re-established inside the
+ // worker: without it the auth checker sees a chat-path call and the
+ // destructive gate silently opens.
+ auto promise = std::make_shared<QPromise<ToolResult>>();
+ promise->start();
+ QFuture<ToolResult> future = promise->future();
+ (void)QtConcurrent::run([promise, tool_name, args, server_id, destructive_ok]() mutable {
CallFlagGuard guard(destructive_ok);
+ QFuture<ToolResult> f;
if (server_id == INTERNAL_SERVER_ID) {
- future = McpProvider::instance().call_tool_async(tool_name, args);
+ f = McpProvider::instance().call_tool_async(tool_name, args);
} else {
// External — McpService::execute_openai_function_async handles the
// QtConcurrent::run wrapping for blocking JSON-RPC clients. Build
// the wire-form name it expects.
const QString fn = server_id + "__" + McpProvider::encode_tool_name_for_wire(tool_name);
- future = McpService::instance().execute_openai_function_async(fn, args);
+ f = McpService::instance().execute_openai_function_async(fn, args);
}
- }
+ f.waitForFinished();
+ promise->addResult(f.resultCount() > 0 ? f.result() : ToolResult::fail("Tool produced no result"));
+ promise->finish();
+ });
+ // Resolve via QFutureWatcher so the socket write lands back on this
+ // (GUI) thread when the worker completes.
auto* watcher = new QFutureWatcher<ToolResult>(this);
connect(watcher, &QFutureWatcher<ToolResult>::finished, this, [self, sock_guard, tool_name, call_id, watcher]() {
const auto fut = watcher->future();
@@ -361,13 +620,20 @@ void TerminalMcpBridge::handle_post_tool(QTcpSocket* sock, const QJsonObject& bo
// ── GET /tools ──────────────────────────────────────────────────────────────
void TerminalMcpBridge::handle_get_tools(QTcpSocket* sock) {
- // Default filter — the catalog the agent gets at boot is also what
- // dynamic refresh returns. AgentService::build_payload owns the per-run
- // filter; this endpoint is a fallback and uses the same defaults.
+ // A caller inside a run scope gets exactly the catalog its own filter
+ // produces, so a dynamic refresh can never widen what dispatch will honour.
+ // Outside a run scope this is a fallback and uses the process defaults.
ToolFilter filter;
- filter.exclude_categories = {"navigation", "system", "settings", "ai-chat", "meta"};
+ bool include_external = true;
+ const auto it = states_.constFind(sock);
+ if (const auto scope = run_scope(it != states_.constEnd() ? it.value().run_token : QString())) {
+ filter = scope->filter;
+ include_external = scope->include_external;
+ } else {
+ filter.exclude_categories = never_dispatchable_categories();
+ }
QJsonObject payload;
- payload["tools"] = tool_definitions(filter);
+ payload["tools"] = tool_definitions(filter, include_external);
write_json_response(sock, 200, payload);
}
@@ -381,6 +647,8 @@ static const char* status_text(int code) {
return "Bad Request";
case 401:
return "Unauthorized";
+ case 403:
+ return "Forbidden";
case 404:
return "Not Found";
case 413:
diff --git a/fincept-qt/src/mcp/TerminalMcpBridge.h b/fincept-qt/src/mcp/TerminalMcpBridge.h
index 4682ee30b..8655ba5a7 100644
--- a/fincept-qt/src/mcp/TerminalMcpBridge.h
+++ b/fincept-qt/src/mcp/TerminalMcpBridge.h
@@ -8,10 +8,18 @@
// POST <endpoint>/tool body: {id, tool, args} → ToolResult JSON
// (optional) GET <endpoint>/tools → [{name, description, inputSchema}]
//
-// Auth: every request must include `X-MCP-Token: <token>`. The token is a
-// UUID generated per-process and injected into the agent config payload by
-// AgentService — agents share the parent's user session, so the token only
-// guards against OTHER local processes stumbling onto the port.
+// Auth: every request must include `X-MCP-Token: <token>`, compared in constant
+// time. Two kinds of token are accepted: the per-process UUID (`token()`), and
+// a per-run UUID minted by `begin_run()` that additionally binds that agent's
+// own tool filter to dispatch. AgentService injects one into the agent config
+// payload. Agents share the parent's user session, so the token only guards
+// against OTHER local processes stumbling onto the port.
+//
+// Every request is also checked against auth/LoopbackGuard.h (Host must be our
+// own loopback authority; no cross-site fetch metadata), which is what stops a
+// web page the user has open — or a DNS-rebound hostname — from driving this
+// port. This endpoint is machine-to-machine, so cross-site navigations are
+// rejected too.
//
// Transport: QTcpServer + manual HTTP/1.1 framing (Qt6::HttpServer is not
// available in this Qt 6.8.3 build). Localhost-only binding on 127.0.0.1:0
@@ -21,9 +29,12 @@
#include <QHash>
#include <QJsonArray>
+#include <QMutex>
#include <QObject>
#include <QString>
+#include <optional>
+
class QTcpServer;
class QTcpSocket;
@@ -46,9 +57,29 @@ class TerminalMcpBridge : public QObject {
/// "http://127.0.0.1:<port>" — no path, no query. Empty when not active.
QString endpoint() const;
- /// Per-process UUID. Agents include this as `X-MCP-Token` on every call.
+ /// Per-process UUID. Accepted as `X-MCP-Token` for the life of the process.
+ /// Prefer `begin_run()` for anything that spawns an agent — a run-scoped
+ /// token carries that agent's own tool filter to the dispatch path.
QString token() const { return token_; }
+ /// Open a run scope and mint the `X-MCP-Token` the agent should present.
+ ///
+ /// The returned token authenticates exactly like `token()` but additionally
+ /// binds `filter` / `include_external` to every call made with it, so the
+ /// per-agent tool filter is enforced at DISPATCH and not only when the
+ /// catalog is built. Without this an agent that knows a tool's name could
+ /// POST a tool its own configuration excluded — the catalog is a hint, the
+ /// bridge is the boundary.
+ ///
+ /// Returns `token()` unchanged when the bridge is not listening (nothing to
+ /// scope). Pair with `end_run()`; scopes are also swept by age and count so
+ /// a caller that never retires one cannot grow the map without bound.
+ QString begin_run(const ToolFilter& filter, bool include_external = true);
+
+ /// Retire a run scope minted by `begin_run()`. No-op for an empty token,
+ /// the process token, or a token that has already been retired.
+ void end_run(const QString& run_token);
+
/// Second per-process UUID. Only injected into agent configs whose
/// `allow_destructive_tools=true`; the agent's toolkit echoes it back as
/// `X-MCP-Allow-Destructive` on each request. Bridge compares the header
@@ -119,11 +150,34 @@ class TerminalMcpBridge : public QObject {
QString path;
int content_length = 0;
QHash<QString, QString> headers;
+ /// Run scope this request authenticated against, empty when it
+ /// presented the process-wide token. Resolved once in try_dispatch()
+ /// so the handlers don't re-walk the token map.
+ QString run_token;
+ };
+
+ /// One live agent run: the tool policy its calls are held to.
+ struct RunScope {
+ ToolFilter filter;
+ bool include_external = true;
+ qint64 started_ms = 0;
};
bool parse_headers(RequestState& st);
void try_dispatch(QTcpSocket* sock);
+ /// Constant-time match of a supplied `X-MCP-Token` against the process
+ /// token and every live run token. On a run-token hit, `run_token_out`
+ /// receives it; on a process-token hit it is cleared.
+ bool authenticate(const QString& supplied, QString* run_token_out) const;
+
+ std::optional<RunScope> run_scope(const QString& run_token) const;
+
+ /// Drop run scopes that are too old or too numerous. Caller holds
+ /// `runs_mutex_`. A leaked scope is fail-safe (the policy stays enforced),
+ /// but it must not accumulate for the life of the process.
+ void sweep_runs_locked();
+
void handle_post_tool(QTcpSocket* sock, const QJsonObject& body);
void handle_get_tools(QTcpSocket* sock);
@@ -135,6 +189,12 @@ class TerminalMcpBridge : public QObject {
QString token_;
QString destructive_token_;
QHash<QTcpSocket*, RequestState> states_;
+
+ /// Live run scopes keyed by the run token handed to the agent. Socket
+ /// handling is GUI-thread-only, but begin_run/end_run are called from the
+ /// agent layer, so this one map is mutex-guarded.
+ QHash<QString, RunScope> runs_;
+ mutable QMutex runs_mutex_;
};
} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/tools/DataSourcesTools.cpp b/fincept-qt/src/mcp/tools/DataSourcesTools.cpp
index ffb2c53ad..0c3b224b7 100644
--- a/fincept-qt/src/mcp/tools/DataSourcesTools.cpp
+++ b/fincept-qt/src/mcp/tools/DataSourcesTools.cpp
@@ -7,6 +7,7 @@
#include "screens/data_sources/ConnectorRegistry.h"
#include "screens/data_sources/DataSourceTypes.h"
#include "storage/repositories/DataSourceRepository.h"
+#include "trading/brokers/BrokerLogRedact.h"
#include <QJsonArray>
#include <QJsonDocument>
@@ -20,6 +21,24 @@ using namespace fincept::screens::datasources;
// ── Helpers ──────────────────────────────────────────────────────────────────
+// `config` is the connector's saved field values — which for most connectors
+// means the password / api_key / token the user typed in. Returning it verbatim
+// made ds_get_connection a credential read, and ds_list_connections (which
+// takes no arguments at all) a one-call bulk dump of every stored connector
+// credential. Redact by key name, reusing redact_detail::is_secret_key from the
+// broker log redactor so there is exactly one list of "what counts as a secret"
+// in the tree. Shape is preserved (still a JSON string) so existing consumers
+// keep parsing it; only secret-named values become "<redacted:N>".
+static QString redact_config_json(const QString& raw) {
+ if (raw.trimmed().isEmpty())
+ return raw;
+ const QJsonDocument doc = QJsonDocument::fromJson(raw.toUtf8());
+ if (!doc.isObject()) // unparseable — we cannot tell which bytes are secret
+ return QStringLiteral("<unparseable config, %1 bytes>").arg(raw.size());
+ return QString::fromUtf8(
+ QJsonDocument(trading::redact_detail::redact_object(doc.object())).toJson(QJsonDocument::Compact));
+}
+
static QJsonObject ds_to_json(const DataSource& ds) {
return QJsonObject{
{"id", ds.id},
@@ -29,7 +48,7 @@ static QJsonObject ds_to_json(const DataSource& ds) {
{"type", ds.type},
{"provider", ds.provider},
{"category", ds.category},
- {"config", ds.config},
+ {"config", redact_config_json(ds.config)},
{"enabled", ds.enabled},
{"tags", ds.tags},
{"created_at", ds.created_at},
@@ -125,7 +144,8 @@ std::vector<ToolDef> get_data_sources_tools() {
{
ToolDef t;
t.name = "ds_get_connection";
- t.description = "Get full details (including config JSON) for a saved connection by ID.";
+ t.description = "Get full details for a saved connection by ID. Secret config fields "
+ "(passwords, API keys, tokens) are redacted.";
t.category = "data-sources";
t.input_schema.properties = QJsonObject{
{"id", QJsonObject{{"type", "string"}, {"description", "Connection ID (UUID)"}}},
diff --git a/fincept-qt/src/mcp/tools/ExcelTools.cpp b/fincept-qt/src/mcp/tools/ExcelTools.cpp
index 9581575dd..5a5eb6f92 100644
--- a/fincept-qt/src/mcp/tools/ExcelTools.cpp
+++ b/fincept-qt/src/mcp/tools/ExcelTools.cpp
@@ -19,13 +19,18 @@
#include "core/window/WindowRegistry.h"
#include "mcp/AsyncDispatch.h"
#include "mcp/ToolSchemaBuilder.h"
+#include "mcp/tools/ExportPathGuard.h"
#include "screens/excel/ExcelScreen.h"
#include "screens/excel/SpreadsheetWidget.h"
+#include "services/file_manager/FileManagerService.h"
+
+#include <algorithm>
#include <QApplication>
#include <QFile>
#include <QJsonArray>
#include <QJsonObject>
+#include <QRegularExpression>
#include <QTabWidget>
#include <QTextStream>
@@ -35,6 +40,13 @@ namespace {
static constexpr const char* TAG = "ExcelTools";
static constexpr int kDefaultTimeoutMs = 15000;
+// Bulk sheet reads/writes run on the UI thread and repopulate every cell, which
+// on a full model is far more work than a single-cell edit. 15 s was not enough:
+// set_excel_sheet_data and get_excel_sheet_data were both killed mid-flight,
+// leaving a half-written sheet — which is where the stray zeros came from, since
+// formulas pointing at cells that never got written evaluate to 0.
+static constexpr int kBulkTimeoutMs = 90000;
+
screens::ExcelScreen* find_excel_screen() {
for (auto* w : WindowRegistry::instance().frames()) {
if (!w || !w->dock_router())
@@ -53,8 +65,53 @@ screens::ExcelScreen* find_excel_screen() {
return nullptr;
}
+// Excel screen, building it on demand.
+//
+// Screens are lazily constructed (P2), so the Excel screen does not exist until
+// the user visits that tab. Every tool here resolved through find_excel_screen()
+// and hard-failed with "Excel screen not open" when it wasn't — which meant an
+// agent driving Excel from the AI Chat tab could fetch SEC data, plan a full DCF
+// model, create the sheet, and then lose 45 consecutive set_excel_cell calls to
+// a screen that had simply never been built. Asking the user to go open a tab
+// first is not a workable contract for a tool the model calls on its own.
+//
+// Tools run on the UI thread (run_on_ui), so constructing widgets here is safe.
+// Two cases: the dock exists but holds a placeholder (materialize_now builds the
+// screen in place, no visible change), or there is no dock at all (navigate
+// creates and shows it — the user asked for work in Excel, so surfacing it is
+// the expected outcome, and it is the only path that registers the dock).
+screens::ExcelScreen* ensure_excel_screen() {
+ if (auto* es = find_excel_screen())
+ return es;
+
+ // Never restructure the dock layout while a modal dialog is open. Tool
+ // bodies are queued onto the UI thread, so they also run inside the nested
+ // event loop of a file dialog — navigating there would rebuild docks under
+ // a screen that is mid-export and holding pointers into them.
+ if (QApplication::activeModalWidget()) {
+ LOG_WARN(TAG, "Excel screen missing but a modal dialog is open — refusing to navigate");
+ return nullptr;
+ }
+
+ for (auto* w : WindowRegistry::instance().frames()) {
+ auto* router = w ? w->dock_router() : nullptr;
+ if (!router)
+ continue;
+ if (router->find_dock_widget("excel"))
+ router->materialize_now("excel");
+ else
+ router->navigate("excel");
+ if (auto* es = find_excel_screen()) {
+ LOG_INFO(TAG, "Excel screen was not open — opened it for a tool call");
+ return es;
+ }
+ }
+ LOG_WARN(TAG, "Could not open the Excel screen for a tool call");
+ return nullptr;
+}
+
QTabWidget* find_excel_tabs() {
- auto* es = find_excel_screen();
+ auto* es = ensure_excel_screen();
return es ? es->findChild<QTabWidget*>() : nullptr;
}
@@ -70,7 +127,62 @@ screens::SpreadsheetWidget* active_sheet() {
return tabs ? sheet_by_index(tabs->currentIndex()) : nullptr;
}
+screens::SpreadsheetWidget* sheet_by_name(const QString& name) {
+ auto* tabs = find_excel_tabs();
+ if (!tabs || name.isEmpty())
+ return nullptr;
+ for (int i = 0; i < tabs->count(); ++i) {
+ auto* s = qobject_cast<screens::SpreadsheetWidget*>(tabs->widget(i));
+ if (s && s->sheet_name().compare(name, Qt::CaseInsensitive) == 0)
+ return s;
+ }
+ return nullptr;
+}
+
+// ── Addressing aliases ──────────────────────────────────────────────────────
+//
+// These tools address a live Excel *screen*: sheets by integer index, cells by
+// zero-based row/col. Every Excel API a model has ever seen — openpyxl,
+// xlsxwriter, the Sheets API, VBA — addresses workbooks by file, sheets by NAME
+// and cells by A1 reference. So models confidently send
+// {workbook_name, tab_name, cell_ref:"B87"}, which matched nothing and failed
+// every call; one turn made 15 such calls, had all 15 rejected, and reported a
+// finished model anyway.
+//
+// Rather than expect every model to learn an unusual convention, accept the
+// conventional one too. Index/row/col remain canonical; these are aliases.
+
+// "B87" / "$B$87" → row 86, col 1 (both zero-based). False if not A1 notation.
+bool parse_a1_ref(const QString& ref, int& row, int& col) {
+ static const QRegularExpression re(QStringLiteral("^\\$?([A-Za-z]{1,3})\\$?([0-9]{1,7})$"));
+ const auto m = re.match(ref.trimmed());
+ if (!m.hasMatch())
+ return false;
+
+ const QString letters = m.captured(1).toUpper();
+ int c = 0;
+ for (const QChar& ch : letters)
+ c = c * 26 + (ch.unicode() - 'A' + 1);
+
+ const int r = m.captured(2).toInt();
+ if (c <= 0 || r <= 0)
+ return false;
+ col = c - 1;
+ row = r - 1;
+ return true;
+}
+
+/// Sheet from sheet_index, or the sheet_name/tab_name alias, or the active one.
screens::SpreadsheetWidget* resolve_sheet(const QJsonObject& args) {
+ for (const char* key : {"sheet_name", "tab_name"}) {
+ const QString name = args.value(QLatin1String(key)).toString().trimmed();
+ if (!name.isEmpty()) {
+ if (auto* s = sheet_by_name(name))
+ return s;
+ return nullptr; // named a sheet that doesn't exist — don't silently
+ // fall through to the active one and edit the wrong sheet
+ }
+ }
if (args.contains("sheet_index") && !args["sheet_index"].isNull()) {
const int i = args["sheet_index"].toInt(-1);
if (i >= 0)
@@ -79,6 +191,59 @@ screens::SpreadsheetWidget* resolve_sheet(const QJsonObject& args) {
return active_sheet();
}
+/// Row/col from the explicit integers, or from a cell/cell_ref A1 alias.
+/// Returns false when neither was supplied (or the A1 string is malformed).
+bool resolve_row_col(const QJsonObject& args, int& row, int& col) {
+ if (args.contains("row") && args.contains("col")) {
+ row = args["row"].toInt(-1);
+ col = args["col"].toInt(-1);
+ return row >= 0 && col >= 0;
+ }
+ for (const char* key : {"cell", "cell_ref", "cell_reference", "ref"}) {
+ const QString ref = args.value(QLatin1String(key)).toString();
+ if (!ref.isEmpty())
+ return parse_a1_ref(ref, row, col);
+ }
+ return false;
+}
+
+/// Declare the alias params so validation accepts them (unknown args are now
+/// rejected) and tool_describe advertises them.
+ToolSchema with_sheet_aliases(ToolSchema s) {
+ ToolParam name_p;
+ name_p.type = "string";
+ name_p.description = "Sheet name, as an alternative to sheet_index";
+ s.params["sheet_name"] = name_p;
+ s.params["tab_name"] = name_p; // common synonym
+
+ ToolParam wb;
+ wb.type = "string";
+ wb.description = "Ignored - there is one live workbook (the Excel screen). Accepted for compatibility.";
+ s.params["workbook_name"] = wb;
+ return s;
+}
+
+ToolSchema with_cell_aliases(ToolSchema s) {
+ s = with_sheet_aliases(std::move(s));
+ ToolParam cell;
+ cell.type = "string";
+ cell.description = "Cell in A1 notation (e.g. \"B87\"), as an alternative to row + col";
+ s.params["cell"] = cell;
+ s.params["cell_ref"] = cell;
+ // row/col stay declared but stop being mandatory — either addressing form is
+ // valid, so the handler enforces "one of the two" instead.
+ if (s.params.contains("row"))
+ s.params["row"].required = false;
+ if (s.params.contains("col"))
+ s.params["col"].required = false;
+ s.required.removeAll(QStringLiteral("row"));
+ s.required.removeAll(QStringLiteral("col"));
+ return s;
+}
+
+constexpr const char* kAddressingError =
+ "Specify the cell either as row + col (zero-based integers) or as cell=\"B87\" (A1 notation)";
+
template <typename BodyFn>
void run_on_ui(ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise, BodyFn&& body) {
AsyncDispatch::callback_to_promise(qApp, std::move(ctx), promise, std::forward<BodyFn>(body));
@@ -99,7 +264,7 @@ std::vector<ToolDef> get_excel_tools() {
run_on_ui(std::move(ctx), promise, [](auto resolve) {
auto* tabs = find_excel_tabs();
if (!tabs) {
- resolve(ToolResult::fail("Excel screen not open"));
+ resolve(ToolResult::fail("Excel screen could not be opened"));
return;
}
QJsonArray arr;
@@ -132,7 +297,7 @@ std::vector<ToolDef> get_excel_tools() {
run_on_ui(std::move(ctx), promise, [](auto resolve) {
auto* tabs = find_excel_tabs();
if (!tabs) {
- resolve(ToolResult::fail("Excel screen not open"));
+ resolve(ToolResult::fail("Excel screen could not be opened"));
return;
}
auto* s = active_sheet();
@@ -160,11 +325,12 @@ std::vector<ToolDef> get_excel_tools() {
t.is_destructive = true;
t.default_timeout_ms = kDefaultTimeoutMs;
t.input_schema = ToolSchemaBuilder().integer("sheet_index", "Sheet index").required().min(0).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* tabs = find_excel_tabs();
if (!tabs) {
- resolve(ToolResult::fail("Excel screen not open"));
+ resolve(ToolResult::fail("Excel screen could not be opened"));
return;
}
const int i = args["sheet_index"].toInt();
@@ -203,7 +369,7 @@ std::vector<ToolDef> get_excel_tools() {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* tabs = find_excel_tabs();
if (!tabs) {
- resolve(ToolResult::fail("Excel screen not open"));
+ resolve(ToolResult::fail("Excel screen could not be opened"));
return;
}
QString name = args["name"].toString();
@@ -228,11 +394,12 @@ std::vector<ToolDef> get_excel_tools() {
t.auth_required = AuthLevel::ExplicitConfirm;
t.default_timeout_ms = kDefaultTimeoutMs;
t.input_schema = ToolSchemaBuilder().integer("sheet_index", "Sheet index to delete").required().min(0).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* tabs = find_excel_tabs();
if (!tabs) {
- resolve(ToolResult::fail("Excel screen not open"));
+ resolve(ToolResult::fail("Excel screen could not be opened"));
return;
}
const int i = args["sheet_index"].toInt();
@@ -270,17 +437,18 @@ std::vector<ToolDef> get_excel_tools() {
.required()
.length(1, 64)
.build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* tabs = find_excel_tabs();
if (!tabs) {
- resolve(ToolResult::fail("Excel screen not open"));
+ resolve(ToolResult::fail("Excel screen could not be opened"));
return;
}
const int i = args["sheet_index"].toInt();
auto* s = sheet_by_index(i);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
const QString name = args["name"].toString();
@@ -296,7 +464,9 @@ std::vector<ToolDef> get_excel_tools() {
{
ToolDef t;
t.name = "get_excel_cell";
- t.description = "Read a cell's raw text (may be a formula starting with '=').";
+ t.description = "Read a cell's raw text (may be a formula starting with '='). Address the cell either as "
+ "row + col (zero-based) or as cell=\"B87\" (A1 notation); the sheet as sheet_index or "
+ "sheet_name.";
t.category = "excel";
t.default_timeout_ms = kDefaultTimeoutMs;
t.input_schema = ToolSchemaBuilder()
@@ -310,14 +480,19 @@ std::vector<ToolDef> get_excel_tools() {
.required()
.min(0)
.build();
+ t.input_schema = with_cell_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheets"));
+ return;
+ }
+ int r = -1, c = -1;
+ if (!resolve_row_col(args, r, c)) {
+ resolve(ToolResult::fail(kAddressingError));
return;
}
- const int r = args["row"].toInt(), c = args["col"].toInt();
if (r >= s->row_count() || c >= s->col_count()) {
resolve(ToolResult::fail("Cell out of range"));
return;
@@ -337,7 +512,9 @@ std::vector<ToolDef> get_excel_tools() {
ToolDef t;
t.name = "set_excel_cell";
t.description =
- "Write a cell's text. Strings starting with '=' are evaluated as formulas (e.g. '=A1+B1', '=SUM(A1:A10)').";
+ "Write a cell's text. Strings starting with '=' are evaluated as formulas (e.g. '=A1+B1', "
+ "'=SUM(A1:A10)'). Address the cell either as row + col (zero-based) or as cell=\"B87\" (A1 notation); "
+ "the sheet as sheet_index or sheet_name.";
t.category = "excel";
t.is_destructive = true;
t.default_timeout_ms = kDefaultTimeoutMs;
@@ -355,14 +532,20 @@ std::vector<ToolDef> get_excel_tools() {
.required()
.length(0, 4096)
.build();
+ t.input_schema = with_cell_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheets"));
+ return;
+ }
+ int r = -1, c = -1;
+ if (!resolve_row_col(args, r, c)) {
+ resolve(ToolResult::fail(kAddressingError));
return;
}
- s->set_cell(args["row"].toInt(), args["col"].toInt(), args["text"].toString());
+ s->set_cell(r, c, args["text"].toString());
resolve(ToolResult::ok("Cell updated"));
});
};
@@ -373,7 +556,7 @@ std::vector<ToolDef> get_excel_tools() {
{
ToolDef t;
t.name = "clear_excel_cell";
- t.description = "Clear a cell (set to empty).";
+ t.description = "Clear a cell (set to empty). Address it as row + col (zero-based) or cell=\"B87\".";
t.category = "excel";
t.is_destructive = true;
t.default_timeout_ms = kDefaultTimeoutMs;
@@ -388,14 +571,20 @@ std::vector<ToolDef> get_excel_tools() {
.required()
.min(0)
.build();
+ t.input_schema = with_cell_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheets"));
return;
}
- s->set_cell(args["row"].toInt(), args["col"].toInt(), QString());
+ int r = -1, c = -1;
+ if (!resolve_row_col(args, r, c)) {
+ resolve(ToolResult::fail(kAddressingError));
+ return;
+ }
+ s->set_cell(r, c, QString());
resolve(ToolResult::ok("Cell cleared"));
});
};
@@ -408,14 +597,15 @@ std::vector<ToolDef> get_excel_tools() {
t.name = "get_excel_sheet_data";
t.description = "Get the entire sheet as a 2D array of cell text (rows of strings).";
t.category = "excel";
- t.default_timeout_ms = kDefaultTimeoutMs;
+ t.default_timeout_ms = kBulkTimeoutMs;
t.input_schema =
ToolSchemaBuilder().integer("sheet_index", "Sheet index (-1 = active)").default_int(-1).min(-1).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
const auto data = s->get_data();
@@ -442,20 +632,30 @@ std::vector<ToolDef> get_excel_tools() {
t.name = "set_excel_sheet_data";
t.description = "Replace the entire sheet with a 2D array of cell text.";
t.category = "excel";
+ // is_destructive only — NOT ExplicitConfirm. The confirm modal that
+ // level waits on was never built, so the checker in AgentService denies
+ // everything >= Verified outright and this tool could never run: the
+ // chat path got "requires explicit_confirm auth" on every call. Worse,
+ // it was inconsistent — set_excel_cell, add_excel_sheet, insert_excel_row
+ // and delete_excel_rows are all destructive without the gate, so writing
+ // 45 cells one at a time was permitted while writing them in one call
+ // was not. is_destructive still blocks the agent path (agents can't
+ // prompt); the chat path, where the user is present and watching, is
+ // allowed. delete_excel_sheet keeps its gate — it destroys existing work.
t.is_destructive = true;
- t.auth_required = AuthLevel::ExplicitConfirm;
- t.default_timeout_ms = kDefaultTimeoutMs;
+ t.default_timeout_ms = kBulkTimeoutMs;
t.input_schema = ToolSchemaBuilder()
.integer("sheet_index", "Sheet index (-1 = active)")
.default_int(-1)
.min(-1)
.array("rows", "2D array of strings (array of row arrays)", QJsonObject{{"type", "array"}})
.build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
QVector<QVector<QString>> data;
@@ -481,11 +681,12 @@ std::vector<ToolDef> get_excel_tools() {
t.default_timeout_ms = kDefaultTimeoutMs;
t.input_schema =
ToolSchemaBuilder().integer("sheet_index", "Sheet index (-1 = active)").default_int(-1).min(-1).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
resolve(ToolResult::ok_data(QJsonObject{
@@ -505,14 +706,15 @@ std::vector<ToolDef> get_excel_tools() {
t.description = "Force recalculation of all formula cells in a sheet.";
t.category = "excel";
t.is_destructive = true;
- t.default_timeout_ms = kDefaultTimeoutMs;
+ t.default_timeout_ms = kBulkTimeoutMs;
t.input_schema =
ToolSchemaBuilder().integer("sheet_index", "Sheet index (-1 = active)").default_int(-1).min(-1).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
s->recalculate();
@@ -538,11 +740,12 @@ std::vector<ToolDef> get_excel_tools() {
.default_str("below")
.enums({"above", "below"})
.build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
if (args["position"].toString("below") == "above")
@@ -571,11 +774,12 @@ std::vector<ToolDef> get_excel_tools() {
.default_str("right")
.enums({"left", "right"})
.build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
if (args["position"].toString("right") == "left")
@@ -598,11 +802,12 @@ std::vector<ToolDef> get_excel_tools() {
t.default_timeout_ms = kDefaultTimeoutMs;
t.input_schema =
ToolSchemaBuilder().integer("sheet_index", "Sheet index (-1 = active)").default_int(-1).min(-1).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
s->delete_selected_rows();
@@ -622,11 +827,12 @@ std::vector<ToolDef> get_excel_tools() {
t.default_timeout_ms = kDefaultTimeoutMs;
t.input_schema =
ToolSchemaBuilder().integer("sheet_index", "Sheet index (-1 = active)").default_int(-1).min(-1).build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
s->delete_selected_cols();
@@ -640,49 +846,94 @@ std::vector<ToolDef> get_excel_tools() {
{
ToolDef t;
t.name = "export_excel_sheet_csv";
- t.description = "Write a sheet to a CSV file on disk (programmatic, no file dialog).";
+ t.description = "Write a sheet to a CSV file inside the export directory (programmatic, no file dialog). "
+ "'path' is a filename or relative path inside that directory; absolute paths elsewhere "
+ "on disk are refused.";
t.category = "excel";
+ // See set_excel_sheet_data above for why ExplicitConfirm is not used.
+ // This is the ONLY tool that persists a sheet to disk, so leaving it
+ // gated meant nothing the model built could ever leave memory — a sheet
+ // it had just filled in was unreachable from File Manager.
+ //
+ // That argument covers the CONFIRMATION gate, not the PATH. `path` was
+ // still raw model text handed straight to QFile::open(WriteOnly), i.e.
+ // arbitrary write anywhere the process can reach. resolve_export_path()
+ // confines it without re-gating the tool.
t.is_destructive = true;
- t.auth_required = AuthLevel::ExplicitConfirm;
- t.default_timeout_ms = kDefaultTimeoutMs;
+ t.default_timeout_ms = kBulkTimeoutMs;
t.input_schema = ToolSchemaBuilder()
.integer("sheet_index", "Sheet index (-1 = active)")
.default_int(-1)
.min(-1)
- .string("path", "Output CSV file path")
+ .string("path", "Output CSV filename inside the export directory, e.g. 'model.csv'")
.required()
.length(1, 1024)
.build();
+ t.input_schema = with_sheet_aliases(std::move(t.input_schema));
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
auto* s = resolve_sheet(args);
if (!s) {
- resolve(ToolResult::fail("Sheet not found"));
+ resolve(ToolResult::fail("Sheet not found - call list_excel_sheets for valid sheet_index values"));
return;
}
- QFile f(args["path"].toString());
+ const auto dest = resolve_export_path(args["path"].toString());
+ if (!dest.ok()) {
+ resolve(ToolResult::fail(dest.error));
+ return;
+ }
+ QFile f(dest.path);
if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {
resolve(ToolResult::fail("Cannot open path for writing"));
return;
}
- QTextStream out(&f);
const auto data = s->get_data();
- for (const auto& row : data) {
- QStringList parts;
- for (const auto& cell : row) {
- QString c = cell;
- if (c.contains(',') || c.contains('"') || c.contains('\n')) {
- c.replace('"', "\"\"");
- c = '"' + c + '"';
+
+ // Trim to the used extent. get_data() pads every sheet to at
+ // least 100x26, so a 12-row model was exporting as 100 rows of
+ // bare commas.
+ int last_row = -1;
+ int last_col = -1;
+ for (int r = 0; r < data.size(); ++r) {
+ for (int c = 0; c < data[r].size(); ++c) {
+ if (!data[r][c].trimmed().isEmpty()) {
+ last_row = std::max(last_row, r);
+ last_col = std::max(last_col, c);
}
- parts.append(c);
}
- out << parts.join(',') << '\n';
+ }
+
+ {
+ QTextStream out(&f);
+ out.setEncoding(QStringConverter::Utf8);
+ for (int r = 0; r <= last_row; ++r) {
+ QStringList parts;
+ for (int c = 0; c <= last_col; ++c) {
+ QString cell = (c < data[r].size()) ? data[r][c] : QString();
+ if (cell.contains(',') || cell.contains('"') || cell.contains('\n')) {
+ cell.replace('"', "\"\"");
+ cell = '"' + cell + '"';
+ }
+ parts.append(cell);
+ }
+ out << parts.join(',') << '\n';
+ }
+ out.flush();
}
f.close();
+
+ // Register with File Manager, exactly as the UI export buttons
+ // do. Without this a model-driven export landed on disk but
+ // never appeared in the Files tab — the file existed and was
+ // simply invisible, which reads as "the export silently failed".
+ const QString out_path = dest.path;
+ const QString file_id = services::FileManagerService::instance().import_file(out_path, "excel");
+
resolve(ToolResult::ok("CSV exported", QJsonObject{
- {"path", args["path"].toString()},
- {"rows", static_cast<int>(data.size())},
+ {"path", out_path},
+ {"rows", last_row + 1},
+ {"cols", last_col + 1},
+ {"file_manager_id", file_id},
}));
});
};
diff --git a/fincept-qt/src/mcp/tools/ExportPathGuard.h b/fincept-qt/src/mcp/tools/ExportPathGuard.h
new file mode 100644
index 000000000..e68b3625a
--- /dev/null
+++ b/fincept-qt/src/mcp/tools/ExportPathGuard.h
@@ -0,0 +1,108 @@
+#pragma once
+// ExportPathGuard.h — one confinement check for every MCP tool that writes (or
+// reads) a caller-supplied filesystem path.
+//
+// Why this exists: `destination_path` / `path` on the export tools is raw
+// model-supplied text. Four tools took it unvalidated —
+// `download_managed_file`, `export_excel_sheet_csv`, `export_layout` /
+// `import_layout`, and `report_export_pdf` — which handed the LLM arbitrary
+// write, and (because `download_managed_file` called `QFile::remove(dest)`
+// unconditionally, purely to work around `QFile::copy` refusing to overwrite)
+// arbitrary *delete* as well. `destination_path="~/.ssh/id_rsa"` deleted the
+// key and then reported "Copy failed". Chained with `write_managed_text_file`
+// — whose bytes the model authors — it was arbitrary write-what-where, e.g. a
+// .cmd dropped into the Startup folder for code execution at next login.
+//
+// The rule: every model-supplied path must resolve inside a single export
+// directory. Canonicalise the PARENT (the destination file does not exist
+// yet, so `QFileInfo(dest).canonicalFilePath()` would be empty) and require it
+// to be the root itself or a descendant. Compare with a trailing separator, or
+// `<root>_evil` passes a naive `startsWith(root)`.
+//
+// Relative paths are resolved against the export root rather than rejected —
+// the model naturally writes `path="TSLA.csv"`, and silently resolving that
+// against the process CWD is exactly the class of bug this guard exists to
+// stop.
+
+#include "core/config/AppPaths.h"
+
+#include <QDir>
+#include <QFileInfo>
+#include <QString>
+
+namespace fincept::mcp::tools {
+
+/// The one directory model-supplied paths may touch: `<AppPaths::root()>/exports`.
+/// Created on first use so canonicalPath() below always resolves.
+inline QString export_root() {
+ const QString root = QDir(AppPaths::root()).absoluteFilePath(QStringLiteral("exports"));
+ QDir().mkpath(root);
+ const QString canonical = QDir(root).canonicalPath();
+ return canonical.isEmpty() ? QDir(root).absolutePath() : canonical;
+}
+
+struct ExportPath {
+ QString path; // absolute destination — only valid when error is empty
+ QString error; // human-readable refusal, ready to hand to ToolResult::fail
+ bool ok() const { return error.isEmpty(); }
+};
+
+/// Confine `requested` to export_root(). Relative paths are resolved against
+/// the root; absolute paths must already live inside it. The parent directory
+/// must exist — we deliberately do not mkpath() an attacker-chosen tree.
+inline ExportPath resolve_export_path(const QString& requested) {
+ ExportPath out;
+
+ const QString raw = QDir::fromNativeSeparators(requested).trimmed();
+ if (raw.isEmpty()) {
+ out.error = QStringLiteral("Missing path");
+ return out;
+ }
+
+ const QString root = export_root();
+ if (root.isEmpty()) {
+ out.error = QStringLiteral("Export directory is unavailable");
+ return out;
+ }
+
+ // Relative → anchor at the root. Absolute → take as-is and let the
+ // containment check below decide.
+ const QString absolute =
+ QFileInfo(raw).isAbsolute() ? QDir::cleanPath(raw) : QDir(root).absoluteFilePath(QDir::cleanPath(raw));
+
+ const QFileInfo fi(absolute);
+ if (fi.fileName().isEmpty()) {
+ out.error = QStringLiteral("Path must name a file, not a directory");
+ return out;
+ }
+
+ // Canonicalise the PARENT: the file itself may not exist yet, and
+ // canonicalPath() on a non-existent path returns empty. This is also what
+ // resolves `..` segments and symlinks that would otherwise escape.
+ const QString parent = QDir(fi.absolutePath()).canonicalPath();
+ if (parent.isEmpty()) {
+ out.error = QStringLiteral("Destination directory does not exist. Write inside the export directory: ") + root;
+ return out;
+ }
+
+#ifdef Q_OS_WIN
+ constexpr Qt::CaseSensitivity kCase = Qt::CaseInsensitive;
+#else
+ constexpr Qt::CaseSensitivity kCase = Qt::CaseSensitive;
+#endif
+ // Trailing '/' matters: without it `<root>_evil` is a prefix match. Qt
+ // canonical paths always use '/', including on Windows — do NOT use
+ // QDir::separator() here, it is '\\' on Windows and would never match.
+ const bool inside = parent.compare(root, kCase) == 0 ||
+ parent.startsWith(root + QLatin1Char('/'), kCase);
+ if (!inside) {
+ out.error = QStringLiteral("Path must be inside the export directory (") + root +
+ QStringLiteral("). Absolute paths elsewhere on disk are refused.");
+ return out;
+ }
+
+ out.path = QDir(parent).absoluteFilePath(fi.fileName());
+ return out;
+}
+
+} // namespace fincept::mcp::tools
diff --git a/fincept-qt/src/mcp/tools/FileManagerTools.cpp b/fincept-qt/src/mcp/tools/FileManagerTools.cpp
index 06012a4dc..ee2175dbb 100644
--- a/fincept-qt/src/mcp/tools/FileManagerTools.cpp
+++ b/fincept-qt/src/mcp/tools/FileManagerTools.cpp
@@ -3,6 +3,7 @@
#include "mcp/tools/FileManagerTools.h"
#include "core/logging/Logger.h"
+#include "mcp/tools/ExportPathGuard.h"
#include "services/file_manager/FileManagerService.h"
#include <QDateTime>
@@ -436,31 +437,45 @@ std::vector<ToolDef> get_file_manager_tools() {
{
ToolDef t;
t.name = "download_managed_file";
- t.description = "Copy a managed file from internal storage to an external path on disk.";
+ t.description = "Copy a managed file out of internal storage into the export directory. "
+ "'destination_path' is a filename (or relative path) inside that directory — "
+ "absolute paths elsewhere on disk are refused.";
t.category = "file_manager";
t.is_destructive = true;
- t.input_schema.properties =
- QJsonObject{{"id", QJsonObject{{"type", "string"}, {"description", "Managed file id"}}},
- {"destination_path",
- QJsonObject{{"type", "string"}, {"description", "Absolute output path. Parent must exist."}}}};
+ t.auth_required = AuthLevel::ExplicitConfirm;
+ t.input_schema.properties = QJsonObject{
+ {"id", QJsonObject{{"type", "string"}, {"description", "Managed file id"}}},
+ {"destination_path",
+ QJsonObject{{"type", "string"},
+ {"description", "Output filename inside the export directory, e.g. 'report.pdf'"}}}};
t.input_schema.required = {"id", "destination_path"};
t.handler = [](const QJsonObject& args) -> ToolResult {
const QString id = args["id"].toString().trimmed();
- const QString dest = args["destination_path"].toString().trimmed();
- if (id.isEmpty() || dest.isEmpty())
+ const QString requested = args["destination_path"].toString().trimmed();
+ if (id.isEmpty() || requested.isEmpty())
return ToolResult::fail("Missing 'id' or 'destination_path'");
+ // Confine before touching the filesystem. The pre-emptive
+ // QFile::remove() that used to sit here (QFile::copy refuses to
+ // overwrite) made this tool an arbitrary-delete primitive for any
+ // path the model could name — it deleted first and only then
+ // discovered the copy would fail.
+ const auto dest = resolve_export_path(requested);
+ if (!dest.ok())
+ return ToolResult::fail(dest.error);
+
auto& svc = services::FileManagerService::instance();
auto f = svc.find_by_id(id);
if (f.id.isEmpty())
return ToolResult::fail("File not found: " + id);
const QString src = svc.full_path(f.name);
- QFile::remove(dest);
- if (!QFile::copy(src, dest))
- return ToolResult::fail("Copy failed");
+ if (src.isEmpty())
+ return ToolResult::fail("Managed file has no readable path: " + id);
+ if (!QFile::copy(src, dest.path))
+ return ToolResult::fail("Copy failed — a file already exists at that name, or it is not writable");
return ToolResult::ok("File downloaded", QJsonObject{
{"id", id},
- {"destination_path", dest},
+ {"destination_path", dest.path},
{"size", f.size},
});
};
diff --git a/fincept-qt/src/mcp/tools/LiveTradingTools.cpp b/fincept-qt/src/mcp/tools/LiveTradingTools.cpp
index c22f1c39c..0b110ede4 100644
--- a/fincept-qt/src/mcp/tools/LiveTradingTools.cpp
+++ b/fincept-qt/src/mcp/tools/LiveTradingTools.cpp
@@ -158,7 +158,14 @@ std::vector<ToolDef> get_live_trading_tools() {
"order_type MARKET/LIMIT/SL/SL-M; product MIS/CNC/NRML. "
"Requires confirmation.";
t.category = "live-trading";
- t.auth_required = AuthLevel::Authenticated;
+ // ExplicitConfirm, not Authenticated: Authenticated (1) sits below
+ // Verified (2), so check_authorization()'s fail-closed branch never
+ // fired and the description's "Requires confirmation" enforced nothing.
+ // The only backstop was ActionCenter::should_queue, which returns true
+ // only for SemiAuto accounts — and accounts default to Auto. Prompt
+ // injection reaching the tool loop through news/EDGAR/forum text could
+ // therefore place real broker orders unattended.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.is_destructive = true;
t.input_schema = ToolSchemaBuilder()
.string("account_id", "Broker account ID (optional if exactly one active account)")
@@ -242,7 +249,14 @@ std::vector<ToolDef> get_live_trading_tools() {
"position_size (positive=long, negative=short, 0=flatten) "
"and places the delta order. Requires confirmation.";
t.category = "live-trading";
- t.auth_required = AuthLevel::Authenticated;
+ // ExplicitConfirm, not Authenticated: Authenticated (1) sits below
+ // Verified (2), so check_authorization()'s fail-closed branch never
+ // fired and the description's "Requires confirmation" enforced nothing.
+ // The only backstop was ActionCenter::should_queue, which returns true
+ // only for SemiAuto accounts — and accounts default to Auto. Prompt
+ // injection reaching the tool loop through news/EDGAR/forum text could
+ // therefore place real broker orders unattended.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.is_destructive = true;
t.input_schema = ToolSchemaBuilder()
.string("account_id", "Broker account ID (optional if exactly one active account)")
@@ -320,7 +334,14 @@ std::vector<ToolDef> get_live_trading_tools() {
t.name = "live_cancel_order";
t.description = "Cancel a single open LIVE order by order_id. Requires confirmation.";
t.category = "live-trading";
- t.auth_required = AuthLevel::Authenticated;
+ // ExplicitConfirm, not Authenticated: Authenticated (1) sits below
+ // Verified (2), so check_authorization()'s fail-closed branch never
+ // fired and the description's "Requires confirmation" enforced nothing.
+ // The only backstop was ActionCenter::should_queue, which returns true
+ // only for SemiAuto accounts — and accounts default to Auto. Prompt
+ // injection reaching the tool loop through news/EDGAR/forum text could
+ // therefore place real broker orders unattended.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.is_destructive = true;
t.input_schema = ToolSchemaBuilder()
.string("account_id", "Broker account ID (optional if exactly one active account)")
@@ -354,7 +375,14 @@ std::vector<ToolDef> get_live_trading_tools() {
t.name = "live_cancel_all_orders";
t.description = "Cancel ALL open LIVE orders for an account. Requires confirmation.";
t.category = "live-trading";
- t.auth_required = AuthLevel::Authenticated;
+ // ExplicitConfirm, not Authenticated: Authenticated (1) sits below
+ // Verified (2), so check_authorization()'s fail-closed branch never
+ // fired and the description's "Requires confirmation" enforced nothing.
+ // The only backstop was ActionCenter::should_queue, which returns true
+ // only for SemiAuto accounts — and accounts default to Auto. Prompt
+ // injection reaching the tool loop through news/EDGAR/forum text could
+ // therefore place real broker orders unattended.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.is_destructive = true;
t.input_schema = ToolSchemaBuilder()
.string("account_id", "Broker account ID (optional if exactly one active account)")
@@ -397,7 +425,14 @@ std::vector<ToolDef> get_live_trading_tools() {
t.description = "Close a single LIVE position by symbol/exchange (places a "
"market counter-order). Requires confirmation.";
t.category = "live-trading";
- t.auth_required = AuthLevel::Authenticated;
+ // ExplicitConfirm, not Authenticated: Authenticated (1) sits below
+ // Verified (2), so check_authorization()'s fail-closed branch never
+ // fired and the description's "Requires confirmation" enforced nothing.
+ // The only backstop was ActionCenter::should_queue, which returns true
+ // only for SemiAuto accounts — and accounts default to Auto. Prompt
+ // injection reaching the tool loop through news/EDGAR/forum text could
+ // therefore place real broker orders unattended.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.is_destructive = true;
t.input_schema = ToolSchemaBuilder()
.string("account_id", "Broker account ID (optional if exactly one active account)")
@@ -440,7 +475,14 @@ std::vector<ToolDef> get_live_trading_tools() {
t.description = "Square off ALL open LIVE positions for an account (market "
"counter-orders). Requires confirmation.";
t.category = "live-trading";
- t.auth_required = AuthLevel::Authenticated;
+ // ExplicitConfirm, not Authenticated: Authenticated (1) sits below
+ // Verified (2), so check_authorization()'s fail-closed branch never
+ // fired and the description's "Requires confirmation" enforced nothing.
+ // The only backstop was ActionCenter::should_queue, which returns true
+ // only for SemiAuto accounts — and accounts default to Auto. Prompt
+ // injection reaching the tool loop through news/EDGAR/forum text could
+ // therefore place real broker orders unattended.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.is_destructive = true;
t.input_schema = ToolSchemaBuilder()
.string("account_id", "Broker account ID (optional if exactly one active account)")
diff --git a/fincept-qt/src/mcp/tools/ProfileTools.cpp b/fincept-qt/src/mcp/tools/ProfileTools.cpp
index 4a2e2a720..3e90aeff9 100644
--- a/fincept-qt/src/mcp/tools/ProfileTools.cpp
+++ b/fincept-qt/src/mcp/tools/ProfileTools.cpp
@@ -128,8 +128,15 @@ std::vector<ToolDef> get_profile_tools() {
{
ToolDef t;
t.name = "profile_get_api_key";
- t.description = "Get the current user's API key from the active session.";
+ t.description = "Get the current user's API key from the active session. Returns live key material — "
+ "requires explicit user confirmation.";
t.category = "profile";
+ // Reading a secret is not "destructive" under the current model, so
+ // nothing gated this: it returned the session API key verbatim to
+ // whatever was driving the tool loop, including a remote agent acting
+ // on prompt-injected instructions. ExplicitConfirm is the only level
+ // that fails closed without a checker installed.
+ t.auth_required = AuthLevel::ExplicitConfirm;
t.input_schema.properties = QJsonObject{};
t.handler = [](const QJsonObject&) -> ToolResult {
const auto& sess = AuthManager::instance().session();
diff --git a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp
index 1aca803dc..1b4fccec8 100644
--- a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp
+++ b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp
@@ -17,6 +17,7 @@
#include "core/events/EventBus.h"
#include "core/logging/Logger.h"
#include "core/report/ReportDocument.h"
+#include "mcp/tools/ExportPathGuard.h"
#include "screens/report_builder/ReportBuilderScreen.h"
#include "services/llm/LlmRequestPolicy.h"
#include "services/report_builder/ReportBuilderService.h"
@@ -90,11 +91,25 @@ QString link_key_for(const QString& chat_id) {
return QStringLiteral("chat_report_link:") + chat_id;
}
-QString get_linked_report_for(const QString& chat_id) {
+/// Reads the chat→report link. `ok` distinguishes "no link" (true, empty
+/// string) from "unknown because the settings read failed" (false) — the two
+/// must never be collapsed: an error read as "no link" makes on_llm_mutation_start()
+/// re-link the chat and overwrite the report the chat was already editing.
+QString get_linked_report_for(const QString& chat_id, bool* ok = nullptr) {
+ if (ok)
+ *ok = true;
if (chat_id.isEmpty())
return {};
auto r = SettingsRepository::instance().get(link_key_for(chat_id));
- return r.is_ok() ? r.value() : QString{};
+ if (r.is_err()) {
+ LOG_ERROR(RB_TOOLS_TAG, QString("settings read failed for '%1' — treating the chat→report link as unknown "
+ "and leaving it untouched: %2")
+ .arg(link_key_for(chat_id), QString::fromStdString(r.error())));
+ if (ok)
+ *ok = false;
+ return {};
+ }
+ return r.value();
}
void set_linked_report_for(const QString& chat_id, const QString& path_or_placeholder) {
@@ -117,8 +132,11 @@ void on_llm_mutation_start() {
const QString chat_id = fincept::ai_chat::detail::t_chat_session_id;
if (chat_id.isEmpty())
return;
- if (!get_linked_report_for(chat_id).isEmpty())
+ bool link_known = false;
+ if (!get_linked_report_for(chat_id, &link_known).isEmpty())
return; // already linked
+ if (!link_known)
+ return; // read failed — unknown, do not modify the stored link
QString current;
QMetaObject::invokeMethod(svc, [svc, &current]() { current = svc->current_file(); }, Qt::BlockingQueuedConnection);
set_linked_report_for(chat_id, current.isEmpty() ? QStringLiteral("<unsaved>") : current);
@@ -747,19 +765,24 @@ std::vector<ToolDef> get_report_builder_tools() {
{
ToolDef t;
t.name = "report_export_pdf";
- t.description = "Export the current report to a PDF at the given absolute path. The Report Builder "
+ t.description = "Export the current report to a PDF inside the export directory. The Report Builder "
"screen must be loaded (any prior mutation auto-navigates to it, so this normally just "
- "works). Uses A4, with headers/footers if metadata defines them.";
+ "works). Uses A4, with headers/footers if metadata defines them. 'path' is a filename "
+ "or relative path inside the export directory; absolute paths elsewhere are refused.";
t.category = "report-builder";
+ t.is_destructive = true; // writes a file to disk
t.input_schema.properties = QJsonObject{
- {"path",
- QJsonObject{{"type", "string"}, {"description", "Absolute output path, e.g. /Users/x/Desktop/TSLA.pdf"}}},
+ {"path", QJsonObject{{"type", "string"},
+ {"description", "Output filename inside the export directory, e.g. 'TSLA.pdf'"}}},
};
t.input_schema.required = {"path"};
t.handler = [](const QJsonObject& args) -> ToolResult {
- QString path = args.value("path").toString().trimmed();
- if (path.isEmpty())
- return ToolResult::fail("Missing 'path'");
+ // `path` was raw model text handed to QPdfWriter — arbitrary write.
+ // Confine it to the export directory. See ExportPathGuard.h.
+ const auto dest = resolve_export_path(args.value("path").toString());
+ if (!dest.ok())
+ return ToolResult::fail(dest.error);
+ const QString path = dest.path;
// Make sure the screen exists — nav.switch_screen lazy-constructs it.
maybe_request_navigation();
@@ -856,7 +879,8 @@ std::vector<ToolDef> get_report_builder_tools() {
t.input_schema.properties = QJsonObject{};
t.handler = [](const QJsonObject&) -> ToolResult {
const QString chat_id = fincept::ai_chat::detail::t_chat_session_id;
- const QString linked = get_linked_report_for(chat_id);
+ bool link_known = false;
+ const QString linked = get_linked_report_for(chat_id, &link_known);
auto& svc = Service::instance();
int n = static_cast<int>(svc.components().size());
QString cur = svc.current_file();
@@ -868,15 +892,26 @@ std::vector<ToolDef> get_report_builder_tools() {
{"component_count", n},
{"title", title.isEmpty() ? QJsonValue::Null : QJsonValue(title)},
};
+ // A failed read must not read as "null == new chat": that is the
+ // documented cue for the model to call report_clear, which would
+ // wipe the canvas this chat was already editing.
+ if (!link_known)
+ data["link_unknown"] = true;
QString msg =
chat_id.isEmpty()
? QStringLiteral("No chat session bound; canvas has %1 components").arg(n)
- : (linked.isEmpty()
- ? QStringLiteral("New chat — canvas has %1 components from a prior session").arg(n)
- : QStringLiteral("Chat is editing %1 (canvas has %2 components)")
- .arg(linked == QLatin1String("<unsaved>") ? QStringLiteral("an unsaved report")
- : linked)
- .arg(n));
+ : (!link_known
+ ? QStringLiteral("Chat→report link could not be read (settings error) — treat it as "
+ "UNKNOWN, keep editing the canvas as-is and do NOT call report_clear. "
+ "Canvas has %1 components")
+ .arg(n)
+ : (linked.isEmpty()
+ ? QStringLiteral("New chat — canvas has %1 components from a prior session").arg(n)
+ : QStringLiteral("Chat is editing %1 (canvas has %2 components)")
+ .arg(linked == QLatin1String("<unsaved>")
+ ? QStringLiteral("an unsaved report")
+ : linked)
+ .arg(n)));
return ToolResult::ok(msg, data);
};
tools.push_back(std::move(t));
diff --git a/fincept-qt/src/mcp/tools/ThreadHelper.h b/fincept-qt/src/mcp/tools/ThreadHelper.h
index 686726c15..347c298a5 100644
--- a/fincept-qt/src/mcp/tools/ThreadHelper.h
+++ b/fincept-qt/src/mcp/tools/ThreadHelper.h
@@ -16,12 +16,16 @@
// helpers consolidate that pattern so each tool file doesn't re-implement
// it (poorly).
+#include "core/logging/Logger.h"
+
+#include <QDeadlineTimer>
#include <QEventLoop>
#include <QMetaObject>
#include <QMutex>
#include <QObject>
#include <QPointer>
#include <QThread>
+#include <QTimer>
#include <QWaitCondition>
#include <functional>
@@ -144,8 +148,24 @@ void run_async_callback_sync(QObject* target, Start&& start, OnDone&& on_done, i
// This is the pattern actually used by the existing fixed code in
// NewsTools::fetch_articles_sync. We just generalize it so each tool file
// doesn't re-roll its own QMutex/QWaitCondition.
+//
+// TIMEOUT (both paths). `signal_done` only ever fires from inside the service
+// callback, so any service that drops its callback on an error branch wedged
+// the waiter forever: the cross-thread path sat in an unbounded
+// `cv.wait(&m)`, the same-thread path in an unbounded `loop.exec()`. With 20+
+// call sites that is a permanent worker-thread leak or a frozen UI. Both paths
+// are now bounded and log an error on expiry, so a dropped callback degrades
+// to an error instead of a hang.
+//
+// Residual hazard, deliberately accepted: callers write results into their own
+// stack via a `[&]` capture inside `start`. If the callback arrives AFTER the
+// timeout, that write lands on an unwound frame. The bound is set high enough
+// (120 s) that only a genuinely dropped callback trips it, and an unbounded
+// hang is the worse failure. Do not lower it without auditing the call sites.
+inline constexpr int kAsyncWaitTimeoutMs = 120000;
+
template <typename Start>
-void run_async_wait(QObject* target, Start&& start) {
+void run_async_wait(QObject* target, Start&& start, int timeout_ms = kAsyncWaitTimeoutMs) {
struct Wait {
QMutex m;
QWaitCondition cv;
@@ -181,10 +201,19 @@ void run_async_wait(QObject* target, Start&& start) {
QMutexLocker lock(&w->m);
already_done = w->done; // start() may have resolved synchronously
}
- if (!already_done)
+ if (!already_done) {
+ // Bound the nested loop. The timer is parented to `loop` so it dies
+ // with it; quit() on an already-quit loop is harmless.
+ if (timeout_ms > 0)
+ QTimer::singleShot(timeout_ms, &loop, &QEventLoop::quit);
loop.exec(QEventLoop::ExcludeUserInputEvents);
+ }
QMutexLocker lock(&w->m);
w->loop = nullptr;
+ if (!w->done)
+ LOG_ERROR("ThreadHelper", QString("run_async_wait timed out after %1 ms (same-thread path) — the service "
+ "never invoked its callback. Result is unset.")
+ .arg(timeout_ms));
return;
}
@@ -193,6 +222,19 @@ void run_async_wait(QObject* target, Start&& start) {
Qt::QueuedConnection);
QMutexLocker lock(&w->m);
+ if (timeout_ms > 0) {
+ // QDeadlineTimer so repeated spurious wakeups can't extend the total
+ // wait past the budget — a plain `wait(&m, timeout)` in a while loop
+ // restarts the clock on every wakeup.
+ QDeadlineTimer deadline(timeout_ms);
+ while (!w->done && !deadline.hasExpired())
+ w->cv.wait(&w->m, deadline);
+ if (!w->done)
+ LOG_ERROR("ThreadHelper", QString("run_async_wait timed out after %1 ms (cross-thread path) — the service "
+ "never invoked its callback. Result is unset.")
+ .arg(timeout_ms));
+ return;
+ }
while (!w->done)
w->cv.wait(&w->m);
}
diff --git a/fincept-qt/src/mcp/tools/WorkspaceTools_LayoutsSnapshots.cpp b/fincept-qt/src/mcp/tools/WorkspaceTools_LayoutsSnapshots.cpp
index 0e6a5d63c..fa6f40670 100644
--- a/fincept-qt/src/mcp/tools/WorkspaceTools_LayoutsSnapshots.cpp
+++ b/fincept-qt/src/mcp/tools/WorkspaceTools_LayoutsSnapshots.cpp
@@ -26,6 +26,7 @@
#include "core/window/WindowRegistry.h"
#include "mcp/AsyncDispatch.h"
#include "mcp/ToolSchemaBuilder.h"
+#include "mcp/tools/ExportPathGuard.h"
#include "mcp/tools/WorkspaceTools.h"
#include "mcp/tools/WorkspaceTools_internal.h"
#include "storage/workspace/CrashRecovery.h"
@@ -251,7 +252,9 @@ void workspace_internal::register_layout_snapshot_tools(std::vector<ToolDef>& to
{
ToolDef t;
t.name = "export_layout";
- t.description = "Export a saved workspace to a JSON file path.";
+ t.description = "Export a saved workspace to a JSON file inside the export directory. "
+ "'path' is a filename or relative path inside that directory; absolute paths "
+ "elsewhere on disk are refused.";
t.category = "workspace";
t.is_destructive = true;
t.default_timeout_ms = kDefaultTimeoutMs;
@@ -259,19 +262,26 @@ void workspace_internal::register_layout_snapshot_tools(std::vector<ToolDef>& to
.string("id", "Layout UUID")
.required()
.length(1, 64)
- .string("path", "Output file path (.json)")
+ .string("path", "Output filename inside the export directory (.json)")
.required()
.length(1, 1024)
.build();
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
+ // `path` is raw model text — confine it before LayoutCatalog
+ // opens it for writing. See ExportPathGuard.h.
+ const auto dest = resolve_export_path(args["path"].toString());
+ if (!dest.ok()) {
+ resolve(ToolResult::fail(dest.error));
+ return;
+ }
const LayoutId id = LayoutId::from_string(args["id"].toString());
- auto r = LayoutCatalog::instance().export_to(id, args["path"].toString());
+ auto r = LayoutCatalog::instance().export_to(id, dest.path);
if (r.is_err()) {
resolve(ToolResult::fail(QString::fromStdString(r.error())));
return;
}
- resolve(ToolResult::ok("Layout exported", QJsonObject{{"path", args["path"].toString()}}));
+ resolve(ToolResult::ok("Layout exported", QJsonObject{{"path", dest.path}}));
});
};
tools.push_back(std::move(t));
@@ -280,15 +290,27 @@ void workspace_internal::register_layout_snapshot_tools(std::vector<ToolDef>& to
{
ToolDef t;
t.name = "import_layout";
- t.description = "Import a workspace JSON file as a new layout.";
+ t.description = "Import a workspace JSON file from the export directory as a new layout. "
+ "'path' is a filename or relative path inside that directory; absolute paths "
+ "elsewhere on disk are refused.";
t.category = "workspace";
t.is_destructive = true;
t.default_timeout_ms = kDefaultTimeoutMs;
- t.input_schema =
- ToolSchemaBuilder().string("path", "Input file path (.json)").required().length(1, 1024).build();
+ t.input_schema = ToolSchemaBuilder()
+ .string("path", "Input filename inside the export directory (.json)")
+ .required()
+ .length(1, 1024)
+ .build();
t.async_handler = [](const QJsonObject& args, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise) {
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
- auto r = LayoutCatalog::instance().import_from(args["path"].toString());
+ // Reads are confined too: an unconfined read path lets the model
+ // pull any JSON on disk into a layout it can then export back out.
+ const auto src = resolve_export_path(args["path"].toString());
+ if (!src.ok()) {
+ resolve(ToolResult::fail(src.error));
+ return;
+ }
+ auto r = LayoutCatalog::instance().import_from(src.path);
if (r.is_err()) {
resolve(ToolResult::fail(QString::fromStdString(r.error())));
return;
diff --git a/fincept-qt/src/mcp/tools/WorkspaceTools_MonitorsWindows.cpp b/fincept-qt/src/mcp/tools/WorkspaceTools_MonitorsWindows.cpp
index 4737ad608..bdf2cb118 100644
--- a/fincept-qt/src/mcp/tools/WorkspaceTools_MonitorsWindows.cpp
+++ b/fincept-qt/src/mcp/tools/WorkspaceTools_MonitorsWindows.cpp
@@ -177,6 +177,17 @@ void workspace_internal::register_monitor_window_tools(std::vector<ToolDef>& too
run_on_ui(std::move(ctx), promise, [args](auto resolve) {
const int monitor_idx = args["monitor_index"].toInt(-1);
auto* frame = new WindowFrame(WindowFrame::next_window_id(), nullptr);
+ // Every other creation site sets this (WindowFrame.cpp,
+ // WindowCycler.cpp, StressLoad.cpp). WindowFrame unregisters
+ // from WindowRegistry only via `connect(this,
+ // &QObject::destroyed, ...)`, so without it a closed frame
+ // lingers as a live QPointer in the registry: all_minimised()
+ // reads isMinimized()==false on the hidden zombie and
+ // lock-on-minimise never fires again, focus_window_by_index()
+ // showNormal()s a closed window back to life, and
+ // close_window's `frame_count() <= 1` guard counts zombies so
+ // the last real window becomes closeable.
+ frame->setAttribute(Qt::WA_DeleteOnClose);
if (monitor_idx >= 0) {
if (auto* s = screen_by_index(monitor_idx)) {
frame->move_to_screen(s);
diff --git a/fincept-qt/src/network/cloud/CloudClient.cpp b/fincept-qt/src/network/cloud/CloudClient.cpp
index a5f75c08a..fc8f2a59f 100644
--- a/fincept-qt/src/network/cloud/CloudClient.cpp
+++ b/fincept-qt/src/network/cloud/CloudClient.cpp
@@ -6,6 +6,8 @@
#include <QNetworkReply>
#include <QUrl>
+#include <chrono>
+
namespace fincept::cloud {
CloudClient& CloudClient::instance() {
@@ -15,6 +17,10 @@ CloudClient& CloudClient::instance() {
CloudClient::CloudClient() {
nam_ = new QNetworkAccessManager(this);
+ // Qt disables the transfer timeout by default: a half-open TCP connection
+ // never emits finished(), so the callback never runs and there is no cancel
+ // path — the only recovery is restarting the app. Matches HttpClient.
+ nam_->setTransferTimeout(std::chrono::seconds{20});
}
void CloudClient::set_credentials(const QString& api_key, const QString& session_token) {
@@ -45,6 +51,12 @@ QNetworkRequest CloudClient::build_request(const QString& endpoint) const {
void CloudClient::finish(QNetworkReply* reply, Callback cb, const QObject* context) {
const QObject* receiver = context ? context : static_cast<const QObject*>(this);
+ // Safety net: guarantee the reply is always deleted. If `context` is
+ // destroyed before the reply finishes, Qt auto-disconnects the callback
+ // lambda below and its reply->deleteLater() would never run → the reply
+ // leaks until app exit. deleteLater() is idempotent, so a double-call when
+ // the lambda also runs is harmless. (Same fix as HttpClient::handle_reply.)
+ connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater);
connect(reply, &QNetworkReply::finished, receiver, [reply, cb = std::move(cb)]() {
reply->deleteLater();
diff --git a/fincept-qt/src/network/http/HttpClient.cpp b/fincept-qt/src/network/http/HttpClient.cpp
index e2c0a1768..6a56ca866 100644
--- a/fincept-qt/src/network/http/HttpClient.cpp
+++ b/fincept-qt/src/network/http/HttpClient.cpp
@@ -2,10 +2,111 @@
#include "core/logging/Logger.h"
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QStringList>
#include <QUrl>
+#include <chrono>
+
namespace fincept {
+namespace {
+/// URL with the query string removed, for logging.
+///
+/// Several callers put a live secret in the query because HttpClient's auth
+/// headers are shared/global and cannot be set per request — Opsgenie
+/// (`?apiKey=`), Gotify (`?token=`), ntfy (`?auth=`), and any saved data
+/// mapping whose template carries `&apikey=`/`&token=`. Logging the raw URL
+/// therefore writes those secrets to fincept.log in plaintext at the default
+/// log level. The error path in handle_reply() already strips the query for
+/// exactly this reason; the request path must do the same. Fixed here, once,
+/// rather than at each call site.
+QString log_url(const QString& url) {
+ const QUrl parsed(url);
+ if (!parsed.hasQuery())
+ return url;
+ return parsed.adjusted(QUrl::RemoveQuery).toString() + QStringLiteral("?<redacted>");
+}
+
+/// Error text for a failed response: `"HTTP_<status>: <server message>"`, or a
+/// bare `"HTTP_<status>"` when the body carries nothing usable. Keeping the
+/// status as a machine-readable prefix lets AuthApi/UserApi keep switching on
+/// it (see HttpClient::status_from_error) while the server's own wording still
+/// reaches the user.
+///
+/// Body shapes seen in practice: the Fincept backend sends `{"error": ...}` or
+/// `{"message": ...}`; FastAPI sends `{"detail": "..."}` and, for request
+/// validation, `{"detail": [{"loc": [...], "msg": "..."}]}`; third-party
+/// webhooks send whatever they like.
+std::string server_message(const QJsonDocument& doc, int status) {
+ const QString prefix = QStringLiteral("HTTP_%1").arg(status);
+ if (!doc.isObject())
+ return prefix.toStdString();
+
+ const QJsonObject obj = doc.object();
+ QString msg;
+ for (const auto* key : {"error", "message", "detail"}) {
+ const QJsonValue v = obj.value(QLatin1String(key));
+ if (!v.isString())
+ continue;
+ msg = v.toString().trimmed();
+ if (!msg.isEmpty())
+ break;
+ }
+
+ // Pydantic/FastAPI field-level validation errors (typically 422).
+ if (msg.isEmpty() && obj.value(QLatin1String("detail")).isArray()) {
+ QStringList parts;
+ for (const auto& item : obj.value(QLatin1String("detail")).toArray()) {
+ const QJsonObject entry = item.toObject();
+ const QString m = entry.value(QLatin1String("msg")).toString().trimmed();
+ if (m.isEmpty())
+ continue;
+ // loc is ["body", "field_name"] — take the last meaningful segment.
+ QString field;
+ const QJsonArray loc = entry.value(QLatin1String("loc")).toArray();
+ for (qsizetype i = loc.size() - 1; i >= 0; --i) {
+ QString seg = loc.at(i).toString();
+ if (seg.isEmpty() || seg == QLatin1String("body"))
+ continue;
+ seg[0] = seg[0].toUpper();
+ seg.replace('_', ' ');
+ field = seg;
+ break;
+ }
+ parts << (field.isEmpty() ? m : field + QStringLiteral(": ") + m);
+ }
+ msg = parts.join(QStringLiteral("; "));
+ }
+
+ if (msg.isEmpty())
+ return prefix.toStdString();
+ return (prefix + QStringLiteral(": ") + msg).toStdString();
+}
+} // namespace
+
+int HttpClient::status_from_error(const std::string& error) {
+ const QString e = QString::fromStdString(error);
+ if (!e.startsWith(QLatin1String("HTTP_")))
+ return 0;
+ const qsizetype colon = e.indexOf(QLatin1Char(':'), 5);
+ const QString digits = (colon < 0) ? e.mid(5) : e.mid(5, colon - 5);
+ bool ok = false;
+ const int status = digits.toInt(&ok);
+ return ok ? status : 0;
+}
+
+QString HttpClient::message_from_error(const std::string& error) {
+ const QString e = QString::fromStdString(error);
+ if (!e.startsWith(QLatin1String("HTTP_")))
+ return e; // transport / JSON-parse failures carry their own text
+ const qsizetype colon = e.indexOf(QLatin1Char(':'), 5);
+ if (colon < 0)
+ return {};
+ return e.mid(colon + 1).trimmed();
+}
+
HttpClient& HttpClient::instance() {
static HttpClient s;
return s;
@@ -13,9 +114,14 @@ HttpClient& HttpClient::instance() {
HttpClient::HttpClient() {
nam_ = new QNetworkAccessManager(this);
+ // Qt disables the transfer timeout by default: a half-open TCP connection
+ // never emits finished(), so the callback never runs, nothing is logged and
+ // there is no cancel path — the only recovery is restarting the app. Every
+ // other network site in this codebase sets one (BrokerHttp, NewsService, …).
+ nam_->setTransferTimeout(std::chrono::seconds{20});
}
-QNetworkRequest HttpClient::build_request(const QString& url) const {
+QNetworkRequest HttpClient::build_request(const QString& url, const Headers& extra_headers) const {
const bool is_relative = !url.startsWith("http");
const QString full_url = is_relative ? (base_url_ + url) : url;
QUrl qurl(full_url);
@@ -38,6 +144,11 @@ QNetworkRequest HttpClient::build_request(const QString& url) const {
req.setRawHeader("X-Session-Token", session_token_.toUtf8());
}
}
+
+ // Applied last so a caller can override any default above for this one
+ // request without touching the shared singleton's auth state.
+ for (auto it = extra_headers.constBegin(); it != extra_headers.constEnd(); ++it)
+ req.setRawHeader(it.key(), it.value());
return req;
}
@@ -65,19 +176,23 @@ void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback, const
LOG_WARN("HTTP",
QString("HTTP %1: %2 — %3").arg(status).arg(sanitized.toString()).arg(reply->errorString()));
- // 401/403 must always be err() — session-expiry detection in AuthApi/SessionGuard depends on it.
+ // 401/403 stay a bare "HTTP_<status>" — session-expiry detection in
+ // AuthApi/AuthManager/SessionGuard matches on exactly that string.
if (status == 401 || status == 403) {
cb(Result<QJsonDocument>::err(QString("HTTP_%1").arg(status).toStdString()));
return;
}
- // Pass through parseable JSON bodies so AuthApi can extract server error messages.
- if (!data.isEmpty() && parse_err.error == QJsonParseError::NoError && doc.isObject()) {
- cb(Result<QJsonDocument>::ok(doc));
- return;
- }
-
- cb(Result<QJsonDocument>::err(QString("HTTP_%1").arg(status).toStdString()));
+ // Every other HTTP error is an error, including one whose body
+ // happens to parse. This used to return ok(doc) so AuthApi could
+ // read the server's message off the document — but ~50 other call
+ // sites share this client and were told a 400/404/429/500/502/503
+ // had succeeded, then parsed the error body as data (DBnomics
+ // reported "0 series found" for a 429; MaritimeService cached an
+ // empty vessel for 60s). The message is preserved in the error
+ // string instead — see server_message() / message_from_error().
+ const bool parsed = !data.isEmpty() && parse_err.error == QJsonParseError::NoError;
+ cb(Result<QJsonDocument>::err(server_message(parsed ? doc : QJsonDocument{}, status)));
return;
}
@@ -89,36 +204,40 @@ void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback, const
});
}
-void HttpClient::get(const QString& url, JsonCallback callback, const QObject* context) {
- LOG_DEBUG("HTTP", "GET " + url);
- auto* reply = nam_->get(build_request(url));
+void HttpClient::get(const QString& url, JsonCallback callback, const QObject* context, const Headers& extra_headers) {
+ LOG_DEBUG("HTTP", "GET " + log_url(url));
+ auto* reply = nam_->get(build_request(url, extra_headers));
handle_reply(reply, std::move(callback), context);
}
-void HttpClient::post(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context) {
- LOG_DEBUG("HTTP", "POST " + url);
+void HttpClient::post(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context,
+ const Headers& extra_headers) {
+ LOG_DEBUG("HTTP", "POST " + log_url(url));
QJsonDocument doc(body);
- auto* reply = nam_->post(build_request(url), doc.toJson());
+ auto* reply = nam_->post(build_request(url, extra_headers), doc.toJson());
handle_reply(reply, std::move(callback), context);
}
-void HttpClient::put(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context) {
- LOG_DEBUG("HTTP", "PUT " + url);
+void HttpClient::put(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context,
+ const Headers& extra_headers) {
+ LOG_DEBUG("HTTP", "PUT " + log_url(url));
QJsonDocument doc(body);
- auto* reply = nam_->put(build_request(url), doc.toJson());
+ auto* reply = nam_->put(build_request(url, extra_headers), doc.toJson());
handle_reply(reply, std::move(callback), context);
}
-void HttpClient::del(const QString& url, JsonCallback callback, const QObject* context) {
- LOG_DEBUG("HTTP", "DELETE " + url);
- auto* reply = nam_->deleteResource(build_request(url));
+void HttpClient::del(const QString& url, JsonCallback callback, const QObject* context, const Headers& extra_headers) {
+ LOG_DEBUG("HTTP", "DELETE " + log_url(url));
+ auto* reply = nam_->deleteResource(build_request(url, extra_headers));
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);
+void HttpClient::del(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context,
+ const Headers& extra_headers) {
+ LOG_DEBUG("HTTP", "DELETE " + log_url(url));
QJsonDocument doc(body);
- auto* reply = nam_->sendCustomRequest(build_request(url), "DELETE", doc.toJson(QJsonDocument::Compact));
+ auto* reply =
+ nam_->sendCustomRequest(build_request(url, extra_headers), "DELETE", doc.toJson(QJsonDocument::Compact));
handle_reply(reply, std::move(callback), context);
}
diff --git a/fincept-qt/src/network/http/HttpClient.h b/fincept-qt/src/network/http/HttpClient.h
index ddea92661..8fc43c742 100644
--- a/fincept-qt/src/network/http/HttpClient.h
+++ b/fincept-qt/src/network/http/HttpClient.h
@@ -1,14 +1,18 @@
#pragma once
#include "core/result/Result.h"
+#include <QByteArray>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QMap>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QObject>
+#include <QString>
#include <functional>
+#include <string>
namespace fincept {
@@ -20,13 +24,34 @@ class HttpClient : public QObject {
using JsonCallback = std::function<void(Result<QJsonDocument>)>;
+ /// Extra raw headers for one request, applied last so they override the
+ /// defaults set by build_request(). This is the supported way to send a
+ /// per-caller credential: this class is a process-wide singleton, so
+ /// set_auth_header()/set_session_token() leak into every other caller's
+ /// requests and must not be used to scope one call.
+ using Headers = QMap<QByteArray, QByteArray>;
+
/// `context` scopes callback lifetime — pass `this` from anything that can outlive its reply.
/// nullptr is safe only for objects whose lifetime equals the app's (singletons).
- void get(const QString& url, JsonCallback callback, const QObject* context = nullptr);
- 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 get(const QString& url, JsonCallback callback, const QObject* context = nullptr,
+ const Headers& extra_headers = {});
+ void post(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr,
+ const Headers& extra_headers = {});
+ void put(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr,
+ const Headers& extra_headers = {});
+ void del(const QString& url, JsonCallback callback, const QObject* context = nullptr,
+ const Headers& extra_headers = {});
+ void del(const QString& url, const QJsonObject& body, JsonCallback callback, const QObject* context = nullptr,
+ const Headers& extra_headers = {});
+
+ /// Error strings produced by this client are `"HTTP_<status>"` or
+ /// `"HTTP_<status>: <server message>"`. These two recover the halves —
+ /// use them instead of re-implementing the parse at each call site.
+ /// status_from_error() returns 0 for transport/parse failures (no status).
+ static int status_from_error(const std::string& error);
+ /// Server-supplied text, or empty when the response carried none.
+ /// For a non-HTTP failure (transport/JSON parse) the raw text is returned.
+ static QString message_from_error(const std::string& error);
void set_auth_header(const QString& api_key);
void set_session_token(const QString& token);
@@ -35,7 +60,7 @@ class HttpClient : public QObject {
private:
HttpClient();
- QNetworkRequest build_request(const QString& url) const;
+ QNetworkRequest build_request(const QString& url, const Headers& extra_headers = {}) const;
void handle_reply(QNetworkReply* reply, JsonCallback callback, const QObject* context);
QNetworkAccessManager* nam_ = nullptr;
diff --git a/fincept-qt/src/network/websocket/WebSocketClient.cpp b/fincept-qt/src/network/websocket/WebSocketClient.cpp
index 25becb1b5..2f6e54af7 100644
--- a/fincept-qt/src/network/websocket/WebSocketClient.cpp
+++ b/fincept-qt/src/network/websocket/WebSocketClient.cpp
@@ -14,12 +14,18 @@ namespace fincept {
namespace {
constexpr const char* kTag = "WS";
-// Mask the `token=` query value so broker access tokens (JWTs) never reach the
-// log file. Applied to every URL we log — these tokens are bearer credentials.
+// Mask credential-bearing query values so they never reach the log file.
+// Applied to every URL we log — these are all bearer credentials.
+//
+// The old pattern was `token=[^&]*` only, which missed the `api_key=` that
+// Zerodha's socket URL carries (and `auth=`, `apikey=`, `secret=`, …), so those
+// were logged verbatim. The capture group keeps the parameter name — including
+// any prefix such as `access_token=` — and replaces only its value.
QString redact_url(const QString& url) {
QString out = url;
- static const QRegularExpression re(QStringLiteral("token=[^&]*"));
- out.replace(re, QStringLiteral("token=REDACTED"));
+ static const QRegularExpression re(QStringLiteral("(api_?key|auth|token|secret|password|signature)=[^&]*"),
+ QRegularExpression::CaseInsensitiveOption);
+ out.replace(re, QStringLiteral("\\1=REDACTED"));
return out;
}
diff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cpp
index e6c834db9..d0bd64046 100644
--- a/fincept-qt/src/python/PythonRunner.cpp
+++ b/fincept-qt/src/python/PythonRunner.cpp
@@ -20,6 +20,7 @@
#include <QStandardPaths>
#include <QStringList>
#include <QThread>
+#include <QTimer>
#include <QUuid>
#include <atomic>
@@ -189,6 +190,124 @@ static void strip_unmanaged_credentials(QProcessEnvironment& env, const QStringL
}
}
+// ── Argument-spill opt-in ────────────────────────────────────────────────────
+// start_next() can replace an oversized argv entry with "@<temp-path>" to dodge
+// the Windows ~32 KB command-line limit. That only works for scripts that
+// implement the convention (read the file, delete it, use its contents). It was
+// applied unconditionally, so any *other* script handed a >8 KB payload — a
+// portfolio config from PortfolioAnalyticsService, a backtest spec from
+// BacktestingService, an option chain from OptionChainService, a Databento
+// query — received the literal string "@C:\...\fincept_arg_*.json" and failed
+// with "malformed JSON" on exactly the inputs that had grown past 8 KB.
+//
+// So spilling is opt-in: only the scripts verified below (grep `resolve_arg` /
+// `startswith("@")` under scripts/) get it.
+//
+// PREFER stdin FOR NEW LARGE PAYLOADS. PythonRunner::run() takes `stdin_data`;
+// it has no size limit, never touches disk, and is invisible to same-user
+// process inspection. New scripts should take `--stdin` rather than grow another
+// `@file` reader.
+static bool script_supports_arg_spill(const QString& script, const QStringList& args) {
+ // yfinance_data.py reads `@file` only for its batch_all action; every other
+ // action takes plain scalar args and would choke on an "@..." string.
+ if (script == QLatin1String("yfinance_data.py"))
+ return !args.isEmpty() && args[0] == QLatin1String("batch_all");
+
+ static const QStringList kSpillCapableScripts = {
+ // scripts/*.py — resolve_arg()
+ QStringLiteral("news_nlp.py"),
+ QStringLiteral("news_correlation.py"),
+ QStringLiteral("news_geolocation.py"),
+ // scripts/Analytics/options/*.py — resolve_arg(), invoked via
+ // MAAnalyticsService::run_python_json()
+ QStringLiteral("Analytics/options/gex_calculator.py"),
+ QStringLiteral("Analytics/options/iv_smile.py"),
+ QStringLiteral("Analytics/options/iv_surface.py"),
+ QStringLiteral("Analytics/options/oi_tracker.py"),
+ QStringLiteral("Analytics/options/straddle_simulator.py"),
+ QStringLiteral("Analytics/options/strategy_chart.py"),
+ // scripts/agents/finagent_core/main.py — payload_str.startswith("@").
+ // AgentService reaches it via its own stdin QProcess, not through here,
+ // but the reader exists so the flag stays correct for any other caller.
+ QStringLiteral("agents/finagent_core/main.py"),
+ };
+ return kSpillCapableScripts.contains(script);
+}
+
+// ── Watchdog budgets ─────────────────────────────────────────────────────────
+// Every spawn gets a kill-timer. Without one, a script blocked on a socket
+// holds one of the THREE concurrency slots forever; three such hangs wedge
+// every Python-backed feature in the terminal until the app is restarted, and
+// nothing is ever shown to the user because the callback simply never fires.
+//
+// This is a *floor* policy, not a per-script tuning knob: callers that know
+// better pass RunOptions::timeout_ms (see BacktestingService). The table below
+// only exists because a handful of scripts legitimately run for many minutes
+// and their callers live in files this change does not touch.
+static constexpr int kDefaultTimeoutMs = 300'000; // 5 min — ordinary fetch/analytics
+static constexpr int kLongRunTimeoutMs = 3'600'000; // 60 min — training / backtests
+
+static int default_timeout_for_script(const QString& script) {
+ // Prefix match on the script's directory. These trees train models, build
+ // FAISS indexes, run multi-year backtests or drive multi-step LLM agents —
+ // minutes is normal for them and 5 min would kill real work.
+ // vision_quant/setup_index.py — CNN training + index build
+ // ai_quant_lab/qlib_rl.py — RL training (streams progress for ages)
+ // ai_quant_lab/qlib_rolling_retraining.py
+ // Analytics/backtesting/* — full backtests / walk-forward / optimise
+ // agents/* — LLM agent chains
+ static const QStringList kLongRunPrefixes = {
+ QStringLiteral("vision_quant/"),
+ QStringLiteral("ai_quant_lab/"),
+ QStringLiteral("agents/"),
+ QStringLiteral("Analytics/backtesting/"),
+ };
+ for (const QString& p : kLongRunPrefixes) {
+ if (script.startsWith(p))
+ return kLongRunTimeoutMs;
+ }
+ return kDefaultTimeoutMs;
+}
+
+// ── Script-level error envelope ──────────────────────────────────────────────
+// Scripts across the tree print a well-formed `{"error": "..."}` (often with
+// `{"success": false}` alongside) to describe a failure. Two things went wrong
+// with that before:
+// * on exit 0 the envelope was treated as a *successful* payload, so the
+// caller got success=true with data it could not use and rendered blank;
+// * on a non-zero exit the caller surfaced `result.error`, which was stderr —
+// and stderr is empty in exactly this case, so the real diagnostic sat
+// unread in `result.output`.
+// Returns true and fills `*out` when the document carries a usable message.
+//
+// Deliberately NOT triggered by `success: false` alone: several providers emit
+// `{"success": true, "data": {...}, "error": null}`, and BacktestingService
+// already unwraps nested `success` flags itself with better messages.
+static bool extract_error_envelope(const QJsonDocument& doc, QString* out) {
+ if (!doc.isObject())
+ return false;
+ const QJsonObject obj = doc.object();
+ const QJsonValue err = obj.value(QLatin1String("error"));
+ if (err.isUndefined() || err.isNull())
+ return false; // absent, or explicitly "no error"
+
+ QString msg;
+ if (err.isString())
+ msg = err.toString();
+ else if (err.isObject())
+ msg = QString::fromUtf8(QJsonDocument(err.toObject()).toJson(QJsonDocument::Compact));
+ else if (err.isArray())
+ msg = QString::fromUtf8(QJsonDocument(err.toArray()).toJson(QJsonDocument::Compact));
+ else
+ msg = err.toVariant().toString();
+
+ msg = msg.trimmed();
+ if (msg.isEmpty() || msg == QLatin1String("{}") || msg == QLatin1String("[]"))
+ return false; // `"error": ""` / `{}` is not a failure signal
+ *out = msg;
+ return true;
+}
+
// Scripts that require NumPy 1.x environment
static const QStringList kNumpy1Scripts = {
"vectorbt", "backtesting", "gluonts", "functime", "pyportfolioopt", "financepy", "ffn", "ffn_wrapper",
@@ -425,7 +544,15 @@ QString PythonRunner::find_scripts_dir() const {
// ── Run Script ───────────────────────────────────────────────────────────────
-void PythonRunner::run(const QString& script, const QStringList& args, Callback cb, StreamCallback on_line) {
+void PythonRunner::run(const QString& script, const QStringList& args, Callback cb, StreamCallback on_line,
+ const QByteArray& stdin_data) {
+ RunOptions opts;
+ opts.stdin_data = stdin_data;
+ run_with_options(script, args, opts, std::move(cb), std::move(on_line));
+}
+
+void PythonRunner::run_with_options(const QString& script, const QStringList& args, const RunOptions& opts, Callback cb,
+ StreamCallback on_line) {
// Thread-affinity guard. PythonRunner is a QObject singleton living on
// whatever thread first called instance() — in practice the main thread,
// because main.cpp warms it at startup. But run() is invoked from
@@ -441,8 +568,9 @@ void PythonRunner::run(const QString& script, const QStringList& args, Callback
StreamCallback on_line_copy = std::move(on_line);
QMetaObject::invokeMethod(
this,
- [this, script, args, cb_copy = std::move(cb_copy), on_line_copy = std::move(on_line_copy)]() mutable {
- run(script, args, std::move(cb_copy), std::move(on_line_copy));
+ [this, script, args, opts, cb_copy = std::move(cb_copy),
+ on_line_copy = std::move(on_line_copy)]() mutable {
+ run_with_options(script, args, opts, std::move(cb_copy), std::move(on_line_copy));
},
Qt::QueuedConnection);
return;
@@ -470,8 +598,14 @@ void PythonRunner::run(const QString& script, const QStringList& args, Callback
return;
}
- // Queue the request and start if under concurrency limit
- queue_.enqueue({script, args, std::move(cb), std::move(on_line)});
+ // Queue the request and start if under concurrency limit.
+ // kTimeoutFromScript defers to the per-tree table; an explicit 0 disables the
+ // watchdog, which is why the sentinel is negative rather than 0.
+ const int resolved_timeout =
+ (opts.timeout_ms == kTimeoutFromScript) ? default_timeout_for_script(script) : opts.timeout_ms;
+
+ queue_.enqueue({script, args, std::move(cb), std::move(on_line), opts.stdin_data,
+ script_supports_arg_spill(script, args), opts.expect_json, resolved_timeout});
start_next();
}
@@ -512,7 +646,7 @@ void PythonRunner::run_code(const QString& code, Callback cb) {
file.close();
// Queue as a special request — use the temp file path directly
- queue_.enqueue({"__code__:" + temp_path, {}, std::move(cb), {}});
+ queue_.enqueue({"__code__:" + temp_path, {}, std::move(cb), {}, {}, false});
start_next();
}
@@ -592,16 +726,25 @@ void PythonRunner::start_next() {
if (!is_code) {
// Spill large args to temp files to avoid Windows 32KB command-line limit.
// Python scripts support "@/path/to/file" — they read and delete the file.
+ // OPT-IN ONLY: see script_supports_arg_spill(). Spilling for a script
+ // that can't read "@file" turns a working call into a parse error.
static constexpr int kArgSpillThreshold = 8192; // 8 KB
QStringList spilled_files;
QStringList safe_args;
for (const QString& arg : req.args) {
- if (arg.size() > kArgSpillThreshold) {
+ if (arg.size() > kArgSpillThreshold && req.supports_arg_spill) {
QString temp_dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
QString temp_path =
temp_dir + "/fincept_arg_" + QUuid::createUuid().toString(QUuid::WithoutBraces) + ".json";
QFile tf(temp_path);
if (tf.open(QIODevice::WriteOnly | QIODevice::Text)) {
+ // 0600 BEFORE the write. TempLocation is /tmp on Linux and
+ // macOS, where the default umask leaves the file 0644 —
+ // world-readable. Spilled payloads routinely carry LLM
+ // provider API keys, the Fincept session key and the MCP
+ // bridge token, so any local user could read them off disk
+ // for the lifetime of the file.
+ tf.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
tf.write(arg.toUtf8());
tf.close();
safe_args << ("@" + temp_path);
@@ -610,14 +753,25 @@ void PythonRunner::start_next() {
safe_args << arg; // fallback: pass as-is (may fail, but don't crash)
}
} else {
+ if (arg.size() > kArgSpillThreshold) {
+ // Not spillable. Windows caps the whole command line at
+ // ~32 KB, so this can still fail to start — the fix is to
+ // move the payload to run()'s `stdin_data`, not to spill.
+ LOG_WARN("Python", QString("Script %1 passed a %2 KB argument on argv (no @file support) — "
+ "move this payload to stdin")
+ .arg(req.script)
+ .arg(arg.size() / 1024));
+ }
safe_args << arg;
}
}
full_args.append(safe_args);
- // Store spilled paths so we can clean them up if the process errors out
- // (Python scripts clean them up on success via resolve_arg)
+ // Store spilled paths so BOTH the finished and errorOccurred handlers
+ // can sweep them. Scripts are supposed to delete the file in
+ // resolve_arg(), but we must not depend on that — see the comment in
+ // the finished handler.
if (!spilled_files.isEmpty()) {
- // Attach to process via dynamic property for cleanup in error handler
+ // Attach to process via dynamic property for cleanup in both handlers
proc->setProperty("spilled_files", QVariant::fromValue(spilled_files));
}
}
@@ -698,7 +852,8 @@ void PythonRunner::start_next() {
auto script_name = std::move(req.script);
connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
- [this, proc, cb, handled, script_name, is_code, temp_file](int exit_code, QProcess::ExitStatus) {
+ [this, proc, cb, handled, script_name, is_code, temp_file, expect_json = req.expect_json](
+ int exit_code, QProcess::ExitStatus) {
if (handled->exchange(true))
return; // errorOccurred already handled this proc
// Collect any remaining buffered data
@@ -713,6 +868,17 @@ void PythonRunner::start_next() {
QString stderr_str = QString::fromUtf8(bufs.stderr_buf);
proc_buffers_.remove(proc);
+
+ // Clean up any spilled arg temp files. The @file convention says
+ // the script deletes them, but that only holds when the script
+ // actually reached its resolve_arg() (it may have exited early,
+ // crashed, or been handed the file for an argument it ignores).
+ // Only errorOccurred used to sweep these, so every *successful*
+ // spilling call leaked one temp file — containing the payload —
+ // into TempLocation for the life of the machine.
+ for (const QString& f : proc->property("spilled_files").toStringList())
+ QFile::remove(f);
+
proc->deleteLater();
// Clean up temp file for inline code
@@ -729,11 +895,45 @@ void PythonRunner::start_next() {
result.output = std::move(stdout_str);
result.error = std::move(stderr_str);
} else {
- // For scripts: extract JSON from output
+ // For scripts: extract JSON from output.
+ //
+ // Success used to be `exit_code == 0 && !json_out.isEmpty()`,
+ // which laundered two distinct failures into empty success:
+ // * a script printing {"error": "rate limited"} and exiting 0
+ // * extract_json's fallback returning an UNBALANCED fragment
+ // (first bracket → EOF) that never parses
+ // Callers then saw success-with-no-rows and rendered a blank
+ // screen instead of falling back to cached data.
QString json_out = extract_json(stdout_str);
- result.success = (exit_code == 0 && !json_out.isEmpty());
- result.output = json_out.isEmpty() ? std::move(stdout_str) : std::move(json_out);
+ result.output = json_out.isEmpty() ? stdout_str : json_out;
result.error = std::move(stderr_str);
+ result.success = (exit_code == 0);
+
+ if (expect_json) {
+ QJsonParseError pe{};
+ const QJsonDocument doc = QJsonDocument::fromJson(json_out.toUtf8(), &pe);
+ const bool parsed = !json_out.isEmpty() && pe.error == QJsonParseError::NoError;
+
+ if (result.success && !parsed) {
+ result.success = false;
+ if (result.error.isEmpty()) {
+ result.error = json_out.isEmpty()
+ ? QStringLiteral("script produced no JSON payload")
+ : QStringLiteral("script produced malformed JSON: %1")
+ .arg(pe.errorString());
+ }
+ }
+
+ // A script-level {"error": ...} envelope is a failure even
+ // on exit 0 — and on a NON-zero exit it is the only useful
+ // diagnostic, because result.error is stderr and these
+ // scripts write their message to stdout. ~412 sites do this.
+ QString envelope;
+ if (parsed && extract_error_envelope(doc, &envelope)) {
+ result.success = false;
+ result.error = envelope;
+ }
+ }
}
if (!result.success && !is_code) {
@@ -778,11 +978,52 @@ void PythonRunner::start_next() {
.arg(python_exe)
.arg(script_path));
proc->start(python_exe, full_args);
- // NOTE: no runaway-kill watchdog here on purpose — several scripts run
- // legitimately for minutes (vision_quant/setup_index.py CNN training,
- // long backtests, some analytics). Reaping a hung subprocess needs a
- // per-script timeout policy (e.g. driven by ToolDef::default_timeout_ms),
- // not a blanket kill. Tracked as deferred in docs/RELEASE_BUGS_2026-07-06.md.
+
+ // Secret / large payloads arrive on stdin instead of argv. QProcess
+ // buffers the write until the channel is actually open, so this is safe
+ // immediately after start() and needs no waitForStarted() (P1).
+ //
+ // The close is GATED on non-empty stdin_data on purpose. Every existing
+ // caller passes nothing and none of them writes to the child's stdin, so
+ // leaving the channel untouched in that case keeps the streaming
+ // (on_line) and daemon-fallback paths byte-for-byte as they are. Only a
+ // caller that opts into stdin gets the EOF it is waiting for.
+ if (!req.stdin_data.isEmpty()) {
+ proc->write(req.stdin_data);
+ proc->closeWriteChannel();
+ }
+
+ // Runaway-kill watchdog.
+ //
+ // This used to be deliberately absent, on the reasoning that several
+ // scripts legitimately run for minutes. True — but the consequence was
+ // that a script blocked on a socket held one of only max_concurrent_ (3)
+ // slots FOREVER, so three hangs silently killed every Python-backed
+ // feature in the terminal until restart, with no error surfaced. The
+ // supposed cover in mcp/tools/PythonTools.cpp resolves the promise, never
+ // the QProcess, so the slot stayed occupied either way.
+ //
+ // The objection is answered by the budget being per-script-tree rather
+ // than blanket (default_timeout_for_script: 60 min for training/backtest/
+ // agent trees, 5 min otherwise), and by callers being able to override or
+ // disable it via RunOptions::timeout_ms.
+ //
+ // kill() drives the normal errorOccurred/finished path, so the slot is
+ // released and the caller gets a real failure instead of silence.
+ if (req.timeout_ms > 0) {
+ auto* watchdog = new QTimer(proc);
+ watchdog->setSingleShot(true);
+ watchdog->setInterval(req.timeout_ms);
+ const QString wd_script = req.script;
+ const int wd_budget = req.timeout_ms;
+ connect(watchdog, &QTimer::timeout, proc, [proc, wd_script, wd_budget]() {
+ if (proc->state() == QProcess::NotRunning)
+ return;
+ LOG_ERROR("Python", QString("Killing %1 — exceeded %2 ms watchdog budget").arg(wd_script).arg(wd_budget));
+ proc->kill();
+ });
+ watchdog->start();
+ }
}
}
diff --git a/fincept-qt/src/python/PythonRunner.h b/fincept-qt/src/python/PythonRunner.h
index 9d37c27e2..8c52d5ee5 100644
--- a/fincept-qt/src/python/PythonRunner.h
+++ b/fincept-qt/src/python/PythonRunner.h
@@ -30,12 +30,65 @@ class PythonRunner : public QObject {
/// `is_stderr` is true for stderr lines, false for stdout.
using StreamCallback = std::function<void(QString line, bool is_stderr)>;
+ /// Per-request policy. Every field defaults to the behaviour every existing
+ /// caller of run() already gets, so opting in is always explicit.
+ struct RunOptions {
+ /// False when the script's stdout is deliberately NOT JSON (plain text,
+ /// CSV, markdown, a bare token). With `expect_json = true` (the default)
+ /// PythonResult::success additionally requires that the extracted
+ /// payload actually PARSES as JSON and does not carry a script-level
+ /// `{"error": ...}` envelope — without that check a script that prints
+ /// `{"error": "rate limited"}` and exits 0 is laundered into an empty
+ /// success and the UI renders blank instead of falling back to cache.
+ ///
+ /// Set this per request. Do NOT re-introduce a script-name list here:
+ /// whether the output is JSON is a property of the *call*, not the file
+ /// (several scripts have both JSON and text-emitting subcommands).
+ bool expect_json = true;
+
+ /// Watchdog budget in milliseconds. On expiry the process is killed,
+ /// which drives the normal finished/errorOccurred path and frees the
+ /// concurrency slot. `0` (or negative) disables the watchdog entirely —
+ /// use only for something that genuinely has no upper bound, and
+ /// remember that three un-timed hangs wedge every Python-backed feature
+ /// until restart (max_concurrent_ is 3).
+ ///
+ /// Negative sentinel `kTimeoutFromScript` means "let PythonRunner pick
+ /// from the script path" (see default_timeout_for_script()).
+ int timeout_ms = kTimeoutFromScript;
+
+ /// Written to the child's stdin after spawn; the write channel is then
+ /// closed so the script sees EOF. See the note on run() below.
+ QByteArray stdin_data;
+ };
+
+ /// Sentinel for RunOptions::timeout_ms — resolve the budget from the script
+ /// path instead of the caller.
+ static constexpr int kTimeoutFromScript = -1;
+
static PythonRunner& instance();
/// Run a script asynchronously. Callback invoked on Qt event loop.
/// Requests are queued if max concurrency is reached.
/// Optional `on_line` delivers each complete stdout/stderr line as it arrives.
- void run(const QString& script, const QStringList& args, Callback cb, StreamCallback on_line = {});
+ ///
+ /// `stdin_data` (optional) is written to the child's stdin immediately after
+ /// spawn, and the write channel is then closed so the script sees EOF. Use
+ /// this — never argv — for anything sensitive (TOTP seeds, API keys, session
+ /// tokens) or large: argv is world-readable to same-user processes
+ /// (Win32_Process.CommandLine / /proc/<pid>/cmdline) and is capped at ~32 KB
+ /// on Windows. When `stdin_data` is empty the write channel is left exactly
+ /// as it is today (untouched), so existing callers are unaffected.
+ void run(const QString& script, const QStringList& args, Callback cb, StreamCallback on_line = {},
+ const QByteArray& stdin_data = {});
+
+ /// Same as run(), with explicit per-request policy. This is the entry point
+ /// for callers that need a non-default timeout or whose script does not emit
+ /// JSON — e.g.
+ /// run_with_options(script, args, {.expect_json = false}, cb);
+ /// run_with_options(script, args, {.timeout_ms = 30 * 60 * 1000}, cb);
+ void run_with_options(const QString& script, const QStringList& args, const RunOptions& opts, Callback cb,
+ StreamCallback on_line = {});
/// Run arbitrary Python code (for notebook/colab cells).
/// Creates a temp file, executes it, returns stdout/stderr.
@@ -86,6 +139,19 @@ class PythonRunner : public QObject {
QStringList args;
Callback cb;
StreamCallback on_line;
+ /// Written to the child's stdin after spawn; the write channel is closed
+ /// afterwards. Empty = leave stdin untouched (legacy behaviour).
+ QByteArray stdin_data;
+ /// True only for scripts that implement the `@<path>` argument-spill
+ /// convention (see script_supports_arg_spill() in PythonRunner.cpp).
+ /// Spilling a >8 KB argument for a script that does NOT implement it
+ /// hands the script the literal string "@C:\...\fincept_arg_*.json",
+ /// which it then fails to JSON-parse.
+ bool supports_arg_spill = false;
+ /// See RunOptions::expect_json.
+ bool expect_json = true;
+ /// Resolved watchdog budget in ms; 0 = no watchdog.
+ int timeout_ms = 0;
};
QQueue<QueuedRequest> queue_;
diff --git a/fincept-qt/src/python/PythonWorker.cpp b/fincept-qt/src/python/PythonWorker.cpp
index cc5a36919..c7c993231 100644
--- a/fincept-qt/src/python/PythonWorker.cpp
+++ b/fincept-qt/src/python/PythonWorker.cpp
@@ -48,6 +48,11 @@ PythonWorker::PythonWorker() {
}
});
+ sweep_timer_.setSingleShot(false);
+ sweep_timer_.setInterval(kSweepIntervalMs);
+ sweep_timer_.setTimerType(Qt::CoarseTimer);
+ connect(&sweep_timer_, &QTimer::timeout, this, &PythonWorker::sweep_deadlines);
+
connect(&PythonRunner::instance(), &PythonRunner::python_ready, this, [this]() { ensure_started(); });
connect(&PythonSetupManager::instance(), &PythonSetupManager::setup_complete, this,
@@ -85,10 +90,15 @@ void PythonWorker::submit(const QString& action, const QJsonObject& payload, Cal
p.action = action;
p.payload = payload;
p.cb = std::move(cb);
+ // Deadline starts now, not at dispatch: a request stuck behind a daemon
+ // that never comes up is just as invisible to the caller as one stuck
+ // behind a wedged Yahoo fetch.
+ p.deadline = QDeadlineTimer(kRequestTimeoutMs);
if (!ready_ || !proc_ || proc_->state() != QProcess::Running) {
// Queue until the daemon is ready (or restarted).
queue_.append({id, std::move(p)});
+ update_sweep_timer();
return;
}
@@ -97,11 +107,14 @@ void PythonWorker::submit(const QString& action, const QJsonObject& payload, Cal
req["action"] = action;
req["payload"] = payload;
in_flight_.insert(id, std::move(p));
+ update_sweep_timer();
proc_->write(encode_frame(req));
}
void PythonWorker::stop() {
shutting_down_ = true;
+ sweep_timer_.stop();
+ ready_watchdog_.stop();
if (!proc_)
return;
if (proc_->state() == QProcess::Running) {
@@ -185,27 +198,109 @@ void PythonWorker::on_process_finished(int exit_code, QProcess::ExitStatus statu
const QString reason = QString("daemon exited (code=%1 status=%2)").arg(exit_code).arg(status);
LOG_INFO("PythonWorker", reason);
- // Fail any in-flight requests; queued requests are preserved for the
- // next restart so callers don't observe spurious failures.
- for (auto it = in_flight_.begin(); it != in_flight_.end(); ++it) {
+ // Take the in-flight map out of the object *before* running any callback.
+ // Two reasons, both load-bearing:
+ // 1. exactly-once — once swapped out, nothing else in this class can see
+ // these ids, so no other path can complete them a second time;
+ // 2. reentrancy — a callback is free to call submit() (a retry) and
+ // inserting into a container we are iterating is undefined behaviour.
+ QHash<int, Pending> taken;
+ taken.swap(in_flight_);
+
+ // Queued requests are normally preserved across a restart so callers don't
+ // observe spurious failures; only a spent restart budget retires them.
+ QVector<QPair<int, Pending>> taken_queue;
+
+ if (!shutting_down_ && !QCoreApplication::closingDown()) {
+ if (restart_count_ >= kMaxRestarts) {
+ LOG_ERROR("PythonWorker",
+ QString("Restart cap (%1) reached — giving up, pending requests will fail").arg(kMaxRestarts));
+ taken_queue.swap(queue_);
+ } else {
+ ++restart_count_;
+ LOG_INFO("PythonWorker",
+ QString("Restarting daemon (attempt %1/%2)").arg(restart_count_).arg(kMaxRestarts));
+ // Relaunch before the callbacks run: a callback that re-submits
+ // then finds a live-but-not-ready process and queues, rather than
+ // racing ensure_started() into launching a second daemon.
+ launch_process();
+ }
+ }
+
+ update_sweep_timer();
+
+ for (auto it = taken.begin(); it != taken.end(); ++it) {
if (it.value().cb)
it.value().cb(false, {}, reason);
}
- in_flight_.clear();
+ for (auto& entry : taken_queue) {
+ if (entry.second.cb)
+ entry.second.cb(false, {}, QStringLiteral("worker restart cap reached"));
+ }
+}
- if (shutting_down_ || QCoreApplication::closingDown()) {
- return;
+void PythonWorker::sweep_deadlines() {
+ // Collect + erase first, invoke last — same invariant as
+ // on_process_finished(): an entry we are about to fail must already be
+ // out of in_flight_/queue_ so a late response frame for the same id
+ // cannot complete it a second time (try_drain_frames() looks the id up
+ // and drops it as unknown), and so a re-entrant submit() from a callback
+ // cannot invalidate the iterators we hold here.
+ QVector<Pending> expired;
+ bool in_flight_expired = false;
+
+ for (auto it = in_flight_.begin(); it != in_flight_.end();) {
+ if (it.value().deadline.hasExpired()) {
+ LOG_WARN("PythonWorker", QString("Request id=%1 action=%2 exceeded %3 ms budget — failing")
+ .arg(it.key())
+ .arg(it.value().action)
+ .arg(kRequestTimeoutMs));
+ expired.append(std::move(it.value()));
+ it = in_flight_.erase(it);
+ in_flight_expired = true;
+ } else {
+ ++it;
+ }
}
- if (restart_count_ >= kMaxRestarts) {
- LOG_ERROR("PythonWorker",
- QString("Restart cap (%1) reached — giving up, pending requests will fail").arg(kMaxRestarts));
- fail_all_pending(QStringLiteral("worker restart cap reached"));
- return;
+ // Queued requests expire too. Without this, a worker that never starts
+ // (script missing, no interpreter — launch_process() returns early and
+ // never arms ready_watchdog_) leaves its callers with no callback at all.
+ for (int i = queue_.size() - 1; i >= 0; --i) {
+ if (queue_[i].second.deadline.hasExpired()) {
+ LOG_WARN("PythonWorker", QString("Queued request id=%1 action=%2 expired before dispatch")
+ .arg(queue_[i].first)
+ .arg(queue_[i].second.action));
+ expired.append(std::move(queue_[i].second));
+ queue_.removeAt(i);
+ }
}
- ++restart_count_;
- LOG_INFO("PythonWorker", QString("Restarting daemon (attempt %1/%2)").arg(restart_count_).arg(kMaxRestarts));
- launch_process();
+
+ if (in_flight_expired && proc_ && proc_->state() != QProcess::NotRunning) {
+ // The daemon dispatch loop is serial, so whatever wedged the expired
+ // request still owns the pipe and everything behind it is stuck too.
+ // Killing is the only recovery; on_process_finished() restarts it and
+ // fails the remaining (not-yet-expired) in-flight requests. kill() is
+ // asynchronous, so `finished` arrives via the event loop — it cannot
+ // re-enter this function.
+ LOG_WARN("PythonWorker", "Killing wedged daemon after request timeout");
+ proc_->kill();
+ }
+
+ update_sweep_timer();
+
+ for (Pending& p : expired) {
+ if (p.cb)
+ p.cb(false, {}, QStringLiteral("daemon timeout"));
+ }
+}
+
+void PythonWorker::update_sweep_timer() {
+ const bool want = !shutting_down_ && (!in_flight_.isEmpty() || !queue_.isEmpty());
+ if (want && !sweep_timer_.isActive())
+ sweep_timer_.start();
+ else if (!want && sweep_timer_.isActive())
+ sweep_timer_.stop();
}
void PythonWorker::on_process_error(QProcess::ProcessError err) {
@@ -217,6 +312,9 @@ void PythonWorker::on_ready_read() {
return;
read_buf_.append(proc_->readAllStandardOutput());
try_drain_frames();
+ // Every early-return path in try_drain_frames() returns here, so this is
+ // the single place the sweep timer needs re-evaluating after a drain.
+ update_sweep_timer();
}
void PythonWorker::try_drain_frames() {
@@ -258,13 +356,18 @@ void PythonWorker::try_drain_frames() {
continue;
}
- // Response
+ // Response. An id that is no longer in flight was already completed —
+ // most often by sweep_deadlines() failing it as timed out and this
+ // frame arriving late. Dropping it here is what keeps the callback
+ // exactly-once; ids are never reused, so this can't be a mismatch.
const int id = obj.value("id").toInt();
auto it = in_flight_.find(id);
if (it == in_flight_.end()) {
- LOG_DEBUG("PythonWorker", QString("Unknown response id=%1 — ignoring").arg(id));
+ LOG_DEBUG("PythonWorker", QString("Unknown/already-completed response id=%1 — ignoring").arg(id));
continue;
}
+ // Take the entry out before invoking: the callback may re-enter
+ // submit(), which inserts into in_flight_.
Pending p = std::move(it.value());
in_flight_.erase(it);
const bool ok = obj.value("ok").toBool();
@@ -301,16 +404,23 @@ void PythonWorker::dispatch_queued() {
}
void PythonWorker::fail_all_pending(const QString& reason) {
- for (auto& entry : queue_) {
+ // Take both containers out before invoking anything — see the swap
+ // comment in on_process_finished(). This is what makes the callback
+ // exactly-once even when a callback re-enters submit() or stop().
+ auto taken_queue = std::move(queue_);
+ queue_.clear();
+ QHash<int, Pending> taken;
+ taken.swap(in_flight_);
+ update_sweep_timer();
+
+ for (auto& entry : taken_queue) {
if (entry.second.cb)
entry.second.cb(false, {}, reason);
}
- queue_.clear();
- for (auto it = in_flight_.begin(); it != in_flight_.end(); ++it) {
+ for (auto it = taken.begin(); it != taken.end(); ++it) {
if (it.value().cb)
it.value().cb(false, {}, reason);
}
- in_flight_.clear();
}
} // namespace fincept::python
diff --git a/fincept-qt/src/python/PythonWorker.h b/fincept-qt/src/python/PythonWorker.h
index f1dd2909f..7494cf0fa 100644
--- a/fincept-qt/src/python/PythonWorker.h
+++ b/fincept-qt/src/python/PythonWorker.h
@@ -1,5 +1,6 @@
#pragma once
+#include <QDeadlineTimer>
#include <QHash>
#include <QJsonObject>
#include <QObject>
@@ -7,6 +8,7 @@
#include <QProcess>
#include <QString>
#include <QTimer>
+#include <QVector>
#include <functional>
@@ -29,6 +31,12 @@ namespace fincept::python {
/// Lifecycle: `start()` is lazy — call from the first producer. Restart on
/// unexpected exit is automatic (up to a retry cap). `stop()` closes stdin
/// and waits briefly for a clean exit.
+///
+/// Liveness: the daemon loop is strictly serial (read → dispatch → write), so
+/// one wedged Yahoo request stalls every request behind it. Each request
+/// therefore carries a deadline; a periodic sweep fails whatever has expired
+/// and kills the daemon so the restart path can recover it. Every request gets
+/// exactly one callback — see `sweep_deadlines()` for the invariant.
class PythonWorker : public QObject {
Q_OBJECT
public:
@@ -62,6 +70,11 @@ class PythonWorker : public QObject {
void try_drain_frames();
void dispatch_queued();
void fail_all_pending(const QString& reason);
+ /// Fail every request whose deadline has passed, then kill a daemon that
+ /// still owes us an expired in-flight response.
+ void sweep_deadlines();
+ /// Run the sweep timer only while something is actually outstanding.
+ void update_sweep_timer();
QProcess* proc_ = nullptr;
bool ready_ = false;
@@ -69,24 +82,43 @@ class PythonWorker : public QObject {
int restart_count_ = 0;
static constexpr int kMaxRestarts = 5;
static constexpr int kReadyTimeoutMs = 15'000; // import yfinance+pandas
+ /// How often we check deadlines — not the budget itself.
+ static constexpr int kSweepIntervalMs = 5'000;
+ /// Wall-clock budget per request, measured from submit() (so it covers
+ /// queue wait + daemon-start time, which is what the caller experiences).
+ /// Sized above the worst legitimate action: batch_all fans out two
+ /// yf.download rounds whose per-HTTP budget is _NET_TIMEOUT (15s) in
+ /// scripts/yfinance_data.py, plus yfinance's internal retries.
+ static constexpr int kRequestTimeoutMs = 90'000;
// Pending request tracking. Keyed by request id for response correlation.
struct Pending {
QString action;
QJsonObject payload;
Callback cb;
+ /// Set once at submit(); never extended. A request lives in exactly
+ /// one of queue_/in_flight_, so whichever container holds it owns the
+ /// right to run its callback.
+ QDeadlineTimer deadline;
};
QHash<int, Pending> in_flight_;
// Requests submitted before the daemon was ready, or queued during restart.
QVector<QPair<int, Pending>> queue_;
+ // Monotonic and never reset, including across daemon restarts. The
+ // exactly-once guarantee depends on this: a response frame from a killed
+ // daemon must never collide with an id we handed out afterwards.
int next_id_ = 1;
// Read buffer — frames may span multiple readyRead() signals.
QByteArray read_buf_;
// Ready-wait watchdog — if the daemon hasn't handshaked within the
- // timeout, kill it and restart.
+ // timeout, kill it and restart. Guards the handshake only.
QTimer ready_watchdog_;
+
+ // Per-request watchdog — repeating; started on the first outstanding
+ // request and stopped when nothing is outstanding.
+ QTimer sweep_timer_;
};
} // namespace fincept::python
diff --git a/fincept-qt/src/screens/about/AboutScreen.cpp b/fincept-qt/src/screens/about/AboutScreen.cpp
index 8a6411cdd..975a86228 100644
--- a/fincept-qt/src/screens/about/AboutScreen.cpp
+++ b/fincept-qt/src/screens/about/AboutScreen.cpp
@@ -237,29 +237,32 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
rl->addWidget(panel, 1);
}
- // Commercial
+ // Enterprise — the separate closed-source product, not a licence for this build.
+ // Fincept no longer sells a commercial licence for the open-source edition;
+ // commercial, institutional and academic use is served by Enterprise instead.
{
auto* panel = makePanel();
auto* pvl = new QVBoxLayout(panel);
pvl->setContentsMargins(0, 0, 0, 0);
pvl->setSpacing(0);
- commercial_header_ = makePanelHeader("★", tr("COMMERCIAL LICENSE"), ui::colors::AMBER);
- pvl->addWidget(commercial_header_);
+ enterprise_header_ = makePanelHeader("★", tr("FINCEPT TERMINAL ENTERPRISE"), ui::colors::AMBER);
+ pvl->addWidget(enterprise_header_);
auto* body = new QWidget(this);
body->setStyleSheet("background: transparent;");
auto* bvl = new QVBoxLayout(body);
bvl->setContentsMargins(14, 10, 14, 10);
bvl->setSpacing(6);
- commercial_bullets_ = {
- makeBullet(tr("Required for commercial deployment")), makeBullet(tr("No source sharing required")),
- makeBullet(tr("Priority support included")), makeBullet(tr("Custom integration options available"))};
- for (auto* b : commercial_bullets_)
+ enterprise_bullets_ = {makeBullet(tr("41 modules · private & proprietary data")),
+ makeBullet(tr("Multi-agent research · live broker routing")),
+ makeBullet(tr("SSO, audit logs & SLA-backed support")),
+ makeBullet(tr("From $99/user/month · no copyleft"))};
+ for (auto* b : enterprise_bullets_)
bvl->addWidget(b);
pvl->addWidget(body);
// Footer link
- auto* foot = new QLabel("[email protected]");
+ auto* foot = new QLabel("fincept.in/enterprise");
foot->setStyleSheet(QString("color: %1; font-size: 11px; background: transparent; "
"padding: 6px 14px; border-top: 1px solid %2; "
"font-family: 'Consolas','Courier New',monospace;")
@@ -376,8 +379,7 @@ AboutScreen::AboutScreen(QWidget* parent) : QWidget(parent) {
const Link links[] = {
{tr("GitHub Repository"), "https://github.com/Fincept-Corporation/FinceptTerminal"},
{tr("License (AGPL-3.0)"), "https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/LICENSE"},
- {tr("Commercial License"),
- "https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/COMMERCIAL_LICENSE.md"},
+ {tr("Fincept Enterprise"), "https://fincept.in/enterprise"},
{tr("Documentation"), "https://github.com/Fincept-Corporation/FinceptTerminal/tree/main/docs"},
{tr("Contributing Guide"),
"https://github.com/Fincept-Corporation/FinceptTerminal/blob/main/docs/CONTRIBUTING.md"},
@@ -478,13 +480,13 @@ void AboutScreen::retranslateUi() {
setBulletText(oss_bullets_[3], tr("Network use counts as distribution"));
}
- // Commercial license
- setPanelHeaderText(commercial_header_, "★", tr("COMMERCIAL LICENSE"));
- if (commercial_bullets_.size() == 4) {
- setBulletText(commercial_bullets_[0], tr("Required for commercial deployment"));
- setBulletText(commercial_bullets_[1], tr("No source sharing required"));
- setBulletText(commercial_bullets_[2], tr("Priority support included"));
- setBulletText(commercial_bullets_[3], tr("Custom integration options available"));
+ // Enterprise (separate closed-source product)
+ setPanelHeaderText(enterprise_header_, "★", tr("FINCEPT TERMINAL ENTERPRISE"));
+ if (enterprise_bullets_.size() == 4) {
+ setBulletText(enterprise_bullets_[0], tr("41 modules · private & proprietary data"));
+ setBulletText(enterprise_bullets_[1], tr("Multi-agent research · live broker routing"));
+ setBulletText(enterprise_bullets_[2], tr("SSO, audit logs & SLA-backed support"));
+ setBulletText(enterprise_bullets_[3], tr("From $99/user/month · no copyleft"));
}
// Diagnostics
@@ -509,7 +511,7 @@ void AboutScreen::retranslateUi() {
if (resource_btns_.size() == 6) {
resource_btns_[0]->setText(tr("GitHub Repository"));
resource_btns_[1]->setText(tr("License (AGPL-3.0)"));
- resource_btns_[2]->setText(tr("Commercial License"));
+ resource_btns_[2]->setText(tr("Fincept Enterprise"));
resource_btns_[3]->setText(tr("Documentation"));
resource_btns_[4]->setText(tr("Contributing Guide"));
resource_btns_[5]->setText(tr("Official Website"));
diff --git a/fincept-qt/src/screens/about/AboutScreen.h b/fincept-qt/src/screens/about/AboutScreen.h
index a53ca2805..fd60a7c63 100644
--- a/fincept-qt/src/screens/about/AboutScreen.h
+++ b/fincept-qt/src/screens/about/AboutScreen.h
@@ -28,11 +28,11 @@ class AboutScreen : public QWidget {
bool check_in_progress_ = false;
QLabel* copyright_ = nullptr;
- // License panels
+ // Edition panels — open-source licence vs the Enterprise product
QLabel* oss_header_ = nullptr;
QList<QLabel*> oss_bullets_;
- QLabel* commercial_header_ = nullptr;
- QList<QLabel*> commercial_bullets_;
+ QLabel* enterprise_header_ = nullptr;
+ QList<QLabel*> enterprise_bullets_;
// Diagnostics
QLabel* diag_header_ = nullptr;
diff --git a/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp b/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp
index 5e3a524ef..324c56ba4 100644
--- a/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp
+++ b/fincept-qt/src/screens/action_center/PendingOrdersPanel.cpp
@@ -11,6 +11,7 @@
#include <QMessageBox>
#include <QPointer>
#include <QPushButton>
+#include <QScopeGuard>
#include <QSignalBlocker>
#include <QVBoxLayout>
@@ -187,6 +188,25 @@ void PendingOrdersPanel::build_ui() {
approve_all_btn_->setAccessibleName(tr("Approve all pending orders"));
reject_all_btn_->setAccessibleName(tr("Reject all pending orders"));
connect(approve_all_btn_, &QPushButton::clicked, this, [this]() {
+ // Latch BOTH bulk buttons for the whole handler. Everything below spins a
+ // nested event loop — the confirmation QMessageBox, and approve_all_pending
+ // itself (one blocking broker round-trip per order, up to ~8 s each) — and
+ // a nested loop keeps delivering clicks, so an un-latched button could fire
+ // the same queue a second time while the first pass was still running. The
+ // per-row buttons already latch (see refresh()); these did not.
+ // QPointer + qScopeGuard: the guard restores on EVERY exit path (early
+ // return, exception) and no-ops if the popover was destroyed meanwhile.
+ QPointer<QPushButton> ap_guard(approve_all_btn_);
+ QPointer<QPushButton> rj_guard(reject_all_btn_);
+ auto set_bulk_enabled = [ap_guard, rj_guard](bool on) {
+ if (ap_guard)
+ ap_guard->setEnabled(on);
+ if (rj_guard)
+ rj_guard->setEnabled(on);
+ };
+ set_bulk_enabled(false);
+ const auto restore = qScopeGuard([set_bulk_enabled]() { set_bulk_enabled(true); });
+
const QString acct = selected_account();
// Bulk approval fires every queued order at the broker in a loop with no
// per-order review. Say exactly how many, for which account, how many are
@@ -231,6 +251,18 @@ void PendingOrdersPanel::build_ui() {
ActionCenter::instance().approve_all_pending(acct);
});
connect(reject_all_btn_, &QPushButton::clicked, this, [this]() {
+ // Same latch as Approve All — QInputDialog spins a nested event loop too.
+ QPointer<QPushButton> ap_guard(approve_all_btn_);
+ QPointer<QPushButton> rj_guard(reject_all_btn_);
+ auto set_bulk_enabled = [ap_guard, rj_guard](bool on) {
+ if (ap_guard)
+ ap_guard->setEnabled(on);
+ if (rj_guard)
+ rj_guard->setEnabled(on);
+ };
+ set_bulk_enabled(false);
+ const auto restore = qScopeGuard([set_bulk_enabled]() { set_bulk_enabled(true); });
+
const QString acct = selected_account();
if (acct.isEmpty()) {
QMessageBox::information(this, tr("Reject All"),
diff --git a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
index d389dc353..b5f6a5d39 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatBubble.cpp
@@ -213,6 +213,32 @@ void AiChatBubble::build_chat_panel() {
scroll_area_->setWidget(msg_container_);
vl->addWidget(scroll_area_, 1);
+ // Follow the stream — see the same handler in AiChatScreen_Layout.cpp. A
+ // timer-based setValue(maximum()) reads the maximum from before the growing
+ // widget re-laid out, so it always trails the newest content; rangeChanged
+ // fires after the layout settles.
+ if (auto* vbar = scroll_area_->verticalScrollBar()) {
+ connect(vbar, &QScrollBar::rangeChanged, this, [this](int, int max) {
+ if (!stick_to_bottom_ || !scroll_area_)
+ return;
+ auto* sb = scroll_area_->verticalScrollBar();
+ if (!sb)
+ return;
+ programmatic_scroll_ = true;
+ sb->setValue(max);
+ programmatic_scroll_ = false;
+ });
+ connect(vbar, &QScrollBar::valueChanged, this, [this](int v) {
+ if (programmatic_scroll_ || !scroll_area_)
+ return;
+ auto* sb = scroll_area_->verticalScrollBar();
+ if (!sb)
+ return;
+ constexpr int kAtBottomSlackPx = 48;
+ stick_to_bottom_ = (v >= sb->maximum() - kAtBottomSlackPx);
+ });
+ }
+
build_welcome_widget();
show_welcome_if_empty();
@@ -523,6 +549,10 @@ void AiChatBubble::on_send() {
hide_welcome();
add_bubble("user", text);
+ last_tool_label_.clear(); // fresh run of tool lines for this message
+ // Snapshot the PRIOR turns — chat_streaming appends `text` as the trailing
+ // user message itself, so appending here first duplicated it on the wire.
+ std::vector<ai_chat::ConversationMessage> hist_copy = chat_history_;
chat_history_.push_back({"user", text});
streaming_ = true;
@@ -538,7 +568,7 @@ void AiChatBubble::on_send() {
// category so the model can't yank the user out of their current screen
// by calling navigate_to_tab / list_tabs / get_current_tab.
ai_chat::LlmService::instance().chat_streaming(
- text, chat_history_,
+ text, hist_copy,
[self, first_chunk](const QString& chunk, bool done) {
QMetaObject::invokeMethod(
qApp,
@@ -568,6 +598,22 @@ void AiChatBubble::on_stream_chunk(const QString& chunk, bool done) {
QLabel* bubble = streaming_bubble_;
if (!bubble)
return;
+ // Tool progress: no room for a separate card here, so render it inline —
+ // but strip the sentinel, which is a routing marker, not text. Consecutive
+ // repeats are dropped rather than counted: the compact bubble can't rewrite
+ // an already-rendered line, and ~45 identical set_excel_cell lines would
+ // bury the conversation.
+ const QString tool_prefix = ai_chat::tool_stream_prefix();
+ if (chunk.startsWith(tool_prefix)) {
+ const QString label = chunk.mid(tool_prefix.size()).trimmed();
+ if (label.isEmpty() || label == last_tool_label_)
+ return;
+ last_tool_label_ = label;
+ fincept::ai_chat::ChatBubbleFactory::append_streaming_chunk(bubble, QStringLiteral("• ") + label +
+ QStringLiteral("\n"));
+ scroll_to_bottom();
+ return;
+ }
if (!chunk.isEmpty()) {
fincept::ai_chat::ChatBubbleFactory::append_streaming_chunk(bubble, chunk);
scroll_to_bottom();
@@ -629,9 +675,17 @@ QLabel* AiChatBubble::add_streaming_bubble() {
}
void AiChatBubble::scroll_to_bottom() {
+ // Re-arm following; the rangeChanged handler does the real work once the
+ // layout settles. This nudge covers content changes that leave the range
+ // untouched.
+ stick_to_bottom_ = true;
QTimer::singleShot(30, this, [this]() {
- if (scroll_area_ && scroll_area_->verticalScrollBar())
- scroll_area_->verticalScrollBar()->setValue(scroll_area_->verticalScrollBar()->maximum());
+ if (!scroll_area_ || !scroll_area_->verticalScrollBar())
+ return;
+ auto* sb = scroll_area_->verticalScrollBar();
+ programmatic_scroll_ = true;
+ sb->setValue(sb->maximum());
+ programmatic_scroll_ = false;
});
}
diff --git a/fincept-qt/src/screens/ai_chat/AiChatBubble.h b/fincept-qt/src/screens/ai_chat/AiChatBubble.h
index 4570d0916..e31ddc30c 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatBubble.h
+++ b/fincept-qt/src/screens/ai_chat/AiChatBubble.h
@@ -66,6 +66,12 @@ class AiChatBubble : public QWidget {
// Panel internals
QScrollArea* scroll_area_ = nullptr;
+ // Auto-follow the newest content; cleared when the user scrolls up to read.
+ bool stick_to_bottom_ = true;
+ // Guards our own setValue() so auto-scroll isn't mistaken for a user scroll.
+ bool programmatic_scroll_ = false;
+ // Last tool-progress label rendered; consecutive repeats are dropped.
+ QString last_tool_label_;
QWidget* msg_container_ = nullptr;
QVBoxLayout* msg_layout_ = nullptr;
QWidget* welcome_widget_ = nullptr; // shown when chat is empty
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp
index 0f7110629..97429a1d7 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen.cpp
@@ -195,8 +195,8 @@ void AiChatScreen::subscribe_mcp_events() {
};
auto& bus = EventBus::instance();
- mcp_event_subs_.append(bus.subscribe("llm.provider_changed", on_provider_event));
- mcp_event_subs_.append(bus.subscribe("ai_chat.session_created", on_session_created));
+ mcp_event_subs_.append(bus.subscribe(this, "llm.provider_changed", on_provider_event));
+ mcp_event_subs_.append(bus.subscribe(this, "ai_chat.session_created", on_session_created));
}
void AiChatScreen::unsubscribe_mcp_events() {
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen.h b/fincept-qt/src/screens/ai_chat/AiChatScreen.h
index 339d4fc88..14d849f35 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen.h
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen.h
@@ -17,6 +17,7 @@
#include <QPropertyAnimation>
#include <QPushButton>
#include <QScrollArea>
+#include <QStringList>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
@@ -124,6 +125,12 @@ class AiChatScreen : public QWidget, public IStatefulScreen, public fincept::IGr
std::vector<ai_chat::ConversationMessage> history_;
bool streaming_ = false;
bool scroll_pending_ = false;
+ // Auto-follow the newest content. Cleared when the user scrolls up to read,
+ // re-armed when they come back to the bottom or send a new message.
+ bool stick_to_bottom_ = true;
+ // Set around our own setValue() calls so the valueChanged handler doesn't
+ // mistake an auto-scroll for the user scrolling.
+ bool programmatic_scroll_ = false;
QPointer<QLabel> streaming_bubble_;
int total_tokens_ = 0;
int total_messages_ = 0;
@@ -137,6 +144,20 @@ class AiChatScreen : public QWidget, public IStatefulScreen, public fincept::IGr
QPointer<QLabel> thinking_body_;
QString thinking_text_;
+ // ── Per-stream "Tools" section ───────────────────────────────────────────
+ // Tool-progress lines arrive on their own channel (see tool_stream_prefix())
+ // and land in a card of their own rather than being appended into the answer
+ // bubble — plumbing like tool_list / tool_describe is not part of the reply.
+ // Expanded while running so the user can see progress, collapsed on finish.
+ QPointer<QWidget> tools_card_;
+ QPointer<QPushButton> tools_header_;
+ QPointer<QLabel> tools_body_;
+ QString tools_text_;
+ QStringList tools_lines_; // rendered lines; last one is rewritten to collapse runs
+ QString tools_run_base_; // tool name of the run currently being collapsed
+ int tools_run_count_ = 0; // length of that run
+ int tools_count_ = 0; // total steps, for the collapsed header
+
// ── Build ────────────────────────────────────────────────────────────
void build_ui();
void retranslateUi();
@@ -159,6 +180,11 @@ class AiChatScreen : public QWidget, public IStatefulScreen, public fincept::IGr
void create_thinking_card();
void finalize_thinking_card();
void reset_thinking_state();
+ // Collapsible "Tools" card for the in-flight assistant message.
+ void append_tool_chunk(const QString& text);
+ void create_tools_card();
+ void finalize_tools_card();
+ void reset_tools_state();
void clear_messages();
void scroll_to_bottom();
void set_input_enabled(bool enabled);
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp
index 53bc3ad25..a16ca9e4f 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Layout.cpp
@@ -244,11 +244,43 @@ void AiChatScreen::build_chat_area() {
scroll_area_->setWidget(messages_container_);
vl->addWidget(scroll_area_, 1);
- // Debounced persistence when the user scrolls through chat history.
- if (auto* vbar = scroll_area_->verticalScrollBar())
+ if (auto* vbar = scroll_area_->verticalScrollBar()) {
+ // Debounced persistence when the user scrolls through chat history.
connect(vbar, &QScrollBar::valueChanged, this,
[this](int) { ScreenStateManager::instance().notify_changed(this); });
+ // ── Follow the stream ────────────────────────────────────────────
+ // scroll_to_bottom()'s singleShot(0) fires BEFORE Qt recomputes the
+ // layout for a widget that just grew (setText on a wrapped QLabel
+ // defers its resize), so setValue(maximum()) lands on the *old*
+ // maximum and the view sits one growth-step short — for a card that
+ // keeps growing, permanently behind. rangeChanged fires after the
+ // layout settles, which is the only moment the true bottom is known.
+ connect(vbar, &QScrollBar::rangeChanged, this, [this](int, int max) {
+ if (!stick_to_bottom_ || !scroll_area_)
+ return;
+ auto* sb = scroll_area_->verticalScrollBar();
+ if (!sb)
+ return;
+ programmatic_scroll_ = true;
+ sb->setValue(max);
+ programmatic_scroll_ = false;
+ });
+
+ // Scrolling up mid-stream means "let me read" — stop dragging the view
+ // down until the user returns to the bottom. Programmatic moves are
+ // excluded, or auto-scroll would immediately re-arm itself.
+ connect(vbar, &QScrollBar::valueChanged, this, [this](int v) {
+ if (programmatic_scroll_ || !scroll_area_)
+ return;
+ auto* sb = scroll_area_->verticalScrollBar();
+ if (!sb)
+ return;
+ constexpr int kAtBottomSlackPx = 48;
+ stick_to_bottom_ = (v >= sb->maximum() - kAtBottomSlackPx);
+ });
+ }
+
// Typing indicator sits above input, inside chat area
vl->addWidget(build_typing_indicator());
vl->addWidget(build_input_area());
diff --git a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
index 412e3db11..428262e28 100644
--- a/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
+++ b/fincept-qt/src/screens/ai_chat/AiChatScreen_Messaging.cpp
@@ -147,17 +147,22 @@ void AiChatScreen::on_send() {
ChatRepository::instance().add_message(active_session_id_, "user", text,
ai_chat::LlmService::instance().active_provider(),
ai_chat::LlmService::instance().active_model());
+ // Snapshot BEFORE appending the new turn: every request builder appends
+ // `text` as the trailing user message itself, so including it in the history
+ // too sent the same turn twice (and, on the Fincept flat-prompt path, printed
+ // "User: …" twice in a row).
+ std::vector<ai_chat::ConversationMessage> hist_copy = history_;
history_.push_back({"user", text});
// Show typing indicator while waiting for first chunk
show_typing(true);
scroll_to_bottom();
- // Fresh Thinking section for this message (reasoning chunks land in a
- // collapsible card created lazily by on_stream_chunk).
+ // Fresh Thinking / Tools sections for this message (both cards are created
+ // lazily by on_stream_chunk when their channel first produces a chunk).
reset_thinking_state();
+ reset_tools_state();
- std::vector<ai_chat::ConversationMessage> hist_copy = history_;
const QString provider = ai_chat::LlmService::instance().active_provider();
if (ai_chat::provider_supports_streaming(provider)) {
QPointer<AiChatScreen> self = this;
@@ -210,6 +215,15 @@ void AiChatScreen::on_stream_chunk(const QString& chunk, bool done) {
return;
}
+ // Tool-progress chunk → its own collapsible Tools card, never the answer
+ // bubble. Keeps plumbing (tool_list / tool_describe) out of the reply.
+ const QString tool_prefix = ai_chat::tool_stream_prefix();
+ if (chunk.startsWith(tool_prefix)) {
+ append_tool_chunk(chunk.mid(tool_prefix.size()));
+ scroll_to_bottom();
+ return;
+ }
+
// Tool-call clear sentinel: reset bubble content (removes partial XML).
if (chunk.startsWith("\x01__TOOL_CALL_CLEAR__")) {
if (!streaming_bubble_)
@@ -234,9 +248,10 @@ void AiChatScreen::on_streaming_done(ai_chat::LlmResponse response) {
streaming_ = false;
show_typing(false);
- // Lock in the Thinking card (swap the live "Thinking…" header for its final
- // label) and stop tracking it so the next message starts a fresh one.
+ // Lock in the Thinking and Tools cards (swap their live headers for final
+ // labels) and stop tracking them so the next message starts fresh ones.
finalize_thinking_card();
+ finalize_tools_card();
// Ensure a bubble exists for any terminal state (success + content,
// failure with an error message, or success-but-empty). Without this,
@@ -418,11 +433,122 @@ void AiChatScreen::reset_thinking_state() {
thinking_text_.clear();
}
+// ── Tools card ──────────────────────────────────────────────────────────────────
+// Same shape as the Thinking card, different channel (tool_stream_prefix()).
+// Starts EXPANDED — unlike chain-of-thought, tool progress is the only signal the
+// user has that a long multi-round turn is advancing — and collapses on finish
+// into a one-line "N tools used" summary.
+
+void AiChatScreen::create_tools_card() {
+ if (tools_card_)
+ return;
+
+ auto* card = new QWidget;
+ card->setMaximumWidth(kAiColMaxWidth);
+ card->setStyleSheet(QString("background:%1;border:1px solid %2;").arg(col::BG_SURFACE(), col::BORDER_DIM()));
+ auto* vl = new QVBoxLayout(card);
+ vl->setContentsMargins(10, 6, 10, 6);
+ vl->setSpacing(4);
+
+ auto* header = new QPushButton(QChar(0x25BE) + (QStringLiteral(" ") + QString::fromUtf8("\xF0\x9F\x94\xA7") +
+ QStringLiteral(" ")) +
+ tr("Using tools…"));
+ header->setCursor(Qt::PointingHandCursor);
+ header->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:none;"
+ "font-size:%2px;font-weight:600;text-align:left;padding:0;}"
+ "QPushButton:hover{color:%3;}")
+ .arg(col::TEXT_TERTIARY())
+ .arg(fnt::SMALL)
+ .arg(col::TEXT_SECONDARY()));
+ vl->addWidget(header);
+
+ auto* body = new QLabel;
+ body->setWordWrap(true);
+ body->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ body->setVisible(true); // expanded while the turn runs
+ body->setStyleSheet(QString("QLabel{color:%1;font-size:%2px;background:transparent;}")
+ .arg(col::TEXT_DIM())
+ .arg(fnt::SMALL));
+ vl->addWidget(body);
+
+ // Raw pointers, not the QPointer members — those are nulled when the stream
+ // finishes, and the finished card must stay toggleable.
+ QObject::connect(header, &QPushButton::clicked, card, [header, body]() {
+ const bool show = !body->isVisible();
+ body->setVisible(show);
+ QString t = header->text();
+ if (!t.isEmpty())
+ t.replace(0, 1, show ? QChar(0x25BE) : QChar(0x25B8));
+ header->setText(t);
+ });
+
+ messages_layout_->insertWidget(messages_layout_->count() - 1, card, 0, Qt::AlignLeft);
+ tools_card_ = card;
+ tools_header_ = header;
+ tools_body_ = body;
+}
+
+void AiChatScreen::append_tool_chunk(const QString& text) {
+ if (text.isEmpty())
+ return;
+ show_typing(false); // the card now signals activity
+ if (!tools_card_)
+ create_tools_card();
+
+ for (const QString& raw : text.split(QLatin1Char('\n'), Qt::SkipEmptyParts)) {
+ const QString line = raw.trimmed();
+ if (line.isEmpty())
+ continue;
+ ++tools_count_;
+
+ // Collapse a consecutive run of the same tool into "name ×N". Writing a
+ // spreadsheet is ~45 back-to-back set_excel_cell calls; listing each is a
+ // wall of noise that buries the steps that actually differ.
+ const QString base = line.section(QStringLiteral(" · "), 0, 0);
+ if (base == tools_run_base_ && !tools_lines_.isEmpty()) {
+ ++tools_run_count_;
+ tools_lines_.last() = base + QStringLiteral(" ×") + QString::number(tools_run_count_);
+ } else {
+ tools_run_base_ = base;
+ tools_run_count_ = 1;
+ tools_lines_.append(line);
+ }
+ }
+
+ tools_text_ = QStringLiteral("• ") + tools_lines_.join(QStringLiteral("\n• "));
+ if (tools_body_)
+ tools_body_->setText(tools_text_);
+}
+
+void AiChatScreen::finalize_tools_card() {
+ if (tools_header_) {
+ // Collapse once the answer is in — the detail stays one click away.
+ if (tools_body_)
+ tools_body_->setVisible(false);
+ tools_header_->setText(QChar(0x25B8) +
+ (QStringLiteral(" ") + QString::fromUtf8("\xF0\x9F\x94\xA7") + QStringLiteral(" ")) +
+ tr("%n tool step(s)", "", tools_count_));
+ }
+ reset_tools_state();
+}
+
+void AiChatScreen::reset_tools_state() {
+ tools_card_ = nullptr;
+ tools_header_ = nullptr;
+ tools_body_ = nullptr;
+ tools_text_.clear();
+ tools_lines_.clear();
+ tools_run_base_.clear();
+ tools_run_count_ = 0;
+ tools_count_ = 0;
+}
+
// ── Helpers ───────────────────────────────────────────────────────────────────
void AiChatScreen::clear_messages() {
streaming_bubble_.clear();
reset_thinking_state(); // card widgets are deleted by the loop below
+ reset_tools_state();
// Skip the welcome panel — it is a permanent fixture reused across sessions
// (it is only shown/hidden). Everything else is a message row.
for (int i = messages_layout_->count() - 1; i >= 0; --i) {
@@ -437,6 +563,12 @@ void AiChatScreen::clear_messages() {
}
void AiChatScreen::scroll_to_bottom() {
+ // Re-arm following. The rangeChanged handler installed in build_chat_area()
+ // does the real work — it fires once the layout has settled and therefore
+ // knows the true maximum. This deferred nudge covers the case where content
+ // changed without altering the scroll range.
+ stick_to_bottom_ = true;
+
// Debounce: a single scroll lands at the end of the current event-loop batch.
// Without this, a 100-chunk stream queued 100 independent 50ms timers, each
// racing to setValue() and starving paint events.
@@ -445,8 +577,12 @@ void AiChatScreen::scroll_to_bottom() {
scroll_pending_ = true;
QTimer::singleShot(0, this, [this]() {
scroll_pending_ = false;
- if (scroll_area_ && scroll_area_->verticalScrollBar())
- scroll_area_->verticalScrollBar()->setValue(scroll_area_->verticalScrollBar()->maximum());
+ if (!scroll_area_ || !scroll_area_->verticalScrollBar())
+ return;
+ auto* sb = scroll_area_->verticalScrollBar();
+ programmatic_scroll_ = true;
+ sb->setValue(sb->maximum());
+ programmatic_scroll_ = false;
});
}
diff --git a/fincept-qt/src/screens/akshare/AkShareScreen.cpp b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
index d2973a2f2..a382a9af8 100644
--- a/fincept-qt/src/screens/akshare/AkShareScreen.cpp
+++ b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
@@ -831,13 +831,20 @@ void AkShareScreen::display_table_data(const QJsonArray& rows_json, const QStrin
columns << it.key();
}
+ // Cap the fill and suppress repaints while it runs — same treatment as the
+ // sibling AsiaMarketsScreen::display_table. Without it a 5 000-row payload
+ // repainted the viewport on every setItem() on the UI thread.
+ int max_rows = qMin(rows_json.size(), 2000);
+
+ data_table_->setUpdatesEnabled(false);
data_table_->setColumnCount(columns.size());
data_table_->setHorizontalHeaderLabels(columns);
-
- // Populate rows (cap at 5000 to avoid UI freeze)
- int max_rows = qMin(rows_json.size(), 5000);
data_table_->setRowCount(max_rows);
+ // Pre-build color lookup to avoid repeated QColor construction
+ const QColor col_pos(colors::CYAN());
+ const QColor col_neg(colors::NEGATIVE());
+
for (int row = 0; row < max_rows; ++row) {
auto obj = rows_json[row].toObject();
for (int col = 0; col < columns.size(); ++col) {
@@ -870,23 +877,18 @@ void AkShareScreen::display_table_data(const QJsonArray& rows_json, const QStrin
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
// Color numbers in cyan, negative in red
- if (val.isDouble()) {
- double v = val.toDouble();
- if (v < 0) {
- item->setForeground(QColor(colors::NEGATIVE()));
- } else {
- item->setForeground(QColor(colors::CYAN()));
- }
- }
+ if (val.isDouble())
+ item->setForeground(val.toDouble() < 0 ? col_neg : col_pos);
data_table_->setItem(row, col, item);
}
}
- // Resize columns to content (limit to avoid freezing)
- if (columns.size() <= 20) {
- data_table_->resizeColumnsToContents();
- }
+ // Fixed column width — much faster than resizeColumnsToContents, which
+ // measured every cell in every column with no row-count guard at all.
+ data_table_->horizontalHeader()->setDefaultSectionSize(110);
+ data_table_->verticalHeader()->setDefaultSectionSize(22);
+ data_table_->setUpdatesEnabled(true);
data_table_->setSortingEnabled(true);
if (rows_json.size() > max_rows) {
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
index a2aadd7b4..ca0108737 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
@@ -22,15 +22,14 @@
#include <QDate>
#include <QDateEdit>
-#include <QEventLoop>
#include <QFrame>
-#include <QFutureWatcher>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
+#include <QPointer>
#include <QScrollArea>
#include <QSet>
#include <QSignalBlocker>
@@ -40,7 +39,9 @@
#include <QVBoxLayout>
#include <QtConcurrent>
+#include <atomic>
#include <cmath>
+#include <memory>
namespace fincept::screens {
namespace algo_ns = fincept::algo;
@@ -148,28 +149,64 @@ QString status_style() {
.arg(ui::fonts::DATA_FAMILY());
}
-// Bounded fetch of the current LTP from the connected broker for deploy-time sanity
-// checks. Runs off-thread with a short timeout so the deploy click never hangs.
-double fetch_quote_ltp(const QString& broker_id, const QString& account_id, const QString& symbol, int timeout_ms) {
- if (broker_id.isEmpty() || account_id.isEmpty() || symbol.isEmpty())
- return 0.0;
- auto fut = QtConcurrent::run([broker_id, account_id, symbol]() -> double {
+// Bounded, non-blocking fetch of the current LTP for deploy-time sanity checks.
+//
+// The previous version parked the GUI thread in `QEventLoop::exec()` with
+// DEFAULT flags, so user input was still delivered while the (already closed)
+// deploy dialog left nothing to constrain the user: destroying the panel during
+// that window left ~DeployGuard and the follow-up QMessageBox dereferencing
+// freed memory. It also let a stack QFutureWatcher die while its future was
+// still running, and degraded silently to 0.0 whenever the broker was slow.
+//
+// Now the broker round-trip runs on a worker and `on_result` is invoked EXACTLY
+// ONCE on `receiver`'s thread (§P1/§P8). 0.0 means "no usable quote": missing
+// broker/account/symbol, a failed request, or a probe that outran `timeout_ms`
+// — the last of which is now logged rather than silent.
+template <typename OnResult>
+void fetch_quote_ltp_async(const QString& broker_id, const QString& account_id, const QString& symbol, int timeout_ms,
+ QObject* receiver, OnResult on_result) {
+ auto answered = std::make_shared<std::atomic<bool>>(false);
+ QPointer<QObject> guard(receiver);
+
+ auto deliver = [answered, guard, on_result](double ltp) {
+ if (answered->exchange(true, std::memory_order_acq_rel))
+ return; // worker vs timeout race — first answer wins
+ if (!guard)
+ return;
+ QMetaObject::invokeMethod(
+ guard.data(),
+ [guard, on_result, ltp]() {
+ if (guard)
+ on_result(ltp);
+ },
+ Qt::QueuedConnection);
+ };
+
+ if (broker_id.isEmpty() || account_id.isEmpty() || symbol.isEmpty()) {
+ deliver(0.0);
+ return;
+ }
+
+ (void)QtConcurrent::run([broker_id, account_id, symbol, deliver]() {
auto* broker = trading::BrokerRegistry::instance().get(broker_id);
- if (!broker)
- return 0.0;
+ if (!broker) {
+ deliver(0.0);
+ return;
+ }
auto creds = trading::AccountManager::instance().load_credentials(account_id);
auto resp = broker->get_quotes(creds, {symbol});
- if (resp.success && resp.data.has_value() && !resp.data->isEmpty())
- return resp.data->first().ltp;
- return 0.0;
+ deliver(resp.success && resp.data.has_value() && !resp.data->isEmpty() ? resp.data->first().ltp : 0.0);
+ });
+
+ QTimer::singleShot(timeout_ms, receiver, [answered, deliver, symbol, timeout_ms]() {
+ if (answered->load(std::memory_order_acquire))
+ return;
+ LOG_WARN("AlgoTrading", QString("Deploy sanity check: quote probe for %1 did not answer within %2 ms — "
+ "skipping the unreachable-rule scan")
+ .arg(symbol)
+ .arg(timeout_ms));
+ deliver(0.0);
});
- QFutureWatcher<double> watcher;
- QEventLoop loop;
- QObject::connect(&watcher, &QFutureWatcher<double>::finished, &loop, &QEventLoop::quit);
- watcher.setFuture(fut);
- QTimer::singleShot(timeout_ms, &loop, &QEventLoop::quit);
- loop.exec();
- return watcher.isFinished() ? watcher.result() : 0.0;
}
// Collects human-readable warnings for price-based leaves that can't fire at `price`
@@ -695,16 +732,24 @@ void StrategyBuilderPanel::on_backtest() {
}
void StrategyBuilderPanel::on_deploy() {
- // Re-entrancy: exec() and the LTP probe below both run nested event loops, so
- // a second click would otherwise open a second dialog and deploy twice.
+ // Re-entrancy: the deploy dialog is modal and the post-accept broker probe
+ // is asynchronous, so without the gate a second click would open a second
+ // dialog and deploy twice.
if (deploying_)
return;
deploying_ = true;
if (deploy_btn_)
deploy_btn_->setEnabled(false);
+ // Releases the click gate on every SYNCHRONOUS exit below. Once the deploy
+ // hands off to the async quote probe the guard is disarmed and the queued
+ // continuation owns the release instead — the old unconditional version
+ // dereferenced `self` after loop.exec() had let the user destroy the panel.
struct DeployGuard {
StrategyBuilderPanel* self;
+ bool armed = true;
~DeployGuard() {
+ if (!armed)
+ return;
self->deploying_ = false;
if (self->deploy_btn_)
self->deploy_btn_->setEnabled(true);
@@ -741,66 +786,92 @@ void StrategyBuilderPanel::on_deploy() {
underlying_combo_ ? underlying_combo_->currentText() : QString(),
expiry_mode_combo_ ? expiry_mode_combo_->currentData().toString() : QString());
}
- if (dialog->exec() == QDialog::Accepted) {
- // Take the dialog's values verbatim — what the user reviewed is what deploys.
- auto deployment = dialog->deployment();
-
- // Sanity check (non-blocking, bounded): warn if a rule can't fire at the
- // current price — e.g. 'crosses_above 280.45' on a stock trading at 1204.
- const double cur_price =
- fetch_quote_ltp(deployment.broker_id, deployment.broker_account_id, deployment.symbol, 2500);
- if (cur_price > 0) {
- QStringList warns;
- scan_unreachable(strat.entry_conditions, tr("Entry"), cur_price, warns);
- scan_unreachable(strat.exit_conditions, tr("Exit"), cur_price, warns);
- if (!warns.isEmpty()) {
- const auto btn =
- QMessageBox::warning(this, tr("Deploy — check conditions"),
- tr("%1 is at %2, but some rules may never trigger:\n\n%3\n\nDeploy anyway?")
- .arg(deployment.symbol)
- .arg(cur_price, 0, 'f', 2)
- .arg(warns.join("\n\n")),
- QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
- if (btn != QMessageBox::Yes) {
- dialog->deleteLater();
- return;
- }
- }
+ const bool accepted = (dialog->exec() == QDialog::Accepted);
+ if (!accepted) {
+ dialog->deleteLater();
+ return;
+ }
+ // Take the dialog's values verbatim — what the user reviewed is what deploys.
+ auto deployment = dialog->deployment();
+ dialog->deleteLater(); // nothing below reads the dialog again
+
+ // Sanity check (non-blocking, bounded): warn if a rule can't fire at the
+ // current price — e.g. 'crosses_above 280.45' on a stock trading at 1204.
+ // The broker probe is off-thread and everything after it lives in the queued
+ // continuation, so the GUI thread is never parked (§P1) and a panel destroyed
+ // mid-probe simply drops the rest instead of writing through freed memory (§P8).
+ deploy_guard.armed = false; // the continuation owns the release from here
+
+ // Releases the click gate on whichever branch the continuation leaves
+ // through. Held as a QPointer, not a raw pointer: the confirmation boxes
+ // run nested event loops, so the panel can still disappear underneath us.
+ struct ReleaseGate {
+ QPointer<StrategyBuilderPanel> panel;
+ ~ReleaseGate() {
+ if (!panel)
+ return;
+ panel->deploying_ = false;
+ if (panel->deploy_btn_)
+ panel->deploy_btn_->setEnabled(true);
}
+ };
- // Confirm before deploying an exact duplicate of an already-running setup.
- if (algo_ns::AlgoEngine::instance().has_active_duplicate(deployment.strategy_id, deployment.symbol,
- deployment.mode, deployment.entry_side)) {
- const auto btn = QMessageBox::question(
- this, tr("Already deployed"),
- tr("An identical deployment is already running:\n\n%1 · %2 · %3 · %4\n\n"
- "Deploy another copy anyway?")
- .arg(deployment.strategy_name, deployment.symbol, deployment.mode.toUpper(), deployment.entry_side),
- QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
- if (btn != QMessageBox::Yes) {
- dialog->deleteLater();
+ QPointer<StrategyBuilderPanel> self = this;
+ fetch_quote_ltp_async(
+ deployment.broker_id, deployment.broker_account_id, deployment.symbol, 2500, this,
+ [self, strat, deployment](double cur_price) {
+ if (!self)
return;
+ ReleaseGate release_gate{self};
+
+ if (cur_price > 0) {
+ QStringList warns;
+ scan_unreachable(strat.entry_conditions, tr("Entry"), cur_price, warns);
+ scan_unreachable(strat.exit_conditions, tr("Exit"), cur_price, warns);
+ if (!warns.isEmpty()) {
+ const auto btn = QMessageBox::warning(
+ self.data(), tr("Deploy — check conditions"),
+ tr("%1 is at %2, but some rules may never trigger:\n\n%3\n\nDeploy anyway?")
+ .arg(deployment.symbol)
+ .arg(cur_price, 0, 'f', 2)
+ .arg(warns.join("\n\n")),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (!self || btn != QMessageBox::Yes)
+ return;
+ }
+ }
+
+ // Confirm before deploying an exact duplicate of an already-running setup.
+ if (algo_ns::AlgoEngine::instance().has_active_duplicate(deployment.strategy_id, deployment.symbol,
+ deployment.mode, deployment.entry_side)) {
+ const auto btn =
+ QMessageBox::question(self.data(), tr("Already deployed"),
+ tr("An identical deployment is already running:\n\n%1 · %2 · %3 · %4\n\n"
+ "Deploy another copy anyway?")
+ .arg(deployment.strategy_name, deployment.symbol,
+ deployment.mode.toUpper(), deployment.entry_side),
+ QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
+ if (!self || btn != QMessageBox::Yes)
+ return;
}
- }
- // Save strategy first
- services::algo::AlgoTradingService::instance().save_strategy(strat);
+ // Save strategy first
+ services::algo::AlgoTradingService::instance().save_strategy(strat);
- LOG_INFO("AlgoTrading", QString("Deploy requested: id=%1 strategy='%2' symbol=%3 mode=%4 backend=%5 "
- "broker=%6 acct=%7 qty=%8")
- .arg(deployment.id, strat.name, deployment.symbol, deployment.mode,
- deployment.backend, deployment.broker_id, deployment.broker_account_id)
- .arg(deployment.quantity));
+ LOG_INFO("AlgoTrading", QString("Deploy requested: id=%1 strategy='%2' symbol=%3 mode=%4 backend=%5 "
+ "broker=%6 acct=%7 qty=%8")
+ .arg(deployment.id, strat.name, deployment.symbol, deployment.mode,
+ deployment.backend, deployment.broker_id, deployment.broker_account_id)
+ .arg(deployment.quantity));
- // Deploy via C++ engine (persists the row, then starts the runner). Feedback
- // is the jump to the Dashboard below — NOT a label on the backtest card, which
- // is unrelated to deployment and read as "stuck on Deploying…".
- algo_ns::AlgoEngine::instance().start_deployment(deployment, strat);
+ // Deploy via C++ engine (persists the row, then starts the runner). Feedback
+ // is the jump to the Dashboard below — NOT a label on the backtest card, which
+ // is unrelated to deployment and read as "stuck on Deploying…".
+ algo_ns::AlgoEngine::instance().start_deployment(deployment, strat);
- // Tell the parent screen to switch to the Dashboard and refresh.
- emit deployed();
- }
- dialog->deleteLater();
+ // Tell the parent screen to switch to the Dashboard and refresh.
+ emit self->deployed();
+ });
}
void StrategyBuilderPanel::load_template(int index) {
diff --git a/fincept-qt/src/screens/auth/PricingScreen.cpp b/fincept-qt/src/screens/auth/PricingScreen.cpp
index 1f42f759f..efcf65009 100644
--- a/fincept-qt/src/screens/auth/PricingScreen.cpp
+++ b/fincept-qt/src/screens/auth/PricingScreen.cpp
@@ -5,6 +5,7 @@
#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "ui/theme/Theme.h"
+#include "ui/widgets/EnterprisePromo.h"
#include <QApplication>
#include <QDesktopServices>
@@ -97,6 +98,15 @@ void PricingScreen::build_ui() {
QString("color: %1; font-size: 12px; background: transparent; %2").arg(ui::colors::TEXT_SECONDARY()).arg(MF));
vl->addWidget(user_info_label_);
+ // ── Enterprise banner ────────────────────────────────────────────────────
+ // The cards below are the open-source build's own credit tiers. Enterprise
+ // is a separate product on a separate backend, so it never appears in the
+ // fetched plan list — surface it here rather than leave the pricing screen
+ // as the one place that omits it.
+ vl->addSpacing(4);
+ vl->addWidget(ui::make_enterprise_banner(content));
+ vl->addSpacing(4);
+
// ── Loading ──────────────────────────────────────────────────────────────
loading_label_ = new QLabel;
loading_label_->setAlignment(Qt::AlignCenter);
diff --git a/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp b/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp
index 5e020a230..2505e2ba1 100644
--- a/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatAgentPanel.cpp
@@ -4,6 +4,7 @@
#include "screens/chat_mode/ChatModeService.h"
#include "ui/theme/Theme.h"
+#include <QEvent>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QJsonArray>
@@ -14,6 +15,31 @@
namespace fincept::chat_mode {
+// Drives the panel's data load off visibility instead of construction (§P3).
+//
+// The five refresh_*() calls used to sit in the constructor. WindowFrame builds
+// ChatModeScreen eagerly at startup, so they fired five HTTP GETs before first
+// paint — each allocating a 15 s timeout QTimer, and all of them pre-login, so
+// they went out with an empty X-API-Key and 401'd. Pure waste that also delayed
+// first paint.
+//
+// The natural home is a showEvent() override; this filter is the identical hook
+// installed from the .cpp so ChatAgentPanel.h stays untouched. Fold it into a
+// real `void showEvent(QShowEvent*) override` when the header is next edited.
+// Lives at file scope so MOC doesn't choke on local classes.
+class AgentPanelShowLoader : public QObject {
+ public:
+ explicit AgentPanelShowLoader(ChatAgentPanel* panel) : QObject(panel), panel_(panel) {
+ panel->installEventFilter(this);
+ }
+
+ protected:
+ bool eventFilter(QObject* watched, QEvent* event) override;
+
+ private:
+ ChatAgentPanel* panel_ = nullptr;
+};
+
static QString list_ss() {
return QString("QListWidget{background:%1;border:1px solid %2;color:%3;"
"font-size:12px;font-family:'Consolas','Courier New',monospace;"
@@ -42,13 +68,23 @@ static QString hint_ss() {
// ── Constructor ───────────────────────────────────────────────────────────────
+bool AgentPanelShowLoader::eventFilter(QObject* watched, QEvent* event) {
+ if (watched == panel_ && event->type() == QEvent::Show) {
+ panel_->refresh_memory();
+ panel_->refresh_schedules();
+ panel_->refresh_tasks();
+ panel_->refresh_mcp_servers();
+ panel_->refresh_monitors();
+ }
+ return QObject::eventFilter(watched, event);
+}
+
ChatAgentPanel::ChatAgentPanel(QWidget* parent) : QWidget(parent) {
build_ui();
- refresh_memory();
- refresh_schedules();
- refresh_tasks();
- refresh_mcp_servers();
- refresh_monitors();
+ // No data load here — AgentPanelShowLoader runs it on first (and every)
+ // show, so nothing hits the network until the user is actually in chat
+ // mode and logged in. See the comment on that class above.
+ new AgentPanelShowLoader(this); // parented to this; destroyed with the panel
}
// ── Build UI ──────────────────────────────────────────────────────────────────
@@ -517,11 +553,15 @@ void ChatAgentPanel::on_add_memory() {
if (!ok)
return;
- ChatModeService::instance().save_memory(key.trimmed(), value.trimmed(), type, [this](bool saved_ok, QString err) {
- if (!saved_ok)
- LOG_WARN("ChatAgentPanel", "Save memory failed: " + err);
- refresh_memory();
- });
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().save_memory(key.trimmed(), value.trimmed(), type,
+ [this, self](bool saved_ok, QString err) {
+ if (!self)
+ return;
+ if (!saved_ok)
+ LOG_WARN("ChatAgentPanel", "Save memory failed: " + err);
+ refresh_memory();
+ });
}
void ChatAgentPanel::on_delete_memory() {
@@ -532,7 +572,10 @@ void ChatAgentPanel::on_delete_memory() {
if (QMessageBox::question(this, tr("Delete Memory"), tr("Delete \"%1\"?").arg(key),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
- ChatModeService::instance().delete_memory(key, [this](bool ok, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().delete_memory(key, [this, self](bool ok, QString err) {
+ if (!self)
+ return;
if (!ok)
LOG_WARN("ChatAgentPanel", "Delete memory failed: " + err);
refresh_memory();
@@ -543,7 +586,10 @@ void ChatAgentPanel::on_clear_all_memory() {
if (QMessageBox::question(this, tr("Clear Memory"), tr("Delete ALL memory entries?"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
- ChatModeService::instance().clear_all_memory([this](bool ok, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().clear_all_memory([this, self](bool ok, QString err) {
+ if (!self)
+ return;
if (!ok)
LOG_WARN("ChatAgentPanel", "Clear memory failed: " + err);
refresh_memory();
@@ -563,8 +609,11 @@ void ChatAgentPanel::on_add_schedule() {
if (!ok || cron.trimmed().isEmpty())
return;
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().create_schedule(query.trimmed(), cron.trimmed(), {},
- [this](bool created_ok, AgentSchedule, QString err) {
+ [this, self](bool created_ok, AgentSchedule, QString err) {
+ if (!self)
+ return;
if (!created_ok)
LOG_WARN("ChatAgentPanel", "Create schedule failed: " + err);
refresh_schedules();
@@ -575,11 +624,15 @@ void ChatAgentPanel::on_delete_schedule() {
auto* item = sched_list_->currentItem();
if (!item)
return;
- ChatModeService::instance().delete_schedule(item->data(Qt::UserRole).toString(), [this](bool ok, QString err) {
- if (!ok)
- LOG_WARN("ChatAgentPanel", "Delete schedule failed: " + err);
- refresh_schedules();
- });
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().delete_schedule(item->data(Qt::UserRole).toString(),
+ [this, self](bool ok, QString err) {
+ if (!self)
+ return;
+ if (!ok)
+ LOG_WARN("ChatAgentPanel", "Delete schedule failed: " + err);
+ refresh_schedules();
+ });
}
void ChatAgentPanel::on_toggle_schedule() {
@@ -588,7 +641,10 @@ void ChatAgentPanel::on_toggle_schedule() {
return;
const QString id = item->data(Qt::UserRole).toString();
const QString status = item->data(Qt::UserRole + 1).toString();
- auto cb = [this](bool ok, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ auto cb = [this, self](bool ok, QString err) {
+ if (!self)
+ return;
if (!ok)
LOG_WARN("ChatAgentPanel", "Toggle schedule failed: " + err);
refresh_schedules();
@@ -609,7 +665,10 @@ void ChatAgentPanel::on_cancel_task() {
auto* item = task_list_->currentItem();
if (!item)
return;
- ChatModeService::instance().cancel_task(item->data(Qt::UserRole).toString(), [this](bool ok, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().cancel_task(item->data(Qt::UserRole).toString(), [this, self](bool ok, QString err) {
+ if (!self)
+ return;
if (!ok)
LOG_WARN("ChatAgentPanel", "Cancel task failed: " + err);
refresh_tasks();
@@ -620,8 +679,11 @@ void ChatAgentPanel::on_view_task_detail() {
auto* item = task_list_->currentItem();
if (!item)
return;
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().get_task(
- item->data(Qt::UserRole).toString(), [this](bool ok, AgentTask task, QString err) {
+ item->data(Qt::UserRole).toString(), [this, self](bool ok, AgentTask task, QString err) {
+ if (!self)
+ return;
if (!ok) {
QMessageBox::warning(this, tr("Task"), tr("Failed: %1").arg(err));
return;
@@ -645,8 +707,11 @@ void ChatAgentPanel::on_send_feedback() {
if (!ok || feedback.trimmed().isEmpty())
return;
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().send_task_feedback(item->data(Qt::UserRole).toString(), feedback.trimmed(),
- [this](bool sent_ok, QString err) {
+ [this, self](bool sent_ok, QString err) {
+ if (!self)
+ return;
if (!sent_ok)
LOG_WARN("ChatAgentPanel", "Feedback failed: " + err);
else
@@ -694,8 +759,11 @@ void ChatAgentPanel::on_add_mcp_server() {
config["url"] = url.trimmed();
}
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().add_mcp_server(
- name.trimmed(), config, [this](bool added_ok, McpServer srv, QString err) {
+ name.trimmed(), config, [this, self](bool added_ok, McpServer srv, QString err) {
+ if (!self)
+ return;
if (!added_ok) {
QMessageBox::warning(this, tr("MCP Server"), tr("Failed: %1").arg(err));
return;
@@ -714,7 +782,10 @@ void ChatAgentPanel::on_delete_mcp_server() {
if (QMessageBox::question(this, tr("Remove Server"), tr("Remove \"%1\"?").arg(name),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
return;
- ChatModeService::instance().delete_mcp_server(name, [this](bool ok, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().delete_mcp_server(name, [this, self](bool ok, QString err) {
+ if (!self)
+ return;
if (!ok)
LOG_WARN("ChatAgentPanel", "Delete MCP server failed: " + err);
refresh_mcp_servers();
@@ -722,8 +793,11 @@ void ChatAgentPanel::on_delete_mcp_server() {
}
void ChatAgentPanel::on_refresh_mcp_servers() {
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().refresh_mcp_servers(
- [this](bool ok, QVector<McpServer> servers, int total_tools, QString err) {
+ [this, self](bool ok, QVector<McpServer> servers, int total_tools, QString err) {
+ if (!self)
+ return;
if (!ok) {
LOG_WARN("ChatAgentPanel", "Refresh MCP failed: " + err);
return;
@@ -800,9 +874,12 @@ void ChatAgentPanel::on_add_monitor() {
return;
trigger_config["condition"] = cond;
+ QPointer<ChatAgentPanel> self = this;
ChatModeService::instance().create_monitor(
name.trimmed(), source_type, source_config, trigger_config, analysis.trimmed(), interval, {},
- [this](bool created_ok, AgentMonitor, QString err) {
+ [this, self](bool created_ok, AgentMonitor, QString err) {
+ if (!self)
+ return;
if (!created_ok)
QMessageBox::warning(this, tr("Monitor"), tr("Failed: %1").arg(err));
refresh_monitors();
@@ -816,11 +893,15 @@ void ChatAgentPanel::on_delete_monitor() {
if (QMessageBox::question(this, tr("Delete Monitor"), tr("Delete?"), QMessageBox::Yes | QMessageBox::No) !=
QMessageBox::Yes)
return;
- ChatModeService::instance().delete_monitor(item->data(Qt::UserRole).toString(), [this](bool ok, QString err) {
- if (!ok)
- LOG_WARN("ChatAgentPanel", "Delete monitor failed: " + err);
- refresh_monitors();
- });
+ QPointer<ChatAgentPanel> self = this;
+ ChatModeService::instance().delete_monitor(item->data(Qt::UserRole).toString(),
+ [this, self](bool ok, QString err) {
+ if (!self)
+ return;
+ if (!ok)
+ LOG_WARN("ChatAgentPanel", "Delete monitor failed: " + err);
+ refresh_monitors();
+ });
}
void ChatAgentPanel::on_toggle_monitor() {
@@ -829,7 +910,10 @@ void ChatAgentPanel::on_toggle_monitor() {
return;
const QString id = item->data(Qt::UserRole).toString();
const QString status = item->data(Qt::UserRole + 1).toString();
- auto cb = [this](bool ok, QString err) {
+ QPointer<ChatAgentPanel> self = this;
+ auto cb = [this, self](bool ok, QString err) {
+ if (!self)
+ return;
if (!ok)
LOG_WARN("ChatAgentPanel", "Toggle monitor failed: " + err);
refresh_monitors();
diff --git a/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp b/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp
index 0bd75593b..e2ff1c501 100644
--- a/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatSessionPanel.cpp
@@ -18,7 +18,11 @@ namespace fincept::chat_mode {
ChatSessionPanel::ChatSessionPanel(QWidget* parent) : QWidget(parent) {
build_ui();
- refresh_sessions();
+ // No refresh_sessions() here (§P3). WindowFrame builds ChatModeScreen
+ // eagerly at startup, so this GET fired before first paint and before
+ // login — an empty X-API-Key that could only 401. ChatModeScreen::showEvent
+ // already calls session_panel_->refresh_sessions() on every entry into chat
+ // mode, which is the only moment the list is actually looked at.
}
void ChatSessionPanel::build_ui() {
diff --git a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp
index 2dc1f3ac5..4ad8228dd 100644
--- a/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp
+++ b/fincept-qt/src/screens/chat_mode/TerminalToolBridge.cpp
@@ -14,21 +14,40 @@
namespace fincept::chat_mode {
-// Categories that are UI-only and should not be exposed to Finagent
-const QStringList TerminalToolBridge::EXCLUDED_CATEGORIES = {"navigation", "system", "settings"};
+// Categories that are UI-only and should not be exposed to Finagent.
+// `profile` and `data-sources` are here because both hand back credential
+// material verbatim (profile_get_api_key returns the session API key;
+// ds_list_connections mapped every saved connector's config — including
+// passwords and tokens — with no arguments at all, i.e. a one-call bulk
+// credential dump). Neither belongs in a cloud agent's tool catalog.
+const QStringList TerminalToolBridge::EXCLUDED_CATEGORIES = {"navigation", "system", "settings", "profile",
+ "data-sources"};
// Real money (live broker order placement/cancel/close) and local process
// control (install/start external MCP servers). See the header for why these
// fail closed on this path but not on the local-agent path.
const QStringList TerminalToolBridge::BLOCKED_CATEGORIES = {"live-trading", "mcp-servers"};
-// Arbitrary local code execution + irreversible file deletion. Their categories
-// ("analytics", "file_manager") also contain read-only tools worth keeping.
+// Arbitrary local code execution + irreversible file deletion, plus
+// download_managed_file: it writes a caller-named path on the local disk, and
+// chained with write_managed_text_file (whose bytes the model authors) that is
+// a write-what-where primitive. It is confined to the export directory now,
+// but a remote agent has no business writing local files at all.
const QStringList TerminalToolBridge::BLOCKED_TOOLS = {"run_python_script", "delete_managed_file",
- "bulk_delete_managed_files"};
+ "bulk_delete_managed_files", "download_managed_file"};
bool TerminalToolBridge::is_remote_blocked(const QString& name, const QString& category) {
- return BLOCKED_CATEGORIES.contains(category) || BLOCKED_TOOLS.contains(name);
+ // EXCLUDED_CATEGORIES was previously applied ONLY while building the
+ // catalog in register_tools(). Catalog-time filtering is cosmetic: the
+ // backend hands us a tool NAME to run, so anything the model already knows
+ // the name of (a stale catalog, a guess, an injected instruction) executed
+ // regardless. Folding the exclusion in here makes both the catalog and the
+ // dispatch path (execute_call) enforce one list.
+ // "ai-chat" is excluded by register_tools() as a recursion guard (the cloud
+ // agent driving the chat LLM that is driving it); mirror that at dispatch.
+ return category == QLatin1String("ai-chat") || category == QLatin1String("ai_chat") ||
+ EXCLUDED_CATEGORIES.contains(category) || BLOCKED_CATEGORIES.contains(category) ||
+ BLOCKED_TOOLS.contains(name);
}
TerminalToolBridge::TerminalToolBridge(QObject* parent) : QObject(parent) {
@@ -168,12 +187,13 @@ void TerminalToolBridge::execute_call(const QString& call_id, const QString& too
const QString tool_category = tool_info ? tool_info->category : QString();
if (is_remote_blocked(local_name, tool_category)) {
LOG_WARN("TerminalToolBridge",
- QString("Refused remote tool '%1' (category '%2') — real-money / arbitrary-code tools are not "
- "available to the cloud agent")
+ QString("Refused remote tool '%1' (category '%2') — real-money / arbitrary-code / credential / "
+ "UI-only tools are not available to the cloud agent")
.arg(local_name, tool_category));
const auto refusal = mcp::ToolResult::fail(
- QString("Tool '%1' is not available to the remote agent. It moves real funds or executes local "
- "code and must be run by the user from the terminal UI.")
+ QString("Tool '%1' is not available to the remote agent. It moves real funds, executes local code, "
+ "reads stored credentials, or drives the local UI, and must be run by the user from the "
+ "terminal itself.")
.arg(local_name));
ChatModeService::instance().submit_tool_result(call_id, refusal.to_json(), [](bool, QString) {});
emit bridge_error(tr("Blocked unsafe remote tool call: %1").arg(local_name));
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
index 75303ace8..d80bee698 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
@@ -77,6 +77,15 @@ void CryptoTradingScreen::showEvent(QShowEvent* event) {
clock_timer_->start();
if (ws_flush_timer_)
ws_flush_timer_->start();
+ // Re-attach the hub WS subscriptions dropped by hideEvent (§D3). Same
+ // topic set: hub_subscribe_topics() derives every topic from the current
+ // exchange_id_ / selected_symbol_ / watchlist_symbols_ / chart timeframe,
+ // none of which hideEvent touches. Gated on initialized_ so the very
+ // first show doesn't subscribe ahead of init_exchange() — that deferred
+ // call owns the initial subscribe and would immediately tear this one
+ // down anyway.
+ if (initialized_)
+ hub_subscribe_topics();
// Restart the live positions/P&L poller if we're in LIVE mode. hideEvent
// stopped it and it was only ever (re)started from the mode toggle, so
// tabbing away and back froze live P&L until the mode was re-toggled.
@@ -104,6 +113,14 @@ void CryptoTradingScreen::hideEvent(QHideEvent* event) {
if (ws_flush_timer_)
ws_flush_timer_->stop();
+ // Drop the hub WS subscriptions (§D3). Stopping ws_flush_timer_ above only
+ // stops the *drain* — the subscription callbacks keep appending to
+ // pending_trades_ / pending_candles_ at exchange tick rate for as long as
+ // the screen stays hidden, so the buffers grew without bound and the first
+ // flush after re-showing dumped the whole accumulation into bottom_panel_
+ // in one multi-second freeze. showEvent re-subscribes the same topic set.
+ hub_unsubscribe_topics();
+
// Reset WS/state trackers so apply_feed_mode and update_clock re-emit
// their state when the tab becomes visible again.
last_ws_state_ = -1;
@@ -534,6 +551,11 @@ void CryptoTradingScreen::hub_subscribe_topics() {
e.side = td.side;
e.price = td.price;
e.amount = td.amount;
+ // Hard cap — belt and braces against the drain ever stalling
+ // (hidden screen, blocked event loop). Newest wins: the time &
+ // sales tape only ever renders the most recent rows anyway.
+ if (self->pending_trades_.size() >= kMaxPendingTrades)
+ self->pending_trades_.remove(0, self->pending_trades_.size() - kMaxPendingTrades + 1);
self->pending_trades_.append(e);
});
@@ -545,6 +567,10 @@ void CryptoTradingScreen::hub_subscribe_topics() {
[self](const fincept::trading::Candle& c) {
if (!self)
return;
+ // Same cap rationale as pending_trades_ above.
+ if (self->pending_candles_.size() >= kMaxPendingCandles)
+ self->pending_candles_.remove(
+ 0, self->pending_candles_.size() - kMaxPendingCandles + 1);
self->pending_candles_.append(c);
});
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h
index a578be192..46e0c5a55 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.h
@@ -205,6 +205,13 @@ class CryptoTradingScreen : public QWidget, public IStatefulScreen, public IGrou
trading::OrderBookData pending_orderbook_;
bool has_pending_orderbook_ = false;
+ // Hard caps on the two unbounded append-only WS buffers. The drain
+ // (flush_ws_updates, 10fps) normally empties them every tick, but any
+ // stall — hidden screen, blocked event loop — used to let them grow at
+ // exchange tick rate forever. Oldest entries are dropped on overflow.
+ static constexpr int kMaxPendingTrades = 2000;
+ static constexpr int kMaxPendingCandles = 2000;
+
// Candle coalescing — append closed candles in order, keep the latest
// in-progress candle separately so we render partial bars without
// flooding the chart on every tick.
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
index c36189983..267c6dbfa 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_AsyncFetch.cpp
@@ -106,7 +106,12 @@ void CryptoTradingScreen::async_fetch_candles(const QString& symbol, const QStri
void CryptoTradingScreen::async_fetch_live_positions() {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ // Snapshot the symbol on the UI thread. Reading self->selected_symbol_
+ // from the worker is a torn read of an implicitly-shared QString being
+ // written by the UI thread, and the `if (!self)` above it is a TOCTOU —
+ // the widget can die between the check and the dereference.
+ const QString symbol = selected_symbol_;
+ (void)QtConcurrent::run([self, symbol]() {
if (!self) {
// Widget destroyed before dispatch — no counter to decrement.
return;
@@ -116,7 +121,7 @@ void CryptoTradingScreen::async_fetch_live_positions() {
// then returns early on every tick and LIVE data never updates again.
QJsonObject result;
try {
- result = ExchangeService::instance().fetch_positions_live(self->selected_symbol_);
+ result = ExchangeService::instance().fetch_positions_live(symbol);
} catch (...) {
LOG_WARN("CryptoTrading", "fetch_positions_live threw");
}
@@ -135,12 +140,13 @@ void CryptoTradingScreen::async_fetch_live_positions() {
void CryptoTradingScreen::async_fetch_live_orders() {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ const QString symbol = selected_symbol_; // snapshot on the UI thread — see above
+ (void)QtConcurrent::run([self, symbol]() {
if (!self)
return;
QJsonObject result;
try {
- result = ExchangeService::instance().fetch_open_orders_live(self->selected_symbol_);
+ result = ExchangeService::instance().fetch_open_orders_live(symbol);
} catch (...) {
LOG_WARN("CryptoTrading", "fetch_open_orders_live threw");
}
@@ -225,12 +231,13 @@ void CryptoTradingScreen::async_fetch_live_balance() {
void CryptoTradingScreen::async_fetch_my_trades() {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ const QString symbol = selected_symbol_; // snapshot on the UI thread — see above
+ (void)QtConcurrent::run([self, symbol]() {
if (!self)
return;
QJsonObject result;
try {
- result = ExchangeService::instance().fetch_my_trades(self->selected_symbol_);
+ result = ExchangeService::instance().fetch_my_trades(symbol);
} catch (...) {
LOG_WARN("CryptoTrading", "fetch_my_trades threw");
}
@@ -248,10 +255,11 @@ void CryptoTradingScreen::async_fetch_my_trades() {
void CryptoTradingScreen::async_fetch_trading_fees() {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ const QString symbol = selected_symbol_; // snapshot on the UI thread — see above
+ (void)QtConcurrent::run([self, symbol]() {
if (!self)
return;
- auto result = ExchangeService::instance().fetch_trading_fees(self->selected_symbol_);
+ auto result = ExchangeService::instance().fetch_trading_fees(symbol);
QMetaObject::invokeMethod(
self,
[self, result]() {
@@ -265,10 +273,11 @@ void CryptoTradingScreen::async_fetch_trading_fees() {
void CryptoTradingScreen::async_fetch_mark_price() {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ const QString symbol = selected_symbol_; // snapshot on the UI thread — see above
+ (void)QtConcurrent::run([self, symbol]() {
if (!self)
return;
- auto mp = ExchangeService::instance().fetch_mark_price(self->selected_symbol_);
+ auto mp = ExchangeService::instance().fetch_mark_price(symbol);
QMetaObject::invokeMethod(
self,
[self, mp]() {
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
index ca58732ef..3e7a443b9 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp
@@ -401,10 +401,15 @@ void CryptoTradingScreen::on_cancel_order(const QString& order_id) {
}
} else {
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self, order_id]() {
+ // Snapshot the symbol on the UI thread. Reading self->selected_symbol_
+ // from the worker races the UI thread's writes — a symbol switch
+ // between dispatch and dereference would cancel against the wrong
+ // market, and the `if (!self)` guard above is a TOCTOU besides.
+ const QString symbol = selected_symbol_;
+ (void)QtConcurrent::run([self, order_id, symbol]() {
if (!self)
return;
- ExchangeService::instance().cancel_exchange_order(order_id, self->selected_symbol_);
+ ExchangeService::instance().cancel_exchange_order(order_id, symbol);
QMetaObject::invokeMethod(
self,
[self]() {
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Refresh.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Refresh.cpp
index e7fe64bd6..b53cba782 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Refresh.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen_Refresh.cpp
@@ -235,14 +235,15 @@ void CryptoTradingScreen::refresh_orderbook() {
if (!initialized_)
return;
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ const QString symbol = selected_symbol_; // snapshot on the UI thread — see refresh_ticker()
+ (void)QtConcurrent::run([self, symbol]() {
if (!self)
return;
- auto ob = ExchangeService::instance().fetch_orderbook(self->selected_symbol_, OB_MAX_DISPLAY_LEVELS);
+ auto ob = ExchangeService::instance().fetch_orderbook(symbol, OB_MAX_DISPLAY_LEVELS);
QMetaObject::invokeMethod(
self,
- [self, ob]() {
- if (!self)
+ [self, symbol, ob]() {
+ if (!self || self->selected_symbol_ != symbol)
return;
self->orderbook_->set_data(ob.bids, ob.asks, ob.spread, ob.spread_pct);
self->bottom_panel_->set_depth_data(ob.bids, ob.asks, ob.spread, ob.spread_pct);
@@ -309,10 +310,11 @@ void CryptoTradingScreen::refresh_watchlist() {
if (!initialized_)
return;
QPointer<CryptoTradingScreen> self = this;
- (void)QtConcurrent::run([self]() {
+ const QStringList symbols = watchlist_symbols_; // snapshot on the UI thread — see refresh_ticker()
+ (void)QtConcurrent::run([self, symbols]() {
if (!self)
return;
- auto tickers = ExchangeService::instance().fetch_tickers(self->watchlist_symbols_);
+ auto tickers = ExchangeService::instance().fetch_tickers(symbols);
QMetaObject::invokeMethod(
self,
[self, tickers]() {
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
index cd2ce446f..1fe467141 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
@@ -1,5 +1,6 @@
#include "screens/dashboard/DashboardScreen.h"
+#include "core/logging/Logger.h"
#include "datahub/DataHub.h"
#include "datahub/DataHubMetaTypes.h"
#include "screens/dashboard/canvas/AddWidgetDialog.h"
@@ -387,11 +388,24 @@ namespace {
// so legacy blobs are still decoded (with empty per-item config).
constexpr quint32 kDashLayoutMagic = 0xDA58A101u;
constexpr quint32 kDashLayoutVersion = 1;
+
+/// Dynamic-property guard: set when restore_layout() could not *read* the
+/// stored blob (as opposed to reading a genuinely absent/corrupt one). While
+/// it is set, save_layout() refuses to write, because the layout on screen is
+/// the built-in default rather than anything the user arranged — persisting it
+/// would replace their real dashboard. Cleared by the next successful load.
+constexpr const char* kDashLayoutLoadFailedProp = "fincept_dash_layout_load_failed";
} // namespace
void DashboardScreen::save_layout() {
save_timer_->stop();
+ if (property(kDashLayoutLoadFailedProp).toBool()) {
+ LOG_WARN("Dashboard", "Skipping layout save — the stored layout could not be read this session, so the "
+ "on-screen default must not overwrite it");
+ return;
+ }
+
GridLayout layout = canvas_->current_layout();
// Serialize: magic+version, cols, row_h, margin, item count, then each item
@@ -425,7 +439,39 @@ void DashboardScreen::restore_layout() {
if (!self)
return;
- if (result.is_err() || result.value().isEmpty()) {
+ if (result.is_err()) {
+ LOG_ERROR("Dashboard",
+ QString("settings read failed for 'dashboard_canvas_layout' — rendering the default "
+ "layout read-only, leaving the stored layout untouched: %1")
+ .arg(QString::fromStdString(result.error())));
+ // Degrade read-only: the user still gets a usable dashboard,
+ // but the layout_changed → save_timer_ → set() chain that
+ // apply_template() is about to trigger is disarmed.
+ self->setProperty(kDashLayoutLoadFailedProp, true);
+ self->build_default_layout();
+
+ // Say so. Suppressing the write stops the saved layout being
+ // destroyed, but on its own it just swaps one silent failure
+ // for another: the user sees a default dashboard, rearranges
+ // it, and none of it persists — with only a LOG_WARN to
+ // explain why. Reuse the toast this screen already owns.
+ if (self->notif_toast_) {
+ fincept::notifications::NotificationRecord rec;
+ rec.request.title = tr("Dashboard layout unavailable");
+ rec.request.message = tr("Your saved layout could not be read, so a default is shown. "
+ "Changes will not be saved this session — restart to retry.");
+ rec.request.level = fincept::notifications::NotifLevel::Warning;
+ self->notif_toast_->show_notification(rec);
+ }
+ return;
+ }
+
+ // The read succeeded, so anything below this point is a genuine
+ // "unset or corrupt" case where writing the default back is the
+ // correct behaviour.
+ self->setProperty(kDashLayoutLoadFailedProp, false);
+
+ if (result.value().isEmpty()) {
self->build_default_layout();
return;
}
diff --git a/fincept-qt/src/screens/dashboard/TickerBar.cpp b/fincept-qt/src/screens/dashboard/TickerBar.cpp
index c03a1a4eb..6e927712b 100644
--- a/fincept-qt/src/screens/dashboard/TickerBar.cpp
+++ b/fincept-qt/src/screens/dashboard/TickerBar.cpp
@@ -28,7 +28,8 @@ static const char* kSettingsCategory = "dashboard";
// Constructor
// ─────────────────────────────────────────────────────────────────────────────
-TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {
+TickerBar::TickerBar(QWidget* parent)
+ : QWidget(parent), ticker_font_(ui::fonts::DATA_FAMILY(), ui::fonts::font_px(-2)), ticker_fm_(ticker_font_) {
setFixedHeight(kEditBarHeight);
setContextMenuPolicy(Qt::DefaultContextMenu);
setAccessibleName(tr("Market ticker"));
@@ -40,6 +41,9 @@ TickerBar::TickerBar(QWidget* parent) : QWidget(parent) {
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this, apply_bg](const ui::ThemeTokens&) {
apply_bg();
+ // Font family/size and every colour are theme tokens, so the
+ // cached measurements go stale with the theme.
+ rebuild_entry_cache();
update();
});
@@ -148,21 +152,38 @@ void TickerBar::save_symbols() {
// set_data — called by DashboardScreen after fetch_quotes returns
// ─────────────────────────────────────────────────────────────────────────────
+// Derives every string, width and colour paintEvent needs, so the paint path is
+// a pure draw. The old code measured each entry here to compute total_width_ and
+// then *discarded* the per-entry widths, forcing paintEvent to re-measure all
+// three segments per entry per pass at 20 fps — roughly 3,000 text-shaping calls
+// a second, forever, on the always-visible dashboard ticker. NewsTickerStrip
+// already caches its widths this way; this brings TickerBar in line.
+void TickerBar::rebuild_entry_cache() {
+ ticker_font_ = QFont(ui::fonts::DATA_FAMILY(), ui::fonts::font_px(-2));
+ ticker_fm_ = QFontMetrics(ticker_font_);
+ symbol_color_ = QColor(ui::colors::WHITE());
+ price_color_ = QColor(ui::colors::GRAY());
+
+ total_width_ = 0;
+ for (auto& e : entries_) {
+ e.price_text = QString::number(e.price, 'f', 2);
+ e.change_text = QString("%1%2%").arg(e.change >= 0 ? "+" : "").arg(e.change, 0, 'f', 2);
+ e.change_col = QColor(ui::change_color(e.change));
+
+ e.symbol_width = ticker_fm_.horizontalAdvance(e.symbol);
+ e.price_width = ticker_fm_.horizontalAdvance(e.price_text);
+ e.change_width = ticker_fm_.horizontalAdvance(e.change_text);
+ e.total_width = e.symbol_width + kSegmentGap + e.price_width + kSegmentGap + e.change_width + kItemSpacing;
+
+ total_width_ += e.total_width;
+ }
+}
+
void TickerBar::set_data(const QVector<Entry>& entries) {
const bool symbols_changed = entries.size() != entries_.size();
entries_ = entries;
- // Cache total width — paintEvent runs every 50ms, no per-frame allocation.
- QFont font(ui::fonts::DATA_FAMILY(), ui::fonts::font_px(-2));
- QFontMetrics fm(font);
- total_width_ = 0;
- for (const auto& e : entries_) {
- const int symbol_w = fm.horizontalAdvance(e.symbol);
- const int price_w = fm.horizontalAdvance(QString::number(e.price, 'f', 2));
- const QString change_str = QString("%1%2%").arg(e.change >= 0 ? "+" : "").arg(e.change, 0, 'f', 2);
- const int change_w = fm.horizontalAdvance(change_str);
- total_width_ += symbol_w + kSegmentGap + price_w + kSegmentGap + change_w + kItemSpacing;
- }
+ rebuild_entry_cache();
// Preserve the scroll position across price updates. set_data() is called
// on EVERY per-symbol hub delivery (rebuild_ticker_from_cache), so zeroing
@@ -284,32 +305,35 @@ void TickerBar::paintEvent(QPaintEvent*) {
QPainter p(this);
p.setRenderHint(QPainter::TextAntialiasing);
- QFont font(ui::fonts::DATA_FAMILY(), ui::fonts::font_px(-2));
- p.setFont(font);
- QFontMetrics fm(font);
+ // Font, metrics, strings, widths and colours all come from the cache built in
+ // rebuild_entry_cache(). Nothing here formats or measures — see P9.
+ p.setFont(ticker_font_);
- const int text_y = (height() + fm.ascent() - fm.descent()) / 2;
+ const int text_y = (height() + ticker_fm_.ascent() - ticker_fm_.descent()) / 2;
+ const int viewport_w = width();
double x = -offset_;
- const int passes = (width() / total_width_) + 2;
+ const int passes = (viewport_w / total_width_) + 2;
for (int pass = 0; pass < passes; ++pass) {
for (const auto& e : entries_) {
- // Symbol — primary text
- p.setPen(QColor(ui::colors::WHITE()));
+ // Skip entries scrolled off either edge. The old loop drew every
+ // entry of every pass regardless of visibility.
+ if (x + e.total_width < 0 || x > viewport_w) {
+ x += e.total_width;
+ continue;
+ }
+
+ p.setPen(symbol_color_);
p.drawText(QPointF(x, text_y), e.symbol);
- x += fm.horizontalAdvance(e.symbol) + kSegmentGap;
-
- // Price — muted
- const QString price_str = QString::number(e.price, 'f', 2);
- p.setPen(QColor(ui::colors::GRAY()));
- p.drawText(QPointF(x, text_y), price_str);
- x += fm.horizontalAdvance(price_str) + kSegmentGap;
-
- // Change — green / red
- const QString change_str = QString("%1%2%").arg(e.change >= 0 ? "+" : "").arg(e.change, 0, 'f', 2);
- p.setPen(QColor(ui::change_color(e.change)));
- p.drawText(QPointF(x, text_y), change_str);
- x += fm.horizontalAdvance(change_str) + kItemSpacing;
+ x += e.symbol_width + kSegmentGap;
+
+ p.setPen(price_color_);
+ p.drawText(QPointF(x, text_y), e.price_text);
+ x += e.price_width + kSegmentGap;
+
+ p.setPen(e.change_col);
+ p.drawText(QPointF(x, text_y), e.change_text);
+ x += e.change_width + kItemSpacing;
}
}
}
diff --git a/fincept-qt/src/screens/dashboard/TickerBar.h b/fincept-qt/src/screens/dashboard/TickerBar.h
index 7880b44ab..4865ef419 100644
--- a/fincept-qt/src/screens/dashboard/TickerBar.h
+++ b/fincept-qt/src/screens/dashboard/TickerBar.h
@@ -1,4 +1,7 @@
#pragma once
+#include <QColor>
+#include <QFont>
+#include <QFontMetrics>
#include <QHideEvent>
#include <QLabel>
#include <QLineEdit>
@@ -18,10 +21,22 @@ class TickerBar : public QWidget {
public:
explicit TickerBar(QWidget* parent = nullptr);
+ /// Callers fill only symbol/price/change; everything below is derived once
+ /// in set_data(). paintEvent runs 20×/s over every entry × every pass, so
+ /// it must not format strings or measure text — see rebuild_entry_cache().
struct Entry {
QString symbol;
double price = 0;
double change = 0;
+
+ // ── Derived (do not set from outside) ──
+ QString price_text;
+ QString change_text;
+ QColor change_col;
+ int symbol_width = 0;
+ int price_width = 0;
+ int change_width = 0;
+ int total_width = 0;
};
void set_data(const QVector<Entry>& entries);
@@ -52,6 +67,10 @@ class TickerBar : public QWidget {
void show_edit_bar();
void hide_edit_bar();
void commit_edit();
+ /// Re-derives font, metrics, per-entry strings/widths/colours and
+ /// total_width_ from entries_. Called on new data and on theme change
+ /// (both font family/size and colours are theme tokens).
+ void rebuild_entry_cache();
// ── Scrolling ──
QVector<Entry> entries_;
@@ -59,6 +78,12 @@ class TickerBar : public QWidget {
double offset_ = 0;
int total_width_ = 0;
+ // ── Cached paint state (never built inside paintEvent — P9) ──
+ QFont ticker_font_;
+ QFontMetrics ticker_fm_;
+ QColor symbol_color_;
+ QColor price_color_;
+
// ── Symbol list ──
QStringList symbols_;
diff --git a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp
index c4405486f..30114ecba 100644
--- a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.cpp
@@ -93,6 +93,19 @@ void LoadingOverlay::attach_to(QWidget* target) {
void LoadingOverlay::set_shimmer_phase(qreal v) {
shimmer_phase_ = v;
+
+ // Rate-gate to P9's 20fps ceiling. The driving QPropertyAnimation loops
+ // forever, and an unconditional update() here repainted at Qt's animation
+ // rate (~60Hz) — while each frame builds four QPainterPaths and four
+ // QLinearGradients under Antialiasing. Every dashboard tile owns one of
+ // these and they are all shimmering simultaneously at startup, which is
+ // exactly when the machine is busiest constructing the dashboard.
+ //
+ // The phase value is still stored every tick, so the animation stays smooth
+ // in value terms; only the repaint is throttled.
+ if (repaint_clock_.isValid() && repaint_clock_.elapsed() < kMinRepaintIntervalMs)
+ return;
+ repaint_clock_.restart();
update();
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h
index 80b7f42c4..cce2f8276 100644
--- a/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h
+++ b/fincept-qt/src/screens/dashboard/widgets/LoadingOverlay.h
@@ -1,5 +1,6 @@
#pragma once
+#include <QElapsedTimer>
#include <QPointer>
#include <QPropertyAnimation>
#include <QWidget>
@@ -88,6 +89,12 @@ class LoadingOverlay : public QWidget {
bool error_mode_ = false;
QString error_text_;
+ /// Repaint budget for the shimmer. The animation ticks at Qt's ~60Hz rate;
+ /// P9 caps timer-driven animation at 20fps, and each shimmer frame builds
+ /// four QPainterPaths + four QLinearGradients under Antialiasing.
+ static constexpr int kMinRepaintIntervalMs = 50;
+ QElapsedTimer repaint_clock_; ///< Throttles set_shimmer_phase() repaints
+
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
diff --git a/fincept-qt/src/screens/dashboard/widgets/NotesWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/NotesWidget.cpp
index 0d113d95c..a169de20e 100644
--- a/fincept-qt/src/screens/dashboard/widgets/NotesWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/NotesWidget.cpp
@@ -138,8 +138,8 @@ void NotesWidget::subscribe_events() {
};
auto& bus = EventBus::instance();
- event_subs_.append(bus.subscribe("notes.created", on_changed));
- event_subs_.append(bus.subscribe("notes.deleted", on_changed));
+ event_subs_.append(bus.subscribe(this, "notes.created", on_changed));
+ event_subs_.append(bus.subscribe(this, "notes.deleted", on_changed));
}
void NotesWidget::unsubscribe_events() {
diff --git a/fincept-qt/src/screens/dashboard/widgets/WebScraperWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/WebScraperWidget.cpp
index d720f06e6..9e641975d 100644
--- a/fincept-qt/src/screens/dashboard/widgets/WebScraperWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/WebScraperWidget.cpp
@@ -41,6 +41,10 @@ namespace {
constexpr qsizetype kMaxRowsRendered = 5000; // safety cap for very large tables
constexpr qsizetype kMaxHtmlBytes = 10 * 1024 * 1024;
+// The URL is user-configured and the body is buffered whole, so bound both the
+// wait and the size. kMaxHtmlBytes is reused deliberately: a response we would
+// refuse to parse is not worth finishing the download for.
+constexpr int kFetchTimeoutMs = 15000;
const char* kDefaultUA = "FinceptTerminal/1.0 (compatible; WebScraperWidget)";
// Decode common HTML entities + numeric char refs. Not exhaustive but covers
@@ -188,9 +192,15 @@ WebScraperWidget::WebScraperWidget(const QJsonObject& cfg, QWidget* parent) : Ba
}
WebScraperWidget::~WebScraperWidget() {
- if (pending_reply_) {
- pending_reply_->abort();
- pending_reply_->deleteLater();
+ // Detach BEFORE aborting. abort() emits finished() synchronously, which runs
+ // handle_reply() on this very stack; that slot clears pending_reply_, so the
+ // old `pending_reply_->deleteLater()` here dereferenced a null QPointer.
+ // Clearing first also makes handle_reply() early-return instead of calling
+ // set_loading()/set_status() on a half-destroyed widget.
+ if (QNetworkReply* r = pending_reply_.data()) {
+ pending_reply_.clear();
+ r->abort();
+ r->deleteLater();
}
}
@@ -338,16 +348,23 @@ void WebScraperWidget::start_fetch() {
set_status(tr("Invalid URL"), true);
return;
}
- if (pending_reply_) {
- pending_reply_->abort();
- pending_reply_->deleteLater();
+ // Same detach-before-abort ordering as the destructor: abort() delivers
+ // finished() synchronously and handle_reply() clears pending_reply_, so
+ // touching it after the abort was a null dereference.
+ if (QNetworkReply* r = pending_reply_.data()) {
pending_reply_.clear();
+ r->abort();
+ r->deleteLater();
}
set_loading(true);
set_status(tr("Fetching…"));
QNetworkRequest req(url);
+ // Without a timeout a slow or half-open endpoint leaves pending_reply_ set
+ // forever, and on_auto_refresh_tick() skips while it is set — so one stuck
+ // fetch permanently disables this widget's auto-refresh.
+ req.setTransferTimeout(kFetchTimeoutMs);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
req.setHeader(QNetworkRequest::UserAgentHeader,
user_agent_.isEmpty() ? QString::fromLatin1(kDefaultUA) : user_agent_);
@@ -357,7 +374,20 @@ void WebScraperWidget::start_fetch() {
for (auto it = headers_.cbegin(); it != headers_.cend(); ++it)
req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());
- pending_reply_ = net_->get(req);
+ QNetworkReply* reply = net_->get(req);
+ pending_reply_ = reply;
+
+ // The whole body is buffered in memory, and the URL is user-configured, so
+ // an oversized endpoint would inflate process RSS without bound. Abort as
+ // soon as either the advertised or the received size crosses the cap.
+ connect(reply, &QNetworkReply::downloadProgress, reply,
+ [reply](qint64 received, qint64 total) {
+ if (received > kMaxHtmlBytes || total > kMaxHtmlBytes) {
+ LOG_WARN("WebScraper", QString("Response exceeds %1 bytes — aborting")
+ .arg(kMaxHtmlBytes));
+ reply->abort();
+ }
+ });
}
void WebScraperWidget::handle_reply(QNetworkReply* reply) {
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen.h b/fincept-qt/src/screens/data_sources/DataSourcesScreen.h
index 9f7382d7c..ed82c10ee 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen.h
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen.h
@@ -82,6 +82,10 @@ class DataSourcesScreen : public QWidget, public fincept::screens::IStatefulScre
void build_category_ladder();
void build_connector_table();
void build_connections_table();
+ /// Single entry point for "the filter text changed" — rebuilds every view
+ /// that depends on it. Driven by `search_debounce_`, never called directly
+ /// from a textChanged signal.
+ void rebuild_all_views();
void update_stats_strip();
void update_provider_ladder();
void update_detail_panel();
@@ -177,6 +181,11 @@ class DataSourcesScreen : public QWidget, public fincept::screens::IStatefulScre
// ── Timers ────────────────────────────────────────────────────────────────
QTimer* clock_timer_ = nullptr;
QTimer* poll_timer_ = nullptr;
+ /// Coalesces keystrokes in either search box into one rebuild. A full
+ /// rebuild walks ~380 connectors and tears down every connection row
+ /// (checkbox + label per row) — doing that per keystroke rebuilt the table
+ /// under the user's cursor mid-word.
+ QTimer* search_debounce_ = nullptr;
// ── State ─────────────────────────────────────────────────────────────────
enum class ViewMode { Gallery, Connections };
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp
index 40ba53b6d..0a12a755f 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Handlers.cpp
@@ -110,7 +110,7 @@ void DataSourcesScreen::on_category_filter(int idx) {
update_action_states();
}
-void DataSourcesScreen::on_search_changed(const QString& /*text*/) {
+void DataSourcesScreen::rebuild_all_views() {
build_category_ladder();
build_connector_table();
build_connections_table();
@@ -119,6 +119,16 @@ void DataSourcesScreen::on_search_changed(const QString& /*text*/) {
update_action_states();
}
+void DataSourcesScreen::on_search_changed(const QString& /*text*/) {
+ // Debounced: every keystroke used to rebuild the ~380-row connector table
+ // and tear down + re-create a QCheckBox and a QLabel for every connection
+ // row, which stole focus and stuttered while typing.
+ if (search_debounce_)
+ search_debounce_->start();
+ else
+ rebuild_all_views();
+}
+
void DataSourcesScreen::on_connector_clicked(const QString& connector_id) {
if (const auto* cfg = find_connector_config(connector_id)) {
selected_connector_id_ = cfg->id;
@@ -308,9 +318,13 @@ void DataSourcesScreen::on_view_mode_toggle() {
}
void DataSourcesScreen::on_connections_search_changed(const QString& text) {
+ // Record the filter immediately (cheap) but debounce the rebuild — same
+ // reasoning as on_search_changed.
conn_search_text_ = text;
- build_connections_table();
- update_stats_strip();
+ if (search_debounce_)
+ search_debounce_->start();
+ else
+ rebuild_all_views();
}
void DataSourcesScreen::on_stat_box_clicked(int stat_index) {
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp
index 71508a22b..689b5a974 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Layout.cpp
@@ -98,6 +98,12 @@ void DataSourcesScreen::setup_ui() {
poll_timer_ = new QTimer(this);
poll_timer_->setInterval(30000);
connect(poll_timer_, &QTimer::timeout, this, &DataSourcesScreen::on_poll_timer);
+
+ // Search debounce — 200 ms after the last keystroke, one rebuild.
+ search_debounce_ = new QTimer(this);
+ search_debounce_->setSingleShot(true);
+ search_debounce_->setInterval(200);
+ connect(search_debounce_, &QTimer::timeout, this, &DataSourcesScreen::rebuild_all_views);
}
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp
index 42e6374ad..b4c9e4b87 100644
--- a/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp
+++ b/fincept-qt/src/screens/data_sources/DataSourcesScreen_Tables.cpp
@@ -27,6 +27,7 @@
#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QHash>
#include <QHeaderView>
#include <QJsonDocument>
#include <QJsonObject>
@@ -115,6 +116,22 @@ void DataSourcesScreen::build_connector_table() {
return;
}
+ // Provider → {total saved, enabled}. Built once here: the per-row calls to
+ // total_connections_for_provider / enabled_connections_for_provider were two
+ // full linear scans of connections_cache_ per surviving row, i.e. O(rows ×
+ // connections) on every keystroke.
+ QHash<QString, QPair<int, int>> conn_counts;
+ conn_counts.reserve(connections_cache_.size());
+ for (const auto& ds : connections_cache_) {
+ const QString key = normalized_provider_key(ds);
+ if (key.isEmpty())
+ continue;
+ auto& entry = conn_counts[key];
+ ++entry.first;
+ if (ds.enabled)
+ ++entry.second;
+ }
+
{
QSignalBlocker blocker(connector_table_);
connector_table_->clearSpans();
@@ -122,8 +139,9 @@ void DataSourcesScreen::build_connector_table() {
for (int row = 0; row < filtered.size(); ++row) {
const auto& cfg = filtered[row];
- const int total_saved = total_connections_for_provider(connections_cache_, cfg.id);
- const int live_saved = enabled_connections_for_provider(connections_cache_, cfg.id);
+ const auto counts = conn_counts.value(cfg.id);
+ const int total_saved = counts.first;
+ const int live_saved = counts.second;
// Col 0: code badge
auto* code_item = make_item(connector_code(cfg), QColor(cfg.color), Qt::AlignCenter);
diff --git a/fincept-qt/src/screens/equity_research/EquityFinancialsTab_Populate.cpp b/fincept-qt/src/screens/equity_research/EquityFinancialsTab_Populate.cpp
index 8a95ff7d9..5691ac2a8 100644
--- a/fincept-qt/src/screens/equity_research/EquityFinancialsTab_Populate.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityFinancialsTab_Populate.cpp
@@ -36,10 +36,42 @@
#include <QVBoxLayout>
#include <QValueAxis>
+#include <algorithm>
+#include <cmath>
+
namespace fincept::screens {
using namespace financials_internal;
+namespace {
+
+/// Rendered in place of any figure the filings did not supply. The tab used to
+/// print a fabricated 0 / 0.00% / "-100.00% YoY" for these.
+const QString kNoData = QStringLiteral("—");
+
+/// get_val() now returns NaN for "the filing does not carry this line", so every
+/// derived figure is NaN-poisoned rather than silently zeroed.
+bool missing(double v) {
+ return std::isnan(v);
+}
+
+/// Ratio over a strictly positive denominator — the shape the old code wrote as
+/// `den > 0 ? num / den : 0.0`, but yielding "not computable" instead of a
+/// fabricated zero. Never substitutes a denominator.
+double pos_ratio(double num, double den) {
+ return (std::isnan(num) || std::isnan(den) || den <= 0.0) ? qQNaN() : num / den;
+}
+
+/// Period-over-period growth. Needs a real, positive base: a missing current
+/// value used to produce exactly -1.0, which printed as "-100.00% YoY" for a
+/// company that never reported the field.
+double growth_ratio(double current, double previous) {
+ return (std::isnan(current) || std::isnan(previous) || previous <= 0.0) ? qQNaN()
+ : (current - previous) / previous;
+}
+
+} // namespace
+
void EquityFinancialsTab::on_financials_loaded(services::equity::FinancialsData payload) {
if (payload.symbol != current_symbol_)
return;
@@ -62,15 +94,25 @@ void EquityFinancialsTab::on_financials_loaded(services::equity::FinancialsData
// ── Populate helpers ──────────────────────────────────────────────────────────
+// Returns NaN — not 0.0 — when the filing carries none of `keys`. A 0.0 miss was
+// indistinguishable from a reported zero, and every caller then divided by it,
+// charted it, or labelled it as if it were a real figure.
double EquityFinancialsTab::get_val(const QJsonObject& o, const QStringList& keys) {
+ bool reported_zero = false;
for (const auto& k : keys) {
- if (o.contains(k) && !o[k].isNull()) {
- double v = o[k].toVariant().toDouble();
- if (v != 0.0)
- return v;
- }
+ if (!o.contains(k) || o[k].isNull())
+ continue;
+ bool ok = false;
+ const double v = o[k].toVariant().toDouble(&ok);
+ if (!ok)
+ continue;
+ if (v != 0.0)
+ return v;
+ // A line item that IS present and reports 0 is data. Keep scanning the
+ // aliases for a non-zero reading first, then fall back to that zero.
+ reported_zero = true;
}
- return 0.0;
+ return reported_zero ? 0.0 : qQNaN();
}
void EquityFinancialsTab::populate_income_view(const services::equity::FinancialsData& d) {
@@ -88,63 +130,65 @@ void EquityFinancialsTab::populate_income_view(const services::equity::Financial
double prev_net = get_val(prev, {"Net Income", "Net Income Common Stockholders"});
double ebitda = get_val(latest, {"EBITDA", "Normalized EBITDA"});
- // Margins
- double gross_margin = revenue > 0 ? gross / revenue : 0.0;
- double op_margin = revenue > 0 ? op_income / revenue : 0.0;
- double net_margin = revenue > 0 ? net_income / revenue : 0.0;
- double ebitda_margin = revenue > 0 ? ebitda / revenue : 0.0;
+ // Margins — NaN when revenue is absent. Never substitute a denominator.
+ double gross_margin = pos_ratio(gross, revenue);
+ double op_margin = pos_ratio(op_income, revenue);
+ double net_margin = pos_ratio(net_income, revenue);
+ double ebitda_margin = pos_ratio(ebitda, revenue);
// Growth labels
- double rev_growth = prev_rev > 0 ? (revenue - prev_rev) / prev_rev : 0.0;
- double net_growth = prev_net > 0 ? (net_income - prev_net) / prev_net : 0.0;
+ double rev_growth = growth_ratio(revenue, prev_rev);
+ double net_growth = growth_ratio(net_income, prev_net);
auto set = [](QLabel* l, const QString& t) {
if (l)
l->setText(t);
};
- set(inc_revenue_val_, fmt_large(revenue));
- set(inc_revenue_sub_, rev_growth != 0.0 ? tr("%1 YoY").arg(fmt_pct(rev_growth)) : QString());
- set(inc_gross_val_, fmt_large(gross));
- set(inc_gross_sub_, tr("%1 margin").arg(fmt_pct(gross_margin)));
- set(inc_opincome_val_, fmt_large(op_income));
- set(inc_opincome_sub_, tr("%1 margin").arg(fmt_pct(op_margin)));
- set(inc_netincome_val_, fmt_large(net_income));
- set(inc_netincome_sub_, net_growth != 0.0 ? tr("%1 YoY").arg(fmt_pct(net_growth)) : QString());
- set(inc_ebitda_val_, fmt_large(ebitda));
- set(inc_ebitda_sub_, tr("%1 margin").arg(fmt_pct(ebitda_margin)));
- set(inc_gross_margin_, fmt_pct(gross_margin));
- set(inc_op_margin_, fmt_pct(op_margin));
- set(inc_net_margin_, fmt_pct(net_margin));
- set(inc_ebitda_margin_, fmt_pct(ebitda_margin));
+ set(inc_revenue_val_, missing(revenue) ? kNoData : fmt_large(revenue));
+ set(inc_revenue_sub_, missing(rev_growth) ? QString() : tr("%1 YoY").arg(fmt_pct(rev_growth)));
+ set(inc_gross_val_, missing(gross) ? kNoData : fmt_large(gross));
+ set(inc_gross_sub_, missing(gross_margin) ? QString() : tr("%1 margin").arg(fmt_pct(gross_margin)));
+ set(inc_opincome_val_, missing(op_income) ? kNoData : fmt_large(op_income));
+ set(inc_opincome_sub_, missing(op_margin) ? QString() : tr("%1 margin").arg(fmt_pct(op_margin)));
+ set(inc_netincome_val_, missing(net_income) ? kNoData : fmt_large(net_income));
+ set(inc_netincome_sub_, missing(net_growth) ? QString() : tr("%1 YoY").arg(fmt_pct(net_growth)));
+ set(inc_ebitda_val_, missing(ebitda) ? kNoData : fmt_large(ebitda));
+ set(inc_ebitda_sub_, missing(ebitda_margin) ? QString() : tr("%1 margin").arg(fmt_pct(ebitda_margin)));
+ set(inc_gross_margin_, missing(gross_margin) ? kNoData : fmt_pct(gross_margin));
+ set(inc_op_margin_, missing(op_margin) ? kNoData : fmt_pct(op_margin));
+ set(inc_net_margin_, missing(net_margin) ? kNoData : fmt_pct(net_margin));
+ set(inc_ebitda_margin_, missing(ebitda_margin) ? kNoData : fmt_pct(ebitda_margin));
// DuPont (needs balance sheet too)
if (!d.balance_sheet.isEmpty()) {
const auto& bal = d.balance_sheet[0].second;
double total_assets = get_val(bal, {"Total Assets"});
double total_equity = get_val(bal, {"Stockholders Equity", "Total Equity", "Total Stockholder Equity"});
- double asset_turnover = total_assets > 0 ? revenue / total_assets : 0.0;
- double eq_mult = total_equity > 0 ? total_assets / total_equity : 0.0;
- double roe = total_equity > 0 ? net_income / total_equity : 0.0;
- double roa = total_assets > 0 ? net_income / total_assets : 0.0;
-
- set(dupont_net_margin_, fmt_pct(net_margin));
- set(dupont_asset_turn_, QString::number(asset_turnover, 'f', 2) + "x");
- set(dupont_eq_mult_, QString::number(eq_mult, 'f', 2) + "x");
- set(dupont_roe_result_, fmt_pct(roe));
-
- // Invested capital for ROIC
+ double asset_turnover = pos_ratio(revenue, total_assets);
+ double eq_mult = pos_ratio(total_assets, total_equity);
+ double roe = pos_ratio(net_income, total_equity);
+ double roa = pos_ratio(net_income, total_assets);
+
+ set(dupont_net_margin_, missing(net_margin) ? kNoData : fmt_pct(net_margin));
+ set(dupont_asset_turn_, missing(asset_turnover) ? kNoData : fmt_ratio(asset_turnover) + QStringLiteral("x"));
+ set(dupont_eq_mult_, missing(eq_mult) ? kNoData : fmt_ratio(eq_mult) + QStringLiteral("x"));
+ set(dupont_roe_result_, missing(roe) ? kNoData : fmt_pct(roe));
+
+ // Invested capital for ROIC — NaN-poisoned if any leg is absent, so a
+ // partial balance sheet reports "no data" rather than an ROIC computed
+ // off a phantom zero cash / zero debt balance.
double total_debt = get_val(bal, {"Total Debt", "Long Term Debt"});
double cash = get_val(bal, {"Cash And Cash Equivalents", "Cash"});
double inv_cap = total_equity + total_debt - cash;
- double roic = inv_cap > 0 ? (op_income * 0.75) / inv_cap : 0.0;
+ double roic = pos_ratio(op_income * 0.75, inv_cap);
double cur_liab = get_val(bal, {"Current Liabilities", "Total Current Liabilities"});
- double roce = (total_assets - cur_liab) > 0 ? op_income / (total_assets - cur_liab) : 0.0;
+ double roce = pos_ratio(op_income, total_assets - cur_liab);
- set(ret_roe_val_, fmt_pct(roe));
- set(ret_roa_val_, fmt_pct(roa));
- set(ret_roic_val_, fmt_pct(roic));
- set(ret_roce_val_, fmt_pct(roce));
+ set(ret_roe_val_, missing(roe) ? kNoData : fmt_pct(roe));
+ set(ret_roa_val_, missing(roa) ? kNoData : fmt_pct(roa));
+ set(ret_roic_val_, missing(roic) ? kNoData : fmt_pct(roic));
+ set(ret_roce_val_, missing(roce) ? kNoData : fmt_pct(roce));
}
}
@@ -161,8 +205,9 @@ void EquityFinancialsTab::populate_balance_view(const services::equity::Financia
double cur_assets = get_val(b, {"Current Assets", "Total Current Assets"});
double cur_liab = get_val(b, {"Current Liabilities", "Total Current Liabilities"});
double inventory = get_val(b, {"Inventory"});
- double ebitda = 0.0;
- double interest = 0.0;
+ // No income statement means no EBITDA / interest reading at all — not zero.
+ double ebitda = qQNaN();
+ double interest = qQNaN();
if (!d.income_statement.isEmpty()) {
const auto& inc = d.income_statement[0].second;
ebitda = get_val(inc, {"EBITDA", "Normalized EBITDA"});
@@ -176,25 +221,25 @@ void EquityFinancialsTab::populate_balance_view(const services::equity::Financia
l->setText(t);
};
- set(bal_assets_val_, fmt_large(total_assets));
- set(bal_liabilities_val_, fmt_large(total_liab));
- set(bal_equity_val_, fmt_large(total_equity));
- set(bal_debt_val_, fmt_large(total_debt));
- set(bal_cash_val_, fmt_large(cash));
+ set(bal_assets_val_, missing(total_assets) ? kNoData : fmt_large(total_assets));
+ set(bal_liabilities_val_, missing(total_liab) ? kNoData : fmt_large(total_liab));
+ set(bal_equity_val_, missing(total_equity) ? kNoData : fmt_large(total_equity));
+ set(bal_debt_val_, missing(total_debt) ? kNoData : fmt_large(total_debt));
+ set(bal_cash_val_, missing(cash) ? kNoData : fmt_large(cash));
- double cur_ratio = cur_liab > 0 ? cur_assets / cur_liab : 0.0;
- double quick_ratio = cur_liab > 0 ? (cur_assets - inventory) / cur_liab : 0.0;
+ double cur_ratio = pos_ratio(cur_assets, cur_liab);
+ double quick_ratio = pos_ratio(cur_assets - inventory, cur_liab);
double work_cap = cur_assets - cur_liab;
- double d_e = total_equity > 0 ? total_debt / total_equity : 0.0;
- double d_a = total_assets > 0 ? total_debt / total_assets : 0.0;
- double int_cov = interest > 0 ? ebitda / interest : 0.0;
-
- set(bal_current_ratio_, fmt_ratio(cur_ratio));
- set(bal_quick_ratio_, fmt_ratio(quick_ratio));
- set(bal_working_cap_, fmt_large(work_cap));
- set(bal_debt_equity_, fmt_ratio(d_e));
- set(bal_debt_assets_, fmt_pct(d_a));
- set(bal_int_coverage_, int_cov > 0 ? fmt_ratio(int_cov) + QStringLiteral("x") : tr("N/A"));
+ double d_e = pos_ratio(total_debt, total_equity);
+ double d_a = pos_ratio(total_debt, total_assets);
+ double int_cov = pos_ratio(ebitda, interest);
+
+ set(bal_current_ratio_, missing(cur_ratio) ? kNoData : fmt_ratio(cur_ratio));
+ set(bal_quick_ratio_, missing(quick_ratio) ? kNoData : fmt_ratio(quick_ratio));
+ set(bal_working_cap_, missing(work_cap) ? kNoData : fmt_large(work_cap));
+ set(bal_debt_equity_, missing(d_e) ? kNoData : fmt_ratio(d_e));
+ set(bal_debt_assets_, missing(d_a) ? kNoData : fmt_pct(d_a));
+ set(bal_int_coverage_, missing(int_cov) ? tr("N/A") : fmt_ratio(int_cov) + QStringLiteral("x"));
}
void EquityFinancialsTab::populate_cashflow_view(const services::equity::FinancialsData& d) {
@@ -217,27 +262,27 @@ void EquityFinancialsTab::populate_cashflow_view(const services::equity::Financi
if (buybacks > 0)
buybacks = -buybacks;
- double revenue = 0.0;
+ double revenue = qQNaN();
if (!d.income_statement.isEmpty())
revenue = get_val(d.income_statement[0].second, {"Total Revenue", "Revenue"});
- double fcf_margin = revenue > 0 ? fcf / revenue : 0.0;
- double capex_rev = revenue > 0 ? qAbs(capex) / revenue : 0.0;
+ double fcf_margin = pos_ratio(fcf, revenue);
+ double capex_rev = pos_ratio(qAbs(capex), revenue);
auto set = [](QLabel* l, const QString& t) {
if (l)
l->setText(t);
};
- set(cf_operating_val_, fmt_large(op_cf));
- set(cf_investing_val_, fmt_large(inv_cf));
- set(cf_financing_val_, fmt_large(fin_cf));
- set(cf_fcf_val_, fmt_large(fcf));
- set(cf_fcf_sub_, fcf_margin != 0.0 ? tr("%1 margin").arg(fmt_pct(fcf_margin)) : QString());
- set(cf_capex_val_, fmt_large(qAbs(capex)));
- set(cf_dividends_val_, fmt_large(qAbs(dividends)));
- set(cf_buybacks_val_, fmt_large(qAbs(buybacks)));
- set(cf_fcf_margin_, fmt_pct(fcf_margin));
- set(cf_capex_rev_, fmt_pct(capex_rev));
+ set(cf_operating_val_, missing(op_cf) ? kNoData : fmt_large(op_cf));
+ set(cf_investing_val_, missing(inv_cf) ? kNoData : fmt_large(inv_cf));
+ set(cf_financing_val_, missing(fin_cf) ? kNoData : fmt_large(fin_cf));
+ set(cf_fcf_val_, missing(fcf) ? kNoData : fmt_large(fcf));
+ set(cf_fcf_sub_, missing(fcf_margin) ? QString() : tr("%1 margin").arg(fmt_pct(fcf_margin)));
+ set(cf_capex_val_, missing(capex) ? kNoData : fmt_large(qAbs(capex)));
+ set(cf_dividends_val_, missing(dividends) ? kNoData : fmt_large(qAbs(dividends)));
+ set(cf_buybacks_val_, missing(buybacks) ? kNoData : fmt_large(qAbs(buybacks)));
+ set(cf_fcf_margin_, missing(fcf_margin) ? kNoData : fmt_pct(fcf_margin));
+ set(cf_capex_rev_, missing(capex_rev) ? kNoData : fmt_pct(capex_rev));
}
// ── Chart builders ────────────────────────────────────────────────────────────
@@ -273,40 +318,59 @@ void EquityFinancialsTab::rebuild_revenue_chart(const services::equity::Financia
if (d.income_statement.isEmpty() || !inc_revenue_chart_)
return;
- // Up to 5 periods, reversed (oldest first)
+ // Up to 5 periods, reversed (oldest first). A period with no reported
+ // revenue is dropped outright: QBarSet has no "missing" slot, so a bar
+ // plotted at zero would assert the company earned nothing that year.
int n = qMin(5, d.income_statement.size());
QStringList cats;
QVector<double> revenue_v, gross_v, net_v;
for (int i = n - 1; i >= 0; --i) {
+ const auto& stmt = d.income_statement[i].second;
+ const double rev = get_val(stmt, {"Total Revenue", "Revenue"});
+ if (missing(rev))
+ continue;
cats << d.income_statement[i].first.left(4);
- revenue_v << get_val(d.income_statement[i].second, {"Total Revenue", "Revenue"}) / 1e9;
- gross_v << get_val(d.income_statement[i].second, {"Gross Profit"}) / 1e9;
- net_v << get_val(d.income_statement[i].second, {"Net Income", "Net Income Common Stockholders"}) / 1e9;
+ revenue_v << rev / 1e9;
+ gross_v << get_val(stmt, {"Gross Profit"}) / 1e9;
+ net_v << get_val(stmt, {"Net Income", "Net Income Common Stockholders"}) / 1e9;
+ }
+
+ auto* chart = new QChart;
+ style_chart(chart);
+ if (cats.isEmpty()) {
+ // Nothing reported — an empty plot, not a chart of zeroes.
+ inc_revenue_chart_->setChart(chart);
+ return;
}
auto* rev_set = new QBarSet(tr("Revenue"));
rev_set->setColor(QColor(kBlue));
- auto* gross_set = new QBarSet(tr("Gross Profit"));
- gross_set->setColor(QColor(kCyan));
- for (int i = 0; i < cats.size(); ++i) {
- *rev_set << revenue_v[i];
- *gross_set << gross_v[i];
- }
+ for (double v : revenue_v)
+ *rev_set << v;
auto* bar_series = new QBarSeries;
bar_series->append(rev_set);
- bar_series->append(gross_set);
+
+ // Gross profit is charted only when every plotted period reports it. Banks
+ // and insurers carry no "Gross Profit" line at all; a zero-height bar there
+ // would be a claim, not a gap.
+ if (std::none_of(gross_v.cbegin(), gross_v.cend(), missing)) {
+ auto* gross_set = new QBarSet(tr("Gross Profit"));
+ gross_set->setColor(QColor(kCyan));
+ for (double v : gross_v)
+ *gross_set << v;
+ bar_series->append(gross_set);
+ }
auto* net_series = new QLineSeries;
net_series->setName(tr("Net Income"));
net_series->setColor(QColor(kGreen));
net_series->setPen(QPen(QColor(kGreen), 2));
for (int i = 0; i < cats.size(); ++i)
- net_series->append(i, net_v[i]);
+ if (!missing(net_v[i]))
+ net_series->append(i, net_v[i]);
- auto* chart = new QChart;
- style_chart(chart);
chart->addSeries(bar_series);
chart->addSeries(net_series);
chart->legend()->show();
@@ -334,22 +398,26 @@ void EquityFinancialsTab::rebuild_margin_chart(const services::equity::Financial
for (int i = n - 1; i >= 0; --i) {
const auto& stmt = d.income_statement[i].second;
cats << d.income_statement[i].first.left(4);
- double rev = get_val(stmt, {"Total Revenue", "Revenue"});
- if (rev == 0.0)
- rev = 1.0;
- gross_v << get_val(stmt, {"Gross Profit"}) / rev * 100.0;
- op_v << get_val(stmt, {"Operating Income", "Operating Profit"}) / rev * 100.0;
- net_v << get_val(stmt, {"Net Income", "Net Income Common Stockholders"}) / rev * 100.0;
- ebitda_v << get_val(stmt, {"EBITDA", "Normalized EBITDA"}) / rev * 100.0;
+ // The denominator is never invented. `if (rev == 0.0) rev = 1.0;` used
+ // to turn a missing revenue line into a divide-by-one, plotting raw
+ // dollars × 100 — margins in the billions of percent.
+ const double rev = get_val(stmt, {"Total Revenue", "Revenue"});
+ gross_v << pos_ratio(get_val(stmt, {"Gross Profit"}), rev) * 100.0;
+ op_v << pos_ratio(get_val(stmt, {"Operating Income", "Operating Profit"}), rev) * 100.0;
+ net_v << pos_ratio(get_val(stmt, {"Net Income", "Net Income Common Stockholders"}), rev) * 100.0;
+ ebitda_v << pos_ratio(get_val(stmt, {"EBITDA", "Normalized EBITDA"}), rev) * 100.0;
}
+ // Line series carry gaps natively: an uncomputable period is simply not
+ // appended rather than being pinned to the axis at 0%.
auto make_line = [&](const QString& name, const QString& color, const QVector<double>& vals) {
auto* s = new QLineSeries;
s->setName(name);
s->setColor(QColor(color));
s->setPen(QPen(QColor(color), 2));
for (int i = 0; i < cats.size(); ++i)
- s->append(i, vals[i]);
+ if (!missing(vals[i]))
+ s->append(i, vals[i]);
return s;
};
@@ -381,31 +449,45 @@ void EquityFinancialsTab::rebuild_balance_chart(const services::equity::Financia
if (d.balance_sheet.isEmpty() || !bal_chart_)
return;
+ // Periods are driven by total assets; a period without it is dropped rather
+ // than drawn as a zero-height stack.
int n = qMin(5, d.balance_sheet.size());
QStringList cats;
-
- auto* assets_set = new QBarSet(tr("Assets"));
- assets_set->setColor(QColor(kBlue));
- auto* liab_set = new QBarSet(tr("Liabilities"));
- liab_set->setColor(QColor(kRed));
- auto* equity_set = new QBarSet(tr("Equity"));
- equity_set->setColor(QColor(kGreen));
+ QVector<double> assets_v, liab_v, equity_v;
for (int i = n - 1; i >= 0; --i) {
- cats << d.balance_sheet[i].first.left(4);
const auto& b = d.balance_sheet[i].second;
- *assets_set << get_val(b, {"Total Assets"}) / 1e9;
- *liab_set << get_val(b, {"Total Liabilities Net Minority Interest", "Total Liabilities"}) / 1e9;
- *equity_set << get_val(b, {"Stockholders Equity", "Total Equity"}) / 1e9;
+ const double assets = get_val(b, {"Total Assets"});
+ if (missing(assets))
+ continue;
+ cats << d.balance_sheet[i].first.left(4);
+ assets_v << assets / 1e9;
+ liab_v << get_val(b, {"Total Liabilities Net Minority Interest", "Total Liabilities"}) / 1e9;
+ equity_v << get_val(b, {"Stockholders Equity", "Total Equity"}) / 1e9;
}
- auto* series = new QBarSeries;
- series->append(assets_set);
- series->append(liab_set);
- series->append(equity_set);
-
auto* chart = new QChart;
style_chart(chart);
+ if (cats.isEmpty()) {
+ bal_chart_->setChart(chart);
+ return;
+ }
+
+ auto* series = new QBarSeries;
+ auto add_set = [&](const QString& name, const QString& color, const QVector<double>& vals) {
+ // Only complete series are plotted — a bar set cannot express a gap.
+ if (std::any_of(vals.cbegin(), vals.cend(), missing))
+ return;
+ auto* set = new QBarSet(name);
+ set->setColor(QColor(color));
+ for (double v : vals)
+ *set << v;
+ series->append(set);
+ };
+ add_set(tr("Assets"), kBlue, assets_v);
+ add_set(tr("Liabilities"), kRed, liab_v);
+ add_set(tr("Equity"), kGreen, equity_v);
+
chart->addSeries(series);
chart->legend()->show();
@@ -423,43 +505,56 @@ void EquityFinancialsTab::rebuild_cashflow_chart(const services::equity::Financi
if (d.cash_flow.isEmpty() || !cf_chart_)
return;
+ // Periods are driven by operating cash flow; a period without it is dropped.
int n = qMin(5, d.cash_flow.size());
QStringList cats;
-
- auto* op_set = new QBarSet(tr("Operating"));
- op_set->setColor(QColor(kGreen));
- auto* inv_set = new QBarSet(tr("Investing"));
- inv_set->setColor(QColor(kOrange));
- auto* fin_set = new QBarSet(tr("Financing"));
- fin_set->setColor(QColor(kPurple));
-
- auto* fcf_series = new QLineSeries;
- fcf_series->setName(tr("Free CF"));
- fcf_series->setColor(QColor(kCyan));
- fcf_series->setPen(QPen(QColor(kCyan), 2));
+ QVector<double> op_v, inv_v, fin_v, fcf_v;
for (int i = n - 1; i >= 0; --i) {
- cats << d.cash_flow[i].first.left(4);
const auto& cf = d.cash_flow[i].second;
- double op = get_val(cf, {"Operating Cash Flow", "Total Cash From Operating Activities"});
- double inv = get_val(cf, {"Investing Cash Flow", "Total Cash From Investing Activities"});
- double fin = get_val(cf, {"Financing Cash Flow", "Total Cash From Financing Activities"});
+ const double op = get_val(cf, {"Operating Cash Flow", "Total Cash From Operating Activities"});
+ if (missing(op))
+ continue;
double capex = get_val(cf, {"Capital Expenditure", "Capital Expenditures"});
if (capex > 0)
capex = -capex;
- *op_set << op / 1e9;
- *inv_set << inv / 1e9;
- *fin_set << fin / 1e9;
- fcf_series->append(cats.size() - 1, (op + capex) / 1e9);
+ cats << d.cash_flow[i].first.left(4);
+ op_v << op / 1e9;
+ inv_v << get_val(cf, {"Investing Cash Flow", "Total Cash From Investing Activities"}) / 1e9;
+ fin_v << get_val(cf, {"Financing Cash Flow", "Total Cash From Financing Activities"}) / 1e9;
+ // No capex line means free cash flow is unknown, not equal to op cash flow.
+ fcf_v << (op + capex) / 1e9;
}
- auto* bar_series = new QBarSeries;
- bar_series->append(op_set);
- bar_series->append(inv_set);
- bar_series->append(fin_set);
-
auto* chart = new QChart;
style_chart(chart);
+ if (cats.isEmpty()) {
+ cf_chart_->setChart(chart);
+ return;
+ }
+
+ auto* bar_series = new QBarSeries;
+ auto add_set = [&](const QString& name, const QString& color, const QVector<double>& vals) {
+ if (std::any_of(vals.cbegin(), vals.cend(), missing))
+ return;
+ auto* set = new QBarSet(name);
+ set->setColor(QColor(color));
+ for (double v : vals)
+ *set << v;
+ bar_series->append(set);
+ };
+ add_set(tr("Operating"), kGreen, op_v);
+ add_set(tr("Investing"), kOrange, inv_v);
+ add_set(tr("Financing"), kPurple, fin_v);
+
+ auto* fcf_series = new QLineSeries;
+ fcf_series->setName(tr("Free CF"));
+ fcf_series->setColor(QColor(kCyan));
+ fcf_series->setPen(QPen(QColor(kCyan), 2));
+ for (int i = 0; i < cats.size(); ++i)
+ if (!missing(fcf_v[i]))
+ fcf_series->append(i, fcf_v[i]);
+
chart->addSeries(bar_series);
chart->addSeries(fcf_series);
chart->legend()->show();
@@ -498,8 +593,14 @@ void EquityFinancialsTab::rebuild_return_chart(const services::equity::Financial
double net = get_val(d.income_statement[i].second, {"Net Income", "Net Income Common Stockholders"});
double assets = get_val(d.balance_sheet[i].second, {"Total Assets"});
double equity = get_val(d.balance_sheet[i].second, {"Stockholders Equity", "Total Equity"});
- roe_series->append(cats.size() - 1, equity > 0 ? (net / equity) * 100.0 : 0.0);
- roa_series->append(cats.size() - 1, assets > 0 ? (net / assets) * 100.0 : 0.0);
+ // An uncomputable period is skipped, not plotted at 0% — a flat zero
+ // return is a claim the filings never made.
+ const double roe = pos_ratio(net, equity) * 100.0;
+ const double roa = pos_ratio(net, assets) * 100.0;
+ if (!missing(roe))
+ roe_series->append(cats.size() - 1, roe);
+ if (!missing(roa))
+ roa_series->append(cats.size() - 1, roa);
}
auto* chart = new QChart;
diff --git a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
index 304fb83f5..34511b997 100644
--- a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
@@ -35,6 +35,28 @@ static constexpr int FONT_VAL = 13; // value labels
static constexpr int FONT_TITLE = 12; // panel titles
static constexpr int FONT_DESC = 12; // description text
+namespace {
+
+// The inline error banner is owned by the content layout rather than by a
+// member pointer (the tab's header is out of scope for this change), so it is
+// addressed by object name.
+constexpr const char* kErrorBannerName = "overviewErrorBanner";
+constexpr const char* kErrorMessageName = "overviewErrorMessage";
+constexpr const char* kRetryButtonName = "overviewRetryButton";
+
+/// Show the inline error banner with `message`, or hide it when `message` is
+/// empty. Modelled on MarketPanel::show_error + its [RETRY] affordance.
+void set_overview_error(QWidget* tab, const QString& message) {
+ auto* banner = tab->findChild<QFrame*>(QLatin1String(kErrorBannerName));
+ if (!banner)
+ return;
+ if (auto* label = tab->findChild<QLabel*>(QLatin1String(kErrorMessageName)))
+ label->setText(message);
+ banner->setVisible(!message.isEmpty());
+}
+
+} // namespace
+
// Panel + row helpers live on the class so they can register the title and
// key labels with the per-instance translation map. Each call site passes a
// stable English source string declared via QT_TR_NOOP so lupdate sees it.
@@ -283,14 +305,19 @@ EquityOverviewTab::EquityOverviewTab(QWidget* parent) : QWidget(parent) {
&EquityOverviewTab::on_historical_loaded);
// Overview waits on three legs (quote / info / historical) and only hides the
// overlay on success, so any one failing left "LOADING OVERVIEW…" spinning
- // over the tab with no way to dismiss it.
+ // over the tab with no way to dismiss it. Hiding the overlay fixed the spin
+ // but discarded the reason, leaving a blank tab that explained nothing — so
+ // render the message inline with a retry, the way MarketPanel does.
connect(&svc, &services::equity::EquityResearchService::error_occurred, this,
- [this](const QString& ctx, const QString&) {
- if (!loading_overlay_)
+ [this](const QString& ctx, const QString& message) {
+ if (ctx != QLatin1String("Quote") && ctx != QLatin1String("Info") &&
+ ctx != QLatin1String("Historical"))
return;
- if (ctx == QLatin1String("Quote") || ctx == QLatin1String("Info") ||
- ctx == QLatin1String("Historical"))
+ if (loading_overlay_)
loading_overlay_->hide_loading();
+ const QString detail = message.trimmed();
+ set_overview_error(this, detail.isEmpty() ? tr("%1 data could not be loaded.").arg(ctx)
+ : tr("%1 data could not be loaded: %2").arg(ctx, detail));
});
}
@@ -299,6 +326,7 @@ void EquityOverviewTab::set_symbol(const QString& symbol) {
return;
current_symbol_ = symbol;
info_loaded_ = quote_loaded_ = historical_loaded_ = false;
+ set_overview_error(this, QString()); // drop the previous symbol's failure
loading_overlay_->show_loading(tr("LOADING OVERVIEW…"));
}
@@ -322,6 +350,37 @@ void EquityOverviewTab::build_ui() {
vl->setContentsMargins(8, 8, 8, 8);
vl->setSpacing(6);
+ // ── Inline error banner (hidden until a load leg fails) ───────────────────
+ // Built from make_panel_/add_row_ so it inherits the tab's panel styling and
+ // registers its title + key with i18n_labels_ for retranslation; the retry
+ // button picks up the global QSS QPushButton rule. It sits above the panels
+ // rather than replacing them, so a partial load (quote arrived, history
+ // failed) still shows the data that did land.
+ auto* error_banner = make_panel_(QT_TR_NOOP("DATA UNAVAILABLE"), ui::colors::NEGATIVE);
+ error_banner->setObjectName(QLatin1String(kErrorBannerName));
+ auto* error_msg = add_row_(error_banner, QT_TR_NOOP("REASON"), ui::colors::NEGATIVE);
+ error_msg->setObjectName(QLatin1String(kErrorMessageName));
+ error_msg->setWordWrap(true); // service messages are full sentences
+ error_msg->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
+
+ auto* retry_btn = new QPushButton(tr("[RETRY]"));
+ retry_btn->setObjectName(QLatin1String(kRetryButtonName));
+ retry_btn->setCursor(Qt::PointingHandCursor);
+ retry_btn->setAccessibleName(tr("Retry loading the overview tab"));
+ connect(retry_btn, &QPushButton::clicked, this, [this]() {
+ if (current_symbol_.isEmpty())
+ return;
+ set_overview_error(this, QString());
+ info_loaded_ = quote_loaded_ = historical_loaded_ = false;
+ if (loading_overlay_)
+ loading_overlay_->show_loading(tr("LOADING OVERVIEW…"));
+ services::equity::EquityResearchService::instance().load_symbol(current_symbol_, current_period_);
+ });
+ static_cast<QVBoxLayout*>(error_banner->layout())->addWidget(retry_btn, 0, Qt::AlignLeft);
+
+ error_banner->setVisible(false);
+ vl->addWidget(error_banner);
+
auto* top = new QHBoxLayout;
top->setSpacing(6);
@@ -490,8 +549,10 @@ void EquityOverviewTab::switch_period(QPushButton* btn, const QString& period) {
active_period_btn_ = btn;
// Reload data with new period
- if (!current_symbol_.isEmpty())
+ if (!current_symbol_.isEmpty()) {
+ set_overview_error(this, QString()); // the previous period's failure no longer applies
services::equity::EquityResearchService::instance().load_symbol(current_symbol_, period);
+ }
}
// ── Column 4: Analyst + 52W + Profitability + Growth ─────────────────────────
@@ -862,6 +923,11 @@ void EquityOverviewTab::retranslateUi() {
for (auto it = i18n_labels_.constBegin(); it != i18n_labels_.constEnd(); ++it) {
it.key()->setText(tr(it.value()));
}
+ // The error banner's title + key ride the map above; its button does not.
+ if (auto* retry_btn = findChild<QPushButton*>(QLatin1String(kRetryButtonName))) {
+ retry_btn->setText(tr("[RETRY]"));
+ retry_btn->setAccessibleName(tr("Retry loading the overview tab"));
+ }
// Re-render whatever data is already loaded so value labels (which carry
// localized "N/A" / recommendation badges / currency-formatted numbers)
// pick up the new language without a service round-trip.
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 5a48da14b..8919753c8 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -105,7 +105,7 @@ EquityResearchScreen::EquityResearchScreen(QWidget* parent) : QWidget(parent) {
// Listen on the app-wide event bus for "load this symbol" requests
// from other parts of the app (e.g. the command bar search).
- EventBus::instance().subscribe("equity_research.load_symbol", [this](const QVariantMap& payload) {
+ EventBus::instance().subscribe(this, "equity_research.load_symbol", [this](const QVariantMap& payload) {
const QString symbol = payload.value("symbol").toString();
if (!symbol.isEmpty())
load_symbol(symbol);
diff --git a/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp b/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp
index 58969fd41..92982dea3 100644
--- a/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityValuationTab.cpp
@@ -14,6 +14,8 @@
#include <QScrollArea>
#include <QVBoxLayout>
+#include <cmath>
+
namespace fincept::screens {
// ─────────────────────────────────────────────────────────────────────────────
@@ -395,22 +397,33 @@ void EquityValuationTab::run_scoring_models() {
: get_stmt_val(bs, "Working Capital");
// ── Altman Z ─────────────────────────────────────────────────
- QJsonObject altman_body;
- altman_body["working_capital"] = working_capital;
- altman_body["total_assets"] = total_assets;
- altman_body["retained_earnings"] = retained_earnings;
- altman_body["ebit"] = ebit;
- altman_body["market_cap"] = last_info_.market_cap;
- altman_body["total_liabilities"] = total_liabilities;
- altman_body["revenue"] = revenue;
-
QPointer<EquityValuationTab> self = this;
- services::QuantLibClient::instance().call("analysis/valuation/predictive/altman-z", altman_body,
- [self](mcp::ToolResult r) {
- if (!self || !r.success)
- return;
- self->display_altman_result(r.data);
- });
+
+ // Four of Altman's five ratios divide by total assets and the fifth by total
+ // liabilities. With an empty balance sheet every input here is 0, and asking
+ // the endpoint anyway yields a score that describes nothing — which then
+ // rendered as a red "DISTRESS ZONE". Don't ask; say so instead.
+ if (total_assets > 0.0 && total_liabilities > 0.0) {
+ QJsonObject altman_body;
+ altman_body["working_capital"] = working_capital;
+ altman_body["total_assets"] = total_assets;
+ altman_body["retained_earnings"] = retained_earnings;
+ altman_body["ebit"] = ebit;
+ altman_body["market_cap"] = last_info_.market_cap;
+ altman_body["total_liabilities"] = total_liabilities;
+ altman_body["revenue"] = revenue;
+
+ services::QuantLibClient::instance().call("analysis/valuation/predictive/altman-z", altman_body,
+ [self](mcp::ToolResult r) {
+ if (!self)
+ return;
+ // An empty value renders "NO DATA" — a failed call must not
+ // leave a stale verdict from the previously viewed symbol.
+ self->display_altman_result(r.success ? r.data : QJsonValue());
+ });
+ } else {
+ display_altman_result(QJsonValue());
+ }
// ── Piotroski F (needs two periods) ──────────────────────────
if (is.size() >= 2 && bs.size() >= 2) {
@@ -548,13 +561,22 @@ void EquityValuationTab::display_dcf_result(const QJsonValue& data) {
void EquityValuationTab::display_altman_result(const QJsonValue& data) {
auto obj = data.toObject();
- double z = obj.value("z_score").toDouble(obj.value("altman_z_score").toDouble(0.0));
+ // NaN sentinel, not 0.0. run_scoring_models() dispatches the Altman request
+ // unconditionally — with all-zero inputs when the balance sheet is empty,
+ // which is the normal case for ETFs, funds and most non-US listings. A 0.0
+ // default fell past both thresholds into "DISTRESS ZONE", so the terminal
+ // published a red bankruptcy verdict for any instrument whose financials
+ // simply did not load. Mirrors the -1 sentinel in display_piotroski_result.
+ const double z = obj.value("z_score").toDouble(obj.value("altman_z_score").toDouble(qQNaN()));
+ const bool has_z = !std::isnan(z);
if (altman_val_)
- altman_val_->setText(QString::number(z, 'f', 2));
+ altman_val_->setText(has_z ? QString::number(z, 'f', 2) : QStringLiteral("—"));
if (altman_badge_) {
- if (z > 2.99)
+ if (!has_z)
+ set_badge(altman_badge_, tr("NO DATA"), ui::colors::TEXT_TERTIARY());
+ else if (z > 2.99)
set_badge(altman_badge_, tr("SAFE ZONE"), ui::colors::POSITIVE());
else if (z >= 1.81)
set_badge(altman_badge_, tr("GREY ZONE"), ui::colors::AMBER());
@@ -582,13 +604,19 @@ void EquityValuationTab::display_piotroski_result(const QJsonValue& data) {
void EquityValuationTab::display_beneish_result(const QJsonValue& data) {
auto obj = data.toObject();
- double m = obj.value("m_score").toDouble(obj.value("beneish_m_score").toDouble(0.0));
+ // Same 0.0-default trap as Altman: an absent m_score defaulted to 0.0, which
+ // is above the -2.22 threshold and therefore accused every company with no
+ // returned score of "POSSIBLE MANIPULATOR".
+ const double m = obj.value("m_score").toDouble(obj.value("beneish_m_score").toDouble(qQNaN()));
+ const bool has_m = !std::isnan(m);
if (beneish_val_)
- beneish_val_->setText(QString::number(m, 'f', 2));
+ beneish_val_->setText(has_m ? QString::number(m, 'f', 2) : QStringLiteral("—"));
if (beneish_badge_) {
- if (m < -2.22)
+ if (!has_m)
+ set_badge(beneish_badge_, tr("NO DATA"), ui::colors::TEXT_TERTIARY());
+ else if (m < -2.22)
set_badge(beneish_badge_, tr("UNLIKELY MANIPULATOR"), ui::colors::POSITIVE());
else
set_badge(beneish_badge_, tr("POSSIBLE MANIPULATOR"), ui::colors::NEGATIVE());
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
index 344bd1158..6e40a18d4 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
@@ -1279,9 +1279,22 @@ void AccountManagementDialog::on_connect_zerodha_browser() {
}
});
+ // Carry the RedirectServer's CSRF nonce into the authorize URL, then arm the
+ // gate. Until this happens the nonce check is inert and RedirectServer logs a
+ // warning on every login (see RedirectServer.h, gate 3).
+ //
+ // Kite does NOT echo an arbitrary `state` query parameter. Its login flow
+ // appends whatever is passed in `redirect_params` — a URL-encoded query
+ // string — to the registered redirect URL, so the nonce has to travel that
+ // way to come back as "...&state=<nonce>".
+ QString login_url = trading::ZerodhaBroker::kite_login_url(api_key);
+ login_url += QStringLiteral("&redirect_params=") +
+ QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral("state=") + z_redirect_server_->state()));
+ z_redirect_server_->set_require_state(true);
+
z_status_->setText(tr("Waiting for browser login on port %1 (120s)...").arg(z_redirect_server_->port()));
z_status_->setStyleSheet(QString("color:%1;").arg(colors::AMBER()));
- QDesktopServices::openUrl(QUrl(trading::ZerodhaBroker::kite_login_url(api_key)));
+ QDesktopServices::openUrl(QUrl(login_url));
}
void AccountManagementDialog::on_connect_zerodha_manual_paste() {
@@ -1562,9 +1575,23 @@ void AccountManagementDialog::on_connect_fyers_browser() {
});
const QString redirect_uri = QStringLiteral("http://127.0.0.1:%1/").arg(kFyersPort);
+
+ // Fyers echoes `state` back on the redirect, so route the RedirectServer's
+ // CSRF nonce through it and arm the gate (see RedirectServer.h, gate 3).
+ // fyers_login_url() stamps a timestamp into `state` by default — it MUST be
+ // replaced, not appended to: RedirectServer rejects any echoed state that
+ // isn't the nonce, so a leftover timestamp fails the real callback.
+ QUrl login_url(trading::FyersBroker::fyers_login_url(client_id, redirect_uri));
+ QUrlQuery login_query(login_url);
+ login_query.removeAllQueryItems(QStringLiteral("state"));
+ login_query.addQueryItem(QStringLiteral("state"),
+ QString::fromLatin1(QUrl::toPercentEncoding(f_redirect_server_->state())));
+ login_url.setQuery(login_query);
+ f_redirect_server_->set_require_state(true);
+
f_status_->setText(tr("Waiting for browser login on port %1 (120s)...").arg(kFyersPort));
f_status_->setStyleSheet(QString("color:%1;").arg(colors::AMBER()));
- QDesktopServices::openUrl(QUrl(trading::FyersBroker::fyers_login_url(client_id, redirect_uri)));
+ QDesktopServices::openUrl(login_url);
}
void AccountManagementDialog::on_connect_fyers_manual_paste() {
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index c469f2a8b..818e016bf 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -1372,26 +1372,35 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
// Per-row SELL → square off just this holding (market, CNC). Routed through
// the screen's close_position path (same as SQUARE OFF ALL) so it reliably
// reduces the holding instead of opening a counter-position.
- auto* action_cell = new QWidget;
- auto* action_lay = new QHBoxLayout(action_cell);
- action_lay->setContentsMargins(2, 0, 2, 0);
- action_lay->setSpacing(4);
- auto* sell_btn = new QPushButton(tr("SELL"));
- sell_btn->setObjectName("eqTableBtn");
- sell_btn->setProperty("act", "sell");
- sell_btn->setFixedHeight(18);
- sell_btn->setCursor(Qt::PointingHandCursor);
+ // Reuse the row's existing SELL button; only its bound symbol/exchange
+ // change. Previously this allocated a QWidget + QHBoxLayout + QPushButton
+ // on EVERY holdings push, and setCellWidget() destroyed the previous
+ // occupant — so each broker refresh churned N button subtrees (each with
+ // a connect, a tooltip and a tr() accessible name) and dropped keyboard
+ // focus out of the action cell. The rest of this function was already
+ // careful (updates disabled, sorting off, item reuse via ensure_item);
+ // only the action cell was missed. Same shape as PaperBlotterPanel and
+ // CryptoBottomPanel: the handler reads dynamic properties, so the
+ // connection is made exactly once.
+ auto* sell_btn = qobject_cast<QPushButton*>(holdings_table_->cellWidget(i, 9));
+ if (!sell_btn) {
+ sell_btn = new QPushButton(tr("SELL"));
+ sell_btn->setObjectName("eqTableBtn");
+ sell_btn->setProperty("act", "sell");
+ sell_btn->setFixedHeight(18);
+ sell_btn->setCursor(Qt::PointingHandCursor);
+ connect(sell_btn, &QPushButton::clicked, this, [this, sell_btn]() {
+ const QString sym = sell_btn->property("fnSymbol").toString();
+ const QString exch = sell_btn->property("fnExchange").toString();
+ LOG_INFO("sqoff", QString("[panel] per-row SELL clicked: sym='%1' exch='%2'").arg(sym, exch));
+ emit square_off_holding_requested(sym, exch);
+ });
+ holdings_table_->setCellWidget(i, 9, sell_btn);
+ }
+ sell_btn->setProperty("fnSymbol", h.symbol);
+ sell_btn->setProperty("fnExchange", h.exchange);
sell_btn->setAccessibleName(tr("Square off holding %1").arg(h.symbol));
sell_btn->setToolTip(tr("Square off %1 — sells the full holding at market").arg(h.symbol));
- const QString row_sym = h.symbol;
- const QString row_exch = h.exchange;
- connect(sell_btn, &QPushButton::clicked, this, [this, row_sym, row_exch]() {
- LOG_INFO("sqoff", QString("[panel] per-row SELL clicked: sym='%1' exch='%2'").arg(row_sym, row_exch));
- emit square_off_holding_requested(row_sym, row_exch);
- });
- action_lay->addWidget(sell_btn);
- action_lay->addStretch();
- holdings_table_->setCellWidget(i, 9, action_cell);
total_invested += h.invested_value;
total_current += h.current_value;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 54e389ac6..63cc6c36e 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -765,13 +765,12 @@ void EquityTradingScreen::async_modify_order(const QString& order_id, double qty
if (!self)
return;
QJsonObject mods;
- if (qty > 0) {
- mods["qty"] = qty;
- // Brokers read one key or the other — Dhan/Kotak modify_order reads
- // "quantity" (was getting nothing → transmitted qty 0, corrupting a
- // resting SL); send both so every broker's modify sees the new qty.
+ // "quantity" is the only spelling any broker's modify_order reads — the
+ // "qty" key that used to be sent alongside it was read by nothing.
+ // UnifiedTrading::modify_order hydrates side/symbol/exchange/product/
+ // order_type from the resting order, so this only carries the deltas.
+ if (qty > 0)
mods["quantity"] = qty;
- }
if (price > 0)
mods["price"] = price;
auto result = UnifiedTrading::instance().modify_order(acct_id, order_id, mods);
diff --git a/fincept-qt/src/screens/excel/ExcelScreen.cpp b/fincept-qt/src/screens/excel/ExcelScreen.cpp
index b97c5acd9..d5ed4344a 100644
--- a/fincept-qt/src/screens/excel/ExcelScreen.cpp
+++ b/fincept-qt/src/screens/excel/ExcelScreen.cpp
@@ -7,6 +7,7 @@
#include "services/file_manager/FileManagerService.h"
#include "ui/theme/Theme.h"
+#include <QColor>
#include <QDateTime>
#include <QFile>
#include <QFileDialog>
@@ -25,8 +26,12 @@
#ifdef FINCEPT_HAS_QXLSX
# include <xlsxdocument.h>
+# include <xlsxformat.h>
#endif
+#include <QPointer>
+#include <QSet>
+
namespace fincept::screens {
using namespace fincept::ui;
@@ -318,36 +323,36 @@ void ExcelScreen::on_import() {
w->deleteLater();
}
- // Every cell becomes a heap-allocated SpreadsheetItem, so an unbounded
- // dimension (a stray value in row 1,000,000) would allocate tens of millions
- // of items and hang the UI. Cap the import window.
+ // The import window bounds BOTH the xlsx.read() calls and the grid we build
+ // from them, so it has to stay something a grid can plausibly show. The old
+ // 20 000 × 512 window was 10.2M cells — a cap that itself caused the hang it
+ // was meant to prevent. 64 columns is already past "BL" in Excel lettering;
+ // anything wider is a data dump, not a spreadsheet.
constexpr int kMaxImportRows = 20000;
- constexpr int kMaxImportCols = 512;
+ constexpr int kMaxImportCols = 64;
bool truncated = false;
for (const auto& name : sheet_names) {
xlsx.selectSheet(name);
- // Determine dimensions
- auto dim = xlsx.dimension();
- int max_row = std::max(dim.lastRow(), 100);
- int max_col = std::max(dim.lastColumn(), 26);
- if (max_row > kMaxImportRows) {
- max_row = kMaxImportRows;
- truncated = true;
- }
- if (max_col > kMaxImportCols) {
- max_col = kMaxImportCols;
+ // Read the sheet's USED range only. Padding out to a minimum 100 × 26
+ // grid here meant every read loop did at least 2 600 xlsx.read() calls
+ // for cells the file doesn't have; SpreadsheetWidget pads the visible
+ // grid to that minimum itself, without touching the file.
+ const auto dim = xlsx.dimension();
+ int data_rows = std::clamp(dim.lastRow(), 0, kMaxImportRows);
+ int data_cols = std::clamp(dim.lastColumn(), 0, kMaxImportCols);
+ if (dim.lastRow() > kMaxImportRows || dim.lastColumn() > kMaxImportCols)
truncated = true;
- }
- auto* sheet = new SpreadsheetWidget(name, max_row, max_col, sheet_tabs_);
+ auto* sheet =
+ new SpreadsheetWidget(name, std::max(data_rows, 100), std::max(data_cols, 26), sheet_tabs_);
// Load data
- QVector<QVector<QString>> cells(max_row);
- for (int r = 0; r < max_row; ++r) {
- cells[r].resize(max_col);
- for (int c = 0; c < max_col; ++c) {
+ QVector<QVector<QString>> cells(data_rows);
+ for (int r = 0; r < data_rows; ++r) {
+ cells[r].resize(data_cols);
+ for (int c = 0; c < data_cols; ++c) {
auto cell = xlsx.read(r + 1, c + 1); // QXlsx is 1-based
cells[r][c] = cell.isValid() ? cell.toString() : "";
}
@@ -389,49 +394,260 @@ void ExcelScreen::on_import() {
// Export (XLSX via QXlsx)
// ─────────────────────────────────────────────────────────────────────────────
-void ExcelScreen::on_export() {
+// ── XLSX writing ────────────────────────────────────────────────────────────
+// Data is snapshotted out of the widgets before any dialog opens (see
+// on_export), so this works on plain values and touches no UI state.
+
+struct ExcelSheetSnapshot {
+ QString name;
+ QVector<QVector<QString>> cells;
+};
+
#ifdef FINCEPT_HAS_QXLSX
- QString path = QFileDialog::getSaveFileName(this, tr("Export as XLSX"), file_name_, tr("Excel Files (*.xlsx)"));
- if (path.isEmpty())
- return;
- // QFileDialog on Linux/macOS does not always append the filter suffix.
- if (!path.endsWith(QLatin1String(".xlsx"), Qt::CaseInsensitive))
- path += QLatin1String(".xlsx");
- QXlsx::Document xlsx;
+// Excel sheet-name rules: 1-31 chars, none of []:*?/\, and unique per workbook.
+// A name that violates these makes addSheet/renameSheet fail, after which the
+// writes land on whatever sheet happened to be current — silently exporting one
+// sheet's data under another's name.
+static QString excel_safe_sheet_name(QString name, QSet<QString>& taken) {
+ static const QString kIllegal = QStringLiteral("[]:*?/\\");
+ for (const QChar& ch : kIllegal)
+ name.replace(ch, QLatin1Char('_'));
+ name = name.trimmed().left(31);
+ if (name.isEmpty())
+ name = QStringLiteral("Sheet");
+
+ QString candidate = name;
+ int n = 2;
+ while (taken.contains(candidate.toLower())) {
+ const QString suffix = QStringLiteral("_") + QString::number(n++);
+ candidate = name.left(31 - suffix.size()) + suffix;
+ }
+ taken.insert(candidate.toLower());
+ return candidate;
+}
- for (int i = 0; i < sheet_tabs_->count(); ++i) {
- auto* sheet = qobject_cast<SpreadsheetWidget*>(sheet_tabs_->widget(i));
- if (!sheet)
+// Last row/col holding anything. get_data() pads every sheet to at least
+// 100x26, so without trimming a 12-row model exports as a 100-row sheet with
+// column widths and header styling stretched across empty space.
+static void excel_used_extent(const QVector<QVector<QString>>& cells, int& last_row, int& last_col) {
+ last_row = -1;
+ last_col = -1;
+ for (int r = 0; r < cells.size(); ++r) {
+ for (int c = 0; c < cells[r].size(); ++c) {
+ if (!cells[r][c].trimmed().isEmpty()) {
+ last_row = std::max(last_row, r);
+ last_col = std::max(last_col, c);
+ }
+ }
+ }
+}
+
+static bool write_snapshots_to_xlsx(QXlsx::Document& xlsx, const QVector<ExcelSheetSnapshot>& snapshots) {
+ using QXlsx::Format;
+
+ // Header: white on the terminal's accent, bold, centred.
+ Format header_fmt;
+ header_fmt.setFontBold(true);
+ header_fmt.setFontColor(QColor(Qt::white));
+ header_fmt.setPatternBackgroundColor(QColor(kAccent()));
+ header_fmt.setHorizontalAlignment(Format::AlignHCenter);
+ header_fmt.setBorderStyle(Format::BorderThin);
+
+ // Row label / section heading: bold, left.
+ Format label_fmt;
+ label_fmt.setFontBold(true);
+
+ // Numbers: thousands separator, 2dp, negatives in parentheses — the
+ // convention finance reads by default.
+ Format num_fmt;
+ num_fmt.setNumberFormat(QStringLiteral("#,##0.00;(#,##0.00)"));
+ num_fmt.setHorizontalAlignment(Format::AlignRight);
+
+ // Rates are stored as decimals (0.105), so a percent format is what makes
+ // them readable — "10.5%" rather than "0.11".
+ Format pct_fmt;
+ pct_fmt.setNumberFormat(QStringLiteral("0.0%"));
+ pct_fmt.setHorizontalAlignment(Format::AlignRight);
+
+ Format price_fmt;
+ price_fmt.setNumberFormat(QStringLiteral("$#,##0.00"));
+ price_fmt.setHorizontalAlignment(Format::AlignRight);
+
+ // Counts (shares, years, periods) — no decimals, no currency.
+ Format count_fmt;
+ count_fmt.setNumberFormat(QStringLiteral("#,##0.##"));
+ count_fmt.setHorizontalAlignment(Format::AlignRight);
+
+ QSet<QString> taken_names;
+ bool wrote_any = false;
+
+ for (int s = 0; s < snapshots.size(); ++s) {
+ const ExcelSheetSnapshot& snap = snapshots[s];
+ const QString name = excel_safe_sheet_name(snap.name, taken_names);
+
+ // First sheet: rename the default one. Later sheets: add. Both are
+ // checked — a silent failure here is what sends writes to the wrong
+ // sheet. sheetNames() is never assumed non-empty.
+ if (s == 0) {
+ const QStringList names = xlsx.sheetNames();
+ if (names.isEmpty()) {
+ if (!xlsx.addSheet(name))
+ continue;
+ } else {
+ xlsx.selectSheet(names.first());
+ if (names.first() != name)
+ xlsx.renameSheet(names.first(), name);
+ }
+ } else if (!xlsx.addSheet(name)) {
+ LOG_WARN("ExcelScreen", "Export: could not add sheet " + name + " — skipped");
continue;
+ }
- if (i > 0)
- xlsx.addSheet(sheet->sheet_name());
- else
- xlsx.selectSheet(xlsx.sheetNames().first());
+ int last_row = -1;
+ int last_col = -1;
+ excel_used_extent(snap.cells, last_row, last_col);
+ if (last_row < 0) {
+ wrote_any = true; // an empty sheet is still a valid sheet
+ continue;
+ }
- // Rename sheet
- xlsx.renameSheet(xlsx.sheetNames().last(), sheet->sheet_name());
+ // Header row = first row with content, if it is text rather than
+ // numbers (a numeric first row is data, not a header).
+ int header_row = -1;
+ for (int r = 0; r <= last_row && header_row < 0; ++r) {
+ for (int c = 0; c <= last_col; ++c) {
+ const QString v = (c < snap.cells[r].size()) ? snap.cells[r][c].trimmed() : QString();
+ if (v.isEmpty())
+ continue;
+ bool numeric = false;
+ v.toDouble(&numeric);
+ header_row = (numeric || v.startsWith(QLatin1Char('='))) ? -2 : r;
+ break;
+ }
+ }
+
+ QVector<int> col_width(last_col + 1, 10);
+
+ for (int r = 0; r <= last_row; ++r) {
+ // Row-level number format, chosen from the row's label in column A.
+ // A single blanket "#,##0.00" is wrong for half a financial model:
+ // a WACC of 0.105 rendered as "0.11" and a 3% terminal growth as
+ // "0.03", losing both precision and meaning. The label is the only
+ // signal available for what a row actually holds.
+ const QString label = (!snap.cells[r].isEmpty()) ? snap.cells[r][0].trimmed().toLower() : QString();
+ const Format* row_fmt = &num_fmt;
+ if (label.contains(QLatin1String("rate")) || label.contains(QLatin1String("growth")) ||
+ label.contains(QLatin1String("margin")) || label.contains(QLatin1String("wacc")) ||
+ label.contains(QLatin1String("yield")) || label.contains(QLatin1String("upside")) ||
+ label.contains(QLatin1String("downside")) || label.startsWith(QLatin1Char('%')) ||
+ label.contains(QLatin1String("% of"))) {
+ row_fmt = &pct_fmt;
+ } else if (label.contains(QLatin1String("price")) || label.contains(QLatin1String("per share"))) {
+ row_fmt = &price_fmt;
+ } else if (label.contains(QLatin1String("shares")) || label.contains(QLatin1String("years")) ||
+ label.contains(QLatin1String("period"))) {
+ row_fmt = &count_fmt;
+ }
- auto cells = sheet->get_data();
- for (int r = 0; r < cells.size(); ++r) {
- for (int c = 0; c < cells[r].size(); ++c) {
- const QString& val = cells[r][c];
- if (val.isEmpty())
+ for (int c = 0; c <= last_col; ++c) {
+ const QString val = (c < snap.cells[r].size()) ? snap.cells[r][c] : QString();
+ if (val.trimmed().isEmpty())
continue;
- // Write formulas as formulas, numbers as numbers
+ // Width from what the cell DISPLAYS, not from its source. A
+ // formula's text is far longer than its result, so sizing on it
+ // pushed every column to the 52-char cap on a model whose widest
+ // visible value was six digits.
+ const int display_len =
+ val.startsWith(QLatin1Char('=')) ? 12 : static_cast<int>(val.size()) + 2;
+ col_width[c] = std::max(col_width[c], display_len);
+
+ if (r == header_row) {
+ xlsx.write(r + 1, c + 1, val, header_fmt);
+ continue;
+ }
+
+ // Formula first — "=1+2" also parses as text, and a formula
+ // written as a string exports as a literal instead of a live cell.
+ if (val.startsWith(QLatin1Char('='))) {
+ xlsx.write(r + 1, c + 1, val, *row_fmt);
+ continue;
+ }
+
+ // Percentages authored as text ("12.5%") become real percentages.
+ if (val.endsWith(QLatin1Char('%'))) {
+ bool pct_ok = false;
+ const double pct = val.left(val.size() - 1).toDouble(&pct_ok);
+ if (pct_ok) {
+ xlsx.write(r + 1, c + 1, pct / 100.0, pct_fmt);
+ continue;
+ }
+ }
+
bool ok = false;
- double d = val.toDouble(&ok);
- if (ok) {
- xlsx.write(r + 1, c + 1, d);
- } else if (val.startsWith('=')) {
- xlsx.write(r + 1, c + 1, val); // QXlsx handles formulas
+ const double d = val.toDouble(&ok);
+ // qIsFinite: "nan"/"inf" parse as doubles and would write XML
+ // Excel refuses to open.
+ if (ok && qIsFinite(d)) {
+ xlsx.write(r + 1, c + 1, d, *row_fmt);
+ } else if (c == 0) {
+ xlsx.write(r + 1, c + 1, val, label_fmt); // first column reads as labels
} else {
xlsx.write(r + 1, c + 1, val);
}
}
}
+
+ for (int c = 0; c <= last_col; ++c)
+ xlsx.setColumnWidth(c + 1, std::min(col_width[c], 52));
+ wrote_any = true;
+ }
+
+ return wrote_any;
+}
+
+#endif // FINCEPT_HAS_QXLSX
+
+void ExcelScreen::on_export() {
+#ifdef FINCEPT_HAS_QXLSX
+ // ── Snapshot BEFORE the file dialog ───────────────────────────────────
+ // getSaveFileName runs a nested event loop. Anything queued on the UI
+ // thread runs inside it — including MCP tool bodies, which can call
+ // navigate() and tear down or rebuild the Excel dock. The old code read
+ // sheet_tabs_ and every SpreadsheetWidget* AFTER the dialog returned, so a
+ // dock rebuild mid-dialog left it walking freed widgets: the observed crash
+ // was a read of address 0x8 (a null QObject's d_ptr) inside Qt6Core during
+ // export. Copying the data out first means the dialog can't invalidate
+ // anything we still need.
+ QVector<ExcelSheetSnapshot> snapshots;
+ if (sheet_tabs_) {
+ for (int i = 0; i < sheet_tabs_->count(); ++i) {
+ auto* sheet = qobject_cast<SpreadsheetWidget*>(sheet_tabs_->widget(i));
+ if (!sheet)
+ continue;
+ snapshots.append({sheet->sheet_name(), sheet->get_data()});
+ }
+ }
+ if (snapshots.isEmpty()) {
+ QMessageBox::warning(this, tr("Export failed"), tr("There is nothing to export."));
+ return;
+ }
+
+ // `this` can still be destroyed while the modal dialog is open; every
+ // member touched after it returns is guarded on the QPointer.
+ QPointer<ExcelScreen> self = this;
+ QString path = QFileDialog::getSaveFileName(this, tr("Export as XLSX"), file_name_, tr("Excel Files (*.xlsx)"));
+ if (!self || path.isEmpty())
+ return;
+ // QFileDialog on Linux/macOS does not always append the filter suffix.
+ if (!path.endsWith(QLatin1String(".xlsx"), Qt::CaseInsensitive))
+ path += QLatin1String(".xlsx");
+
+ QXlsx::Document xlsx;
+ if (!write_snapshots_to_xlsx(xlsx, snapshots)) {
+ QMessageBox::warning(this, tr("Export failed"), tr("Could not build the workbook contents."));
+ return;
}
if (xlsx.saveAs(path)) {
@@ -472,42 +688,55 @@ void ExcelScreen::on_export_csv() {
if (!sheet)
return;
- QString path =
- QFileDialog::getSaveFileName(this, tr("Export CSV"), sheet->sheet_name() + ".csv", tr("CSV Files (*.csv)"));
- if (path.isEmpty())
- return;
+ // Snapshot before the dialog — same re-entrancy hazard as on_export: the
+ // modal loop can run queued work that rebuilds the Excel dock and frees
+ // `sheet`. Reading it afterwards is a use-after-free.
+ const QString sheet_name = sheet->sheet_name();
+ const QVector<QVector<QString>> cells = sheet->get_data();
- QFile file(path);
- if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
- QMessageBox::warning(this, tr("Export failed"), tr("Could not open file for writing:\n%1").arg(path));
+ QPointer<ExcelScreen> self = this;
+ QString path = QFileDialog::getSaveFileName(this, tr("Export CSV"), sheet_name + ".csv", tr("CSV Files (*.csv)"));
+ if (!self || path.isEmpty())
return;
- }
-
- QTextStream out(&file);
- out.setEncoding(QStringConverter::Utf8);
- auto cells = sheet->get_data();
+ if (!path.endsWith(QLatin1String(".csv"), Qt::CaseInsensitive))
+ path += QLatin1String(".csv");
// Find the last row/col with data to avoid huge trailing empty rows
- int last_row = 0;
- int last_col = 0;
+ int last_row = -1;
+ int last_col = -1;
for (int r = 0; r < cells.size(); ++r) {
for (int c = 0; c < cells[r].size(); ++c) {
- if (!cells[r][c].isEmpty()) {
+ if (!cells[r][c].trimmed().isEmpty()) {
last_row = std::max(last_row, r);
last_col = std::max(last_col, c);
}
}
}
- for (int r = 0; r <= last_row; ++r) {
- QStringList row;
- for (int c = 0; c <= last_col; ++c) {
- QString val = (c < cells[r].size()) ? cells[r][c] : "";
- if (val.contains(',') || val.contains('"') || val.contains('\n'))
- val = "\"" + val.replace("\"", "\"\"") + "\"";
- row << val;
+ // Scoped so the stream flushes and the file closes BEFORE File Manager
+ // copies it. Previously both were destroyed at end of function — i.e. after
+ // import_file — so the Files tab could receive a truncated copy.
+ {
+ QFile file(path);
+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
+ QMessageBox::warning(this, tr("Export failed"), tr("Could not open file for writing:\n%1").arg(path));
+ return;
+ }
+ QTextStream out(&file);
+ out.setEncoding(QStringConverter::Utf8);
+
+ for (int r = 0; r <= last_row; ++r) {
+ QStringList row;
+ for (int c = 0; c <= last_col; ++c) {
+ QString val = (r < cells.size() && c < cells[r].size()) ? cells[r][c] : QString();
+ if (val.contains(',') || val.contains('"') || val.contains('\n'))
+ val = "\"" + val.replace("\"", "\"\"") + "\"";
+ row << val;
+ }
+ out << row.join(",") << "\n";
}
- out << row.join(",") << "\n";
+ out.flush();
+ file.close();
}
LOG_INFO("ExcelScreen", QString("Exported CSV to %1").arg(path));
diff --git a/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp b/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
index 0f90add5b..63dd6bd48 100644
--- a/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
+++ b/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
@@ -6,6 +6,8 @@
#include <QApplication>
#include <QClipboard>
#include <QHBoxLayout>
+#include <QFontMetrics>
+#include <QHash>
#include <QHeaderView>
#include <QInputDialog>
#include <QKeySequence>
@@ -35,6 +37,10 @@ SpreadsheetItem::SpreadsheetItem() : QTableWidgetItem(QTableWidgetItem::UserType
SpreadsheetItem::SpreadsheetItem(const QString& text) : QTableWidgetItem(QTableWidgetItem::UserType), raw_text_(text) {}
+QTableWidgetItem* SpreadsheetItem::clone() const {
+ return new SpreadsheetItem(raw_text_);
+}
+
void SpreadsheetItem::setData(int role, const QVariant& value) {
if (role == Qt::EditRole) {
raw_text_ = value.toString();
@@ -49,6 +55,41 @@ QVariant SpreadsheetItem::data(int role) const {
if (role == Qt::DisplayRole || role == Qt::EditRole) {
return raw_text_;
}
+
+ // ── Presentation ─────────────────────────────────────────────────────
+ // The grid rendered every cell identically: left-aligned, same weight. A
+ // financial model laid out that way is unreadable — figures don't line up
+ // on the decimal and section headings look like data. Both are derived
+ // from the raw text, never from evaluating the formula, so painting stays
+ // cheap.
+ if (role == Qt::TextAlignmentRole) {
+ bool numeric = false;
+ raw_text_.toDouble(&numeric);
+ const bool right = numeric || raw_text_.startsWith(QLatin1Char('='));
+ return QVariant(static_cast<int>((right ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignVCenter));
+ }
+
+ if (role == Qt::FontRole) {
+ // A label in column A with nothing beside it is a section heading
+ // ("INPUTS & ASSUMPTIONS"), not a data row.
+ if (column() == 0 && !raw_text_.trimmed().isEmpty()) {
+ const auto* tbl = tableWidget();
+ if (tbl) {
+ bool row_is_bare = true;
+ for (int c = 1; c < tbl->columnCount() && row_is_bare; ++c) {
+ const auto* other = tbl->item(row(), c);
+ if (other && !other->data(Qt::EditRole).toString().trimmed().isEmpty())
+ row_is_bare = false;
+ }
+ if (row_is_bare) {
+ QFont f = tbl->font();
+ f.setBold(true);
+ return f;
+ }
+ }
+ }
+ }
+
return QTableWidgetItem::data(role);
}
@@ -123,12 +164,45 @@ QVariant SpreadsheetItem::evaluate_formula() const {
static thread_local QSet<const SpreadsheetItem*> evaluating;
if (evaluating.contains(this))
return QStringLiteral("#CYCLE");
+
+ // ── Memoise within one evaluation pass ────────────────────────────────
+ // Formulas are evaluated lazily from data(DisplayRole), and each one reads
+ // its dependencies' DisplayRole, which evaluates THEM from scratch. On a
+ // chain — the shape of every financial model, Revenue → EBIT → NOPAT → FCF
+ // → PV → EV → equity → per-share — that is O(2^depth) per cell, and the
+ // whole grid repaints together. A DCF was enough to wedge the UI thread
+ // long enough for set_excel_sheet_data to blow its timeout mid-write.
+ //
+ // The cache lives only for the outermost evaluation: entries are dropped
+ // when the last frame unwinds, so an edit is still picked up immediately.
+ // Invalidation is therefore not a concern — nothing can change while a
+ // single synchronous pass is running.
+ static thread_local QHash<const SpreadsheetItem*, QVariant> eval_cache;
+ static thread_local int eval_depth = 0;
+ const auto cached = eval_cache.constFind(this);
+ if (cached != eval_cache.constEnd())
+ return cached.value();
+
evaluating.insert(this);
+ ++eval_depth;
struct EvalGuard {
const SpreadsheetItem* item;
- ~EvalGuard() { evaluating.remove(item); }
+ ~EvalGuard() {
+ evaluating.remove(item);
+ if (--eval_depth == 0)
+ eval_cache.clear();
+ }
} eval_guard{this};
+ // Store into the cache on every return path.
+ struct Memo {
+ const SpreadsheetItem* item;
+ QVariant operator()(QVariant v) const {
+ eval_cache.insert(item, v);
+ return v;
+ }
+ } memo{this};
+
QString expr = raw_text_.mid(1).trimmed().toUpper();
// ── Function calls: SUM, AVG/AVERAGE, MIN, MAX, COUNT ────────────────
@@ -138,18 +212,18 @@ QVariant SpreadsheetItem::evaluate_formula() const {
QString func = fm.captured(1);
auto vals = resolve_range(fm.captured(2), fm.captured(3));
if (vals.isEmpty())
- return 0.0;
+ return memo(0.0);
if (func == "SUM")
- return std::accumulate(vals.begin(), vals.end(), 0.0);
+ return memo(std::accumulate(vals.begin(), vals.end(), 0.0));
if (func == "AVG" || func == "AVERAGE")
- return std::accumulate(vals.begin(), vals.end(), 0.0) / vals.size();
+ return memo(std::accumulate(vals.begin(), vals.end(), 0.0) / vals.size());
if (func == "MIN")
- return *std::min_element(vals.begin(), vals.end());
+ return memo(*std::min_element(vals.begin(), vals.end()));
if (func == "MAX")
- return *std::max_element(vals.begin(), vals.end());
+ return memo(*std::max_element(vals.begin(), vals.end()));
if (func == "COUNT")
- return static_cast<double>(vals.size());
+ return memo(static_cast<double>(vals.size()));
}
// ── Simple cell reference: =A1 ───────────────────────────────────────
@@ -159,7 +233,7 @@ QVariant SpreadsheetItem::evaluate_formula() const {
int r, c;
parse_cell_ref(expr, r, c);
if (r >= 0 && c >= 0)
- return resolve_cell_value(r, c);
+ return memo(resolve_cell_value(r, c));
}
// ── Simple arithmetic with cell refs: =A1+B1, =A1*2, etc. ───────────
@@ -191,7 +265,7 @@ QVariant SpreadsheetItem::evaluate_formula() const {
// Validate: only digits, operators, decimal points, parens
static QRegularExpression valid_re("^[0-9+\\-*/().eE]+$");
if (!valid_re.match(eval_expr).hasMatch()) {
- return "#ERR";
+ return memo("#ERR");
}
// Use a simple recursive descent parser
@@ -266,48 +340,48 @@ QVariant SpreadsheetItem::evaluate_formula() const {
num_buf += ch;
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
if (!flush_num())
- return QVariant("#ERR");
+ return memo(QVariant("#ERR"));
while (!ops.isEmpty() && ops.last() != '(' && precedence(ops.last()) >= precedence(ch)) {
if (!apply_op())
- return QVariant(div_zero ? "#DIV/0!" : "#ERR");
+ return memo(QVariant(div_zero ? "#DIV/0!" : "#ERR"));
}
ops.append(ch);
} else if (ch == '(') {
ops.append(ch);
} else if (ch == ')') {
if (!flush_num())
- return QVariant("#ERR");
+ return memo(QVariant("#ERR"));
while (!ops.isEmpty() && ops.last() != '(') {
if (!apply_op())
- return QVariant(div_zero ? "#DIV/0!" : "#ERR");
+ return memo(QVariant(div_zero ? "#DIV/0!" : "#ERR"));
}
if (ops.isEmpty())
- return QVariant("#ERR"); // ')' with no matching '('
+ return memo(QVariant("#ERR")); // ')' with no matching '('
ops.removeLast(); // remove '('
}
}
if (!flush_num())
- return QVariant("#ERR");
+ return memo(QVariant("#ERR"));
while (!ops.isEmpty()) {
if (!apply_op())
- return QVariant(div_zero ? "#DIV/0!" : "#ERR");
+ return memo(QVariant(div_zero ? "#DIV/0!" : "#ERR"));
}
if (nums.size() == 1) {
double result = nums.first();
if (!std::isfinite(result))
- return QVariant("#NUM!");
+ return memo(QVariant("#NUM!"));
if (std::floor(result) == result && std::abs(result) < 1e15)
- return static_cast<qlonglong>(result);
+ return memo(static_cast<qlonglong>(result));
// 'g' with 12 significant digits: 2.5 renders as "2.5", not
// "2.500000", while still keeping precision on long decimals.
- return QString::number(result, 'g', 12);
+ return memo(QString::number(result, 'g', 12));
}
} catch (...) {
// fall through
}
- return "#ERR";
+ return memo("#ERR");
}
// ═════════════════════════════════════════════════════════════════════════════
@@ -362,6 +436,9 @@ void SpreadsheetWidget::build_ui(int rows, int cols) {
// Table
table_ = new QTableWidget(rows, cols, this);
+ // Cells are created lazily (see below); the prototype makes every implicitly
+ // created cell a formula-aware SpreadsheetItem rather than a plain one.
+ table_->setItemPrototype(new SpreadsheetItem());
setup_headers(cols);
table_->setSelectionMode(QAbstractItemView::ExtendedSelection);
@@ -374,12 +451,12 @@ void SpreadsheetWidget::build_ui(int rows, int cols) {
table_->setAlternatingRowColors(false);
table_->setContextMenuPolicy(Qt::CustomContextMenu);
- // Pre-populate with SpreadsheetItems
- for (int r = 0; r < rows; ++r) {
- for (int c = 0; c < cols; ++c) {
- table_->setItem(r, c, new SpreadsheetItem());
- }
- }
+ // Cells are deliberately NOT pre-populated. A 20 000 × 512 import window is
+ // 10.2M cells; allocating a SpreadsheetItem for each here cost ~2 GB and
+ // several seconds on the UI thread, and set_data() then threw the whole lot
+ // away and allocated a second set. Every read path tolerates a null item
+ // (cell_text/get_data return "", set_cell creates on demand), so an empty
+ // grid costs nothing until something is actually written to it.
connect(table_, &QTableWidget::cellChanged, this, &SpreadsheetWidget::on_cell_changed);
connect(table_, &QTableWidget::currentCellChanged, this, &SpreadsheetWidget::on_current_cell_changed);
@@ -495,21 +572,67 @@ void SpreadsheetWidget::set_data(const QVector<QVector<QString>>& cells) {
table_->setColumnCount(cols);
setup_headers(cols);
- for (int r = 0; r < rows; ++r) {
- for (int c = 0; c < cols; ++c) {
- QString text;
- if (r < cells.size() && c < cells[r].size()) {
- text = cells[r][c];
- }
- auto* item = new SpreadsheetItem(text);
- table_->setItem(r, c, item);
+ // Allocate ONLY the cells that carry a value. The old loop allocated
+ // rows × cols items unconditionally — for a 20 000-row import that is
+ // millions of heap objects for cells that are, and stay, empty. Anything
+ // reading a missing cell already gets "" (cell_text / get_data), and the
+ // item prototype materialises a real SpreadsheetItem the moment the user
+ // types into one.
+ table_->clearContents(); // drop any items from a previous load
+ for (int r = 0; r < cells.size() && r < rows; ++r) {
+ const auto& src_row = cells[r];
+ for (int c = 0; c < src_row.size() && c < cols; ++c) {
+ if (src_row[c].isEmpty())
+ continue;
+ table_->setItem(r, c, new SpreadsheetItem(src_row[c]));
}
}
table_->blockSignals(false);
+ autofit_columns(cells);
recalculate();
}
+// Size columns to their content.
+//
+// Every column sat at the fixed 80 px default, so a model written into the grid
+// showed as "Terminal …" / "Effective…" — the labels that make it readable were
+// exactly the ones clipped. Widths are measured from the source text with the
+// table's own font rather than via resizeColumnsToContents(), which would walk
+// all 2 600 cells and evaluate every formula just to measure it.
+void SpreadsheetWidget::autofit_columns(const QVector<QVector<QString>>& cells) {
+ constexpr int kMinWidth = 64;
+ constexpr int kMaxWidth = 340; // past this, wrapping/scrolling beats widening
+ constexpr int kPadding = 18;
+
+ // Text shaping is the expensive part: one horizontalAdvance() per non-empty
+ // cell. On a large import that is millions of shaping calls on the UI thread
+ // for column widths that are already decided by the first screenful of rows.
+ // Sample the head of the sheet instead — headers and the first data rows are
+ // what actually set the width.
+ constexpr int kMaxMeasuredRows = 200;
+ const int measured_rows = std::min<int>(cells.size(), kMaxMeasuredRows);
+
+ const QFontMetrics fm(table_->font());
+ // A formula's text is far longer than the number it produces; measuring the
+ // source would push its column to the cap. Budget for a typical result.
+ const int formula_width = fm.horizontalAdvance(QStringLiteral("1,234,567.89"));
+
+ for (int c = 0; c < table_->columnCount(); ++c) {
+ int width = kMinWidth;
+ for (int r = 0; r < measured_rows; ++r) {
+ if (c >= cells[r].size())
+ continue;
+ const QString& text = cells[r][c];
+ if (text.trimmed().isEmpty())
+ continue;
+ const int w = text.startsWith(QLatin1Char('=')) ? formula_width : fm.horizontalAdvance(text);
+ width = std::max(width, w + kPadding);
+ }
+ table_->setColumnWidth(c, std::clamp(width, kMinWidth, kMaxWidth));
+ }
+}
+
QString SpreadsheetWidget::cell_text(int row, int col) const {
auto* item = dynamic_cast<SpreadsheetItem*>(table_->item(row, col));
return item ? item->raw_text() : "";
@@ -523,6 +646,18 @@ void SpreadsheetWidget::set_cell(int row, int col, const QString& text) {
} else {
item->setData(Qt::EditRole, text);
}
+
+ // Grow the column if this value doesn't fit. A model written cell-by-cell
+ // (the set_excel_cell path) never goes through set_data, so without this it
+ // keeps the 80 px default and clips every label.
+ if (!text.startsWith(QLatin1Char('=')) && !text.trimmed().isEmpty() && col >= 0) {
+ constexpr int kMaxWidth = 340;
+ constexpr int kPadding = 18;
+ const QFontMetrics fm(table_->font());
+ const int needed = std::min(fm.horizontalAdvance(text) + kPadding, kMaxWidth);
+ if (needed > table_->columnWidth(col))
+ table_->setColumnWidth(col, needed);
+ }
}
void SpreadsheetWidget::recalculate() {
diff --git a/fincept-qt/src/screens/excel/SpreadsheetWidget.h b/fincept-qt/src/screens/excel/SpreadsheetWidget.h
index 6745f44f4..5f66a45c6 100644
--- a/fincept-qt/src/screens/excel/SpreadsheetWidget.h
+++ b/fincept-qt/src/screens/excel/SpreadsheetWidget.h
@@ -22,6 +22,14 @@ class SpreadsheetItem : public QTableWidgetItem {
QVariant data(int role) const override;
void setData(int role, const QVariant& value) override;
+ /// Qt clones the table's item prototype whenever the model has to
+ /// materialise a cell that has no item yet (typing into an empty cell,
+ /// pasting past the filled range, drag & drop). The base implementation
+ /// slices back to a plain QTableWidgetItem, which would silently disable
+ /// formula evaluation for that cell — the grid is no longer pre-populated,
+ /// so this is now the common path, not an edge case.
+ QTableWidgetItem* clone() const override;
+
/// The raw text (may be a formula starting with '=')
QString raw_text() const { return raw_text_; }
@@ -98,6 +106,9 @@ class SpreadsheetWidget : public QWidget {
private:
void build_ui(int rows, int cols);
void setup_headers(int cols);
+ /// Size each column to its widest value (clamped). Measured from the source
+ /// text so formulas don't have to be evaluated just to lay the grid out.
+ void autofit_columns(const QVector<QVector<QString>>& cells);
void install_shortcuts();
static QString column_label(int col);
diff --git a/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp b/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp
index 97922c0a4..9731e3a83 100644
--- a/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp
+++ b/fincept-qt/src/screens/fno/MultiStraddleSubTab.cpp
@@ -203,6 +203,20 @@ void MultiStraddleSubTab::showEvent(QShowEvent* e) {
void MultiStraddleSubTab::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
+ // §D3: pair the showEvent subscribe. The `chain_subscribed_` latch never
+ // reset and on_chain_published() has no visibility gate, so a hidden tab
+ // kept rebuilding on every option-chain publish for the rest of the
+ // process.
+ //
+ // unsubscribe_pattern(), not the blanket unsubscribe(this): this tab also
+ // owns per-token `subscribe()` entries created by subscribe_token(), whose
+ // lifetime is tracked by token_refcount_ / topic_for_token_ and released
+ // by remove_selection(). Dropping those here would leave the refcounts
+ // populated with no subscription behind them, so subscribe_token() would
+ // short-circuit on re-show and the selections' OI history would never come
+ // back.
+ fincept::datahub::DataHub::instance().unsubscribe_pattern(this, QStringLiteral("option:chain:*"));
+ chain_subscribed_ = false;
}
void MultiStraddleSubTab::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/fno/OISubTab.cpp b/fincept-qt/src/screens/fno/OISubTab.cpp
index 24b564cb5..a0697b4ae 100644
--- a/fincept-qt/src/screens/fno/OISubTab.cpp
+++ b/fincept-qt/src/screens/fno/OISubTab.cpp
@@ -168,6 +168,19 @@ void OISubTab::showEvent(QShowEvent* e) {
void OISubTab::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
+ // §D3: pair the showEvent subscribe. Without this the `subscribed_` latch
+ // never resets, and on_chain_published() has no visibility gate — so a
+ // hidden tab kept driving oi_bars_->set_chain(), pain_chart_->set_chain()
+ // and buildup_model()->set_chain() on every option-chain publish for the
+ // rest of the process. These tabs live in a QStackedWidget, so one visit
+ // armed it permanently.
+ //
+ // unsubscribe_pattern() rather than the blanket unsubscribe(this) so this
+ // stays symmetric with the subscribe_pattern() above and can't collaterally
+ // drop any concrete-topic subscription added here later (the sibling
+ // MultiStraddleSubTab already has exactly that hazard).
+ fincept::datahub::DataHub::instance().unsubscribe_pattern(this, QStringLiteral("option:chain:*"));
+ subscribed_ = false;
}
void OISubTab::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/fno/ScreenerSubTab.cpp b/fincept-qt/src/screens/fno/ScreenerSubTab.cpp
index 0b47c84df..d7a78f1fe 100644
--- a/fincept-qt/src/screens/fno/ScreenerSubTab.cpp
+++ b/fincept-qt/src/screens/fno/ScreenerSubTab.cpp
@@ -340,6 +340,16 @@ void ScreenerSubTab::showEvent(QShowEvent* e) {
void ScreenerSubTab::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
+ // §D3: pair the showEvent subscribe. The `subscribed_` latch never reset
+ // and on_chain_published() has no visibility gate, so a hidden tab ran a
+ // full apply_filters() rebuild on every option-chain publish for the rest
+ // of the process.
+ //
+ // unsubscribe_pattern() rather than the blanket unsubscribe(this) so this
+ // stays symmetric with the subscribe_pattern() above and can't collaterally
+ // drop any concrete-topic subscription added here later.
+ fincept::datahub::DataHub::instance().unsubscribe_pattern(this, QStringLiteral("option:chain:*"));
+ subscribed_ = false;
}
void ScreenerSubTab::on_chain_published(const QVariant& v) {
diff --git a/fincept-qt/src/screens/info/TrademarksScreen.cpp b/fincept-qt/src/screens/info/TrademarksScreen.cpp
index 338f58fab..752cb4779 100644
--- a/fincept-qt/src/screens/info/TrademarksScreen.cpp
+++ b/fincept-qt/src/screens/info/TrademarksScreen.cpp
@@ -132,8 +132,9 @@ QWidget* TrademarksScreen::build_page() {
pvl->addWidget(heading("4", tr("COPYRIGHT NOTICE")));
pvl->addWidget(body(tr("Copyright 2024-2026 Fincept Corporation. All rights reserved.")));
- pvl->addWidget(body(tr("This software is licensed under AGPL-3.0-or-later for open source use, "
- "with a separate commercial license available for enterprise deployment.")));
+ pvl->addWidget(body(tr("This software is licensed under AGPL-3.0-or-later, and under no other licence. "
+ "Fincept Terminal Enterprise is a separate closed-source product and is not "
+ "covered by this licence.")));
pvl->addWidget(heading("5", tr("DATA PROVIDER ACKNOWLEDGMENTS")));
pvl->addWidget(bullet(tr("Market data provided by various exchanges and data vendors")));
diff --git a/fincept-qt/src/screens/markets/MarketPanelStore.cpp b/fincept-qt/src/screens/markets/MarketPanelStore.cpp
index cb65b2529..99c1939ef 100644
--- a/fincept-qt/src/screens/markets/MarketPanelStore.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanelStore.cpp
@@ -1,5 +1,6 @@
#include "screens/markets/MarketPanelStore.h"
+#include "core/logging/Logger.h"
#include "services/markets/MarketDataService.h"
#include "storage/repositories/SettingsRepository.h"
@@ -9,6 +10,18 @@
namespace fincept::screens {
+namespace {
+constexpr const char* kPanelStoreTag = "MarketPanels";
+
+/// Set when load() could not *read* the stored panel set (as opposed to
+/// reading a genuinely absent one). While it is set, save() refuses to write:
+/// the panels in memory are the built-in defaults, and MarketsScreen persists
+/// the whole set on every panel edit, so one transient DB error would otherwise
+/// replace the user's panels wholesale. Cleared by the next successful load,
+/// and by reset_to_defaults() (explicit user intent to overwrite).
+bool g_panel_load_failed = false;
+} // namespace
+
MarketPanelStore& MarketPanelStore::instance() {
static MarketPanelStore inst;
return inst;
@@ -16,7 +29,15 @@ MarketPanelStore& MarketPanelStore::instance() {
QVector<MarketPanelConfig> MarketPanelStore::load() {
auto result = SettingsRepository::instance().get(kSettingsKey);
- if (!result.is_ok() || result.value().isEmpty())
+ if (result.is_err()) {
+ LOG_ERROR(kPanelStoreTag, QString("settings read failed for '%1' — showing the built-in panels read-only, "
+ "leaving the stored set untouched: %2")
+ .arg(QString::fromLatin1(kSettingsKey), QString::fromStdString(result.error())));
+ g_panel_load_failed = true;
+ return build_defaults();
+ }
+ g_panel_load_failed = false;
+ if (result.value().isEmpty())
return build_defaults();
auto doc = QJsonDocument::fromJson(result.value().toUtf8());
@@ -66,6 +87,12 @@ QVector<MarketPanelConfig> MarketPanelStore::load() {
}
void MarketPanelStore::save(const QVector<MarketPanelConfig>& panels) {
+ if (g_panel_load_failed) {
+ LOG_WARN(kPanelStoreTag, "Skipping panel save — the stored panel set could not be read this session, so the "
+ "on-screen defaults must not overwrite it");
+ return;
+ }
+
QJsonArray arr;
for (const auto& cfg : panels) {
QJsonObject obj;
@@ -89,6 +116,9 @@ void MarketPanelStore::save(const QVector<MarketPanelConfig>& panels) {
}
void MarketPanelStore::reset_to_defaults() {
+ // Explicit user intent to overwrite the stored set with the defaults —
+ // the only path allowed to lift the read-failure guard.
+ g_panel_load_failed = false;
save(build_defaults());
}
diff --git a/fincept-qt/src/screens/news/NewsScreen.cpp b/fincept-qt/src/screens/news/NewsScreen.cpp
index 076c2593f..3df9b834b 100644
--- a/fincept-qt/src/screens/news/NewsScreen.cpp
+++ b/fincept-qt/src/screens/news/NewsScreen.cpp
@@ -350,20 +350,50 @@ void NewsScreen::showEvent(QShowEvent* e) {
if (first_show_) {
first_show_ = false;
- fincept::NewsArticleRepository::instance().ensure_seen_column();
- fincept::NewsArticleRepository::instance().ensure_saved_column();
+ // First entry used to run a schema migration (PRAGMA table_info +
+ // conditional ALTER TABLE) plus two unbounded SELECTs straight on the
+ // GUI thread, so opening News stalled in proportion to all accumulated
+ // history — invisible on a fresh install, worse every week. It now runs
+ // on a worker (Database hands out a per-thread SQLite connection) and
+ // the results are applied back here, guarded on both hops (§P1/§P8).
+ //
+ // TODO(cross-file): ensure_seen_column()/ensure_saved_column() are
+ // startup schema work and belong next to the other migrations in
+ // Database::open(); they sit here only until that move lands.
+ const int64_t since_ts = QDateTime::currentSecsSinceEpoch() - (30LL * 86400);
+ QPointer<NewsScreen> self = this;
+ (void)QtConcurrent::run([self, since_ts]() {
+ auto& repo = fincept::NewsArticleRepository::instance();
+ repo.ensure_seen_column();
+ repo.ensure_saved_column();
- int64_t since_ts = QDateTime::currentSecsSinceEpoch() - (30LL * 86400);
- auto seen_result = fincept::NewsArticleRepository::instance().load_seen_ids(since_ts);
- if (seen_result.is_ok()) {
- for (const auto& id : seen_result.value())
- feed_panel_->model()->mark_seen(id);
- }
+ QSet<QString> seen_ids;
+ if (auto seen_result = repo.load_seen_ids(since_ts); seen_result.is_ok())
+ seen_ids = seen_result.value();
+
+ QVector<services::NewsArticle> saved;
+ if (auto saved_result = repo.load_saved(); saved_result.is_ok())
+ saved = saved_result.value();
- auto saved_result = fincept::NewsArticleRepository::instance().load_saved();
- if (saved_result.is_ok())
- side_panel_->update_saved(saved_result.value());
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self,
+ [self, seen_ids = std::move(seen_ids), saved = std::move(saved)]() {
+ if (!self)
+ return;
+ for (const auto& id : seen_ids)
+ self->feed_panel_->model()->mark_seen(id);
+ self->side_panel_->update_saved(saved);
+ LOG_INFO("NewsScreen", QString("Restored %1 seen IDs and %2 bookmarks from DB")
+ .arg(seen_ids.size())
+ .arg(saved.size()));
+ },
+ Qt::QueuedConnection);
+ });
+ // Independent of the restore above — kick the feed fetch immediately so
+ // the screen starts filling while the worker runs.
LOG_INFO("NewsScreen", "showEvent: calling on_refresh");
on_refresh();
LOG_INFO("NewsScreen", "showEvent: on_refresh returned");
@@ -419,10 +449,10 @@ void NewsScreen::subscribe_mcp_events() {
};
auto& bus = EventBus::instance();
- mcp_event_subs_.append(bus.subscribe("news.monitor_added", on_monitors_changed));
- mcp_event_subs_.append(bus.subscribe("news.monitor_toggled", on_monitors_changed));
- mcp_event_subs_.append(bus.subscribe("news.monitor_deleted", on_monitors_changed));
- mcp_event_subs_.append(bus.subscribe("news.refresh_requested", on_refresh_requested));
+ mcp_event_subs_.append(bus.subscribe(this, "news.monitor_added", on_monitors_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "news.monitor_toggled", on_monitors_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "news.monitor_deleted", on_monitors_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "news.refresh_requested", on_refresh_requested));
}
void NewsScreen::unsubscribe_mcp_events() {
diff --git a/fincept-qt/src/screens/news/NewsTickerStrip.cpp b/fincept-qt/src/screens/news/NewsTickerStrip.cpp
index 9d99306bb..68ef0d6aa 100644
--- a/fincept-qt/src/screens/news/NewsTickerStrip.cpp
+++ b/fincept-qt/src/screens/news/NewsTickerStrip.cpp
@@ -80,6 +80,19 @@ void NewsTickerStrip::resume() {
scroll_timer_.start();
}
+void NewsTickerStrip::showEvent(QShowEvent* event) {
+ QWidget::showEvent(event);
+ // Respect an explicit pause() (hover-to-read / edit) — visibility must not
+ // silently override a deliberate pause the user is relying on.
+ if (!paused_ && !entries_.isEmpty())
+ scroll_timer_.start();
+}
+
+void NewsTickerStrip::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ scroll_timer_.stop();
+}
+
void NewsTickerStrip::paintEvent(QPaintEvent*) {
if (entries_.isEmpty())
return;
diff --git a/fincept-qt/src/screens/news/NewsTickerStrip.h b/fincept-qt/src/screens/news/NewsTickerStrip.h
index 46c182abd..18ee09b6d 100644
--- a/fincept-qt/src/screens/news/NewsTickerStrip.h
+++ b/fincept-qt/src/screens/news/NewsTickerStrip.h
@@ -27,6 +27,14 @@ class NewsTickerStrip : public QWidget {
void mousePressEvent(QMouseEvent* event) override;
void enterEvent(QEnterEvent* event) override;
void leaveEvent(QEvent* event) override;
+ /// P3: the scroll timer must not run while this strip is invisible. It was
+ /// previously driven only by the owning screen calling pause()/resume(), so
+ /// a refactor that dropped one of those calls left a 20fps antialiased paint
+ /// running behind a hidden tab with nothing to notice it. These overrides
+ /// make the invariant self-enforcing; pause()/resume() remain for the
+ /// explicit hover-to-read and edit cases, which are not visibility events.
+ void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private:
struct TickerEntry {
diff --git a/fincept-qt/src/screens/notes/NotesScreen.cpp b/fincept-qt/src/screens/notes/NotesScreen.cpp
index a4f46cf40..bae511356 100644
--- a/fincept-qt/src/screens/notes/NotesScreen.cpp
+++ b/fincept-qt/src/screens/notes/NotesScreen.cpp
@@ -1090,8 +1090,8 @@ void NotesScreen::subscribe_mcp_events() {
};
auto& bus = EventBus::instance();
- mcp_event_subs_.append(bus.subscribe("notes.created", on_notes_changed));
- mcp_event_subs_.append(bus.subscribe("notes.deleted", on_notes_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "notes.created", on_notes_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "notes.deleted", on_notes_changed));
}
void NotesScreen::unsubscribe_mcp_events() {
diff --git a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
index a4a9c68b6..2c9770778 100644
--- a/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/AnalyticsSectorsView.cpp
@@ -567,8 +567,13 @@ void AnalyticsSectorsView::update_sector_table(const QVector<SectorInfo>& sector
const auto& s = sectors[r];
sector_table_->setRowHeight(r, 30);
- // Col 0 — color swatch
- sector_table_->setCellWidget(r, 0, new Swatch(sector_color(r), 10, 10, sector_table_));
+ // Col 0 — color swatch. Construct only when the cell is empty: the colour
+ // is a pure function of the row index and never changes, but setCellWidget()
+ // destroys the previous occupant, so the old unconditional form churned the
+ // full swatch set on every 60s poll. (The surrounding code already goes out
+ // of its way to preserve the user's selection across this rebuild.)
+ if (!sector_table_->cellWidget(r, 0))
+ sector_table_->setCellWidget(r, 0, new Swatch(sector_color(r), 10, 10, sector_table_));
auto set_text = [&](int col, const QString& text, QColor color, Qt::Alignment align) {
auto* item = new QTableWidgetItem(text);
diff --git a/fincept-qt/src/screens/portfolio/views/PlanningView.cpp b/fincept-qt/src/screens/portfolio/views/PlanningView.cpp
index 9035fa77e..c106ba602 100644
--- a/fincept-qt/src/screens/portfolio/views/PlanningView.cpp
+++ b/fincept-qt/src/screens/portfolio/views/PlanningView.cpp
@@ -1,6 +1,7 @@
// src/screens/portfolio/views/PlanningView.cpp
#include "screens/portfolio/views/PlanningView.h"
+#include "core/logging/Logger.h"
#include "storage/repositories/SettingsRepository.h"
#include "ui/theme/Theme.h"
@@ -28,6 +29,14 @@
namespace fincept::screens {
+namespace {
+/// Dynamic-property guard set by load_goals() when the stored goal array could
+/// not be *read*. While it is set, save_goals() refuses to write: goals_ was
+/// emptied for display, and the next add/remove would persist that truncation
+/// over the user's real goals. Cleared by the next successful load.
+constexpr const char* kGoalsReadFailedProp = "fincept_goals_read_failed";
+} // namespace
+
PlanningView::PlanningView(QWidget* parent) : QWidget(parent) {
build_ui();
}
@@ -926,8 +935,21 @@ void PlanningView::load_goals() {
goals_.clear();
const QString pid = summary_.portfolio.id;
if (!pid.isEmpty()) {
- auto res = SettingsRepository::instance().get(QString("pi.goals.%1").arg(pid));
- if (res.is_ok() && !res.value().isEmpty()) {
+ const QString key = QString("pi.goals.%1").arg(pid);
+ auto res = SettingsRepository::instance().get(key);
+ if (res.is_err()) {
+ // A read error is not "no goals". The empty list above is a display
+ // fallback only — arm the guard so the next add/remove cannot
+ // persist it over the user's real goals.
+ LOG_ERROR("Planning", QString("settings read failed for '%1' — showing an empty goal list read-only, "
+ "leaving the stored goals untouched: %2")
+ .arg(key, QString::fromStdString(res.error())));
+ setProperty(kGoalsReadFailedProp, true);
+ refresh_goals_list();
+ return;
+ }
+ setProperty(kGoalsReadFailedProp, false);
+ if (!res.value().isEmpty()) {
const auto doc = QJsonDocument::fromJson(res.value().toUtf8());
for (const auto v : doc.array()) {
const auto o = v.toObject();
@@ -940,6 +962,8 @@ void PlanningView::load_goals() {
goals_.append(g);
}
}
+ } else {
+ setProperty(kGoalsReadFailedProp, false);
}
refresh_goals_list();
}
@@ -948,6 +972,14 @@ void PlanningView::save_goals() {
const QString pid = summary_.portfolio.id;
if (pid.isEmpty())
return;
+ if (property(kGoalsReadFailedProp).toBool()) {
+ LOG_WARN("Planning", "Skipping goal save — the stored goals could not be read, so the list on screen is "
+ "empty rather than the user's goals");
+ QMessageBox::warning(this, tr("Goals Not Saved"),
+ tr("Your saved goals could not be read from the database, so this change was not "
+ "saved — nothing stored was overwritten. Reopen this view to retry."));
+ return;
+ }
QJsonArray arr;
for (const auto& g : goals_) {
QJsonObject o;
diff --git a/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp b/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
index 0810a87ea..15c032f59 100644
--- a/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
+++ b/fincept-qt/src/screens/portfolio_monitor/PortfolioMonitorScreen.cpp
@@ -1,6 +1,7 @@
// PortfolioMonitorScreen.cpp — unified all-accounts positions & holdings.
#include "screens/portfolio_monitor/PortfolioMonitorScreen.h"
+#include "core/logging/Logger.h"
#include "storage/repositories/SettingsRepository.h"
#include "trading/TradingTypes.h"
#include "trading/UnifiedPortfolioService.h"
@@ -19,6 +20,7 @@
#include <QPushButton>
#include <QScrollArea>
#include <QShowEvent>
+#include <QSignalBlocker>
#include <QSpinBox>
#include <QTabWidget>
#include <QTimer>
@@ -40,6 +42,12 @@ namespace {
// shows invested/current in the parent tooltip.
enum Col { ColSymbol = 0, ColProduct, ColQty, ColAvg, ColLtp, ColPnl, ColPnlPct, ColAction, ColCount };
+/// Dynamic-property guard set around the showEvent() fallback that routes the
+/// screen to PAPER after a *failed* read of portfolio_monitor.mode. While it is
+/// set, on_mode_toggled() applies the mode but does not persist it, so a
+/// transient DB error cannot demote a LIVE user to paper on disk.
+constexpr const char* kModePersistSuppressedProp = "fincept_mode_persist_suppressed";
+
const QString kRupee = QString::fromUtf8("₹");
QString fmt_money(double v, bool signed_pfx = false) {
@@ -105,11 +113,24 @@ void PortfolioMonitorScreen::showEvent(QShowEvent* event) {
// on a state change, so style/route the paper default explicitly.
const auto saved =
SettingsRepository::instance().get(QStringLiteral("portfolio_monitor.mode"), QStringLiteral("paper"));
- const bool live = saved.is_ok() && saved.value() == QLatin1String("live");
- if (live)
+ if (saved.is_err()) {
+ LOG_ERROR("PortfolioMonitor",
+ QString("settings read failed for 'portfolio_monitor.mode' — showing PAPER for this session, "
+ "leaving the stored mode untouched: %1")
+ .arg(QString::fromStdString(saved.error())));
+ // The stored mode is unknown, not "paper". Apply paper in memory
+ // (styles + routes the service) with the persist suppressed, and
+ // block mode_btn_ so an already-checked button can't re-enter
+ // on_mode_toggled() via toggled().
+ const QSignalBlocker block(mode_btn_);
+ setProperty(kModePersistSuppressedProp, true);
+ on_mode_toggled(false);
+ setProperty(kModePersistSuppressedProp, false);
+ } else if (saved.value() == QLatin1String("live")) {
mode_btn_->setChecked(true); // fires on_mode_toggled(true)
- else
+ } else {
on_mode_toggled(false);
+ }
}
// activate() is idempotent: picks up newly-added accounts and forces a
// portfolio refresh, so reopening the panel always shows fresh data.
@@ -241,8 +262,11 @@ void PortfolioMonitorScreen::on_mode_toggled(bool live) {
: tr("Showing paper portfolios — click for live"));
UnifiedPortfolioService::instance().set_mode(live ? UnifiedPortfolioService::Mode::Live
: UnifiedPortfolioService::Mode::Paper);
- SettingsRepository::instance().set(QStringLiteral("portfolio_monitor.mode"),
- live ? QStringLiteral("live") : QStringLiteral("paper"));
+ // Suppressed only by the showEvent() fallback after a failed read — writing
+ // "paper" there would overwrite a stored "live".
+ if (!property(kModePersistSuppressedProp).toBool())
+ SettingsRepository::instance().set(QStringLiteral("portfolio_monitor.mode"),
+ live ? QStringLiteral("live") : QStringLiteral("paper"));
rebuild_positions();
rebuild_holdings();
update_summary();
diff --git a/fincept-qt/src/screens/settings/AppearanceSection.cpp b/fincept-qt/src/screens/settings/AppearanceSection.cpp
index 5012ab75f..ff5b23200 100644
--- a/fincept-qt/src/screens/settings/AppearanceSection.cpp
+++ b/fincept-qt/src/screens/settings/AppearanceSection.cpp
@@ -28,6 +28,11 @@ constexpr const char* kDefaultFontSize = "14px";
constexpr const char* kDefaultFontFamily = "Consolas";
constexpr const char* kDefaultDensity = "Default";
+/// Dynamic-property guard set by reload() when a settings *read* failed. While
+/// it is set, Save is disabled and its handler refuses to write — the widgets
+/// hold defaults, not the user's values, and set() is an INSERT OR REPLACE.
+constexpr const char* kAppearanceReadFailedProp = "fincept_appearance_read_failed";
+
// make_row() (shared helper in SettingsRowHelpers.h) builds the label — and the
// optional description — QLabel internally and only returns the row widget. To
// re-translate those at runtime we grab them back from the row's direct child
@@ -242,6 +247,12 @@ void AppearanceSection::build_ui() {
save_btn_->setAccessibleName(tr("Save appearance settings"));
save_btn_->setStyleSheet(btn_primary_ss());
connect(save_btn_, &QPushButton::clicked, this, [this]() {
+ if (property(kAppearanceReadFailedProp).toBool()) {
+ LOG_WARN("Settings", "Refusing to save appearance settings — the stored values could not be read, so "
+ "the widgets on screen are defaults rather than the user's settings");
+ return;
+ }
+
auto& repo = SettingsRepository::instance();
repo.set("appearance.font_size", app_font_size_->currentText(), "appearance");
@@ -294,9 +305,22 @@ void AppearanceSection::reload() {
const QSignalBlocker b2(app_font_family_);
const QSignalBlocker b4(app_density_);
+ // A read error is not "unset". The Save handler writes every widget on this
+ // page straight back, so a failed read must disarm Save; the default is
+ // still used in memory so the page renders something sensible.
+ bool read_failed = false;
+ auto log_read_error = [&read_failed](const QString& key, const std::string& err) {
+ LOG_ERROR("Settings", QString("settings read failed for '%1' — showing the default, leaving the stored "
+ "value untouched and disabling Save: %2")
+ .arg(key, QString::fromStdString(err)));
+ read_failed = true;
+ };
+
auto load_combo = [&](QComboBox* cb, const QString& key, const QString& def) {
auto r = repo.get(key);
- QString val = r.is_ok() ? r.value() : def;
+ if (r.is_err())
+ log_read_error(key, r.error());
+ const QString val = r.is_ok() ? r.value() : def;
int idx = cb->findText(val);
if (idx >= 0)
cb->setCurrentIndex(idx);
@@ -306,7 +330,12 @@ void AppearanceSection::reload() {
if (!cb)
return;
auto r = repo.get(key);
- cb->setChecked(!r.is_ok() ? def : r.value() != "false");
+ if (r.is_err()) {
+ log_read_error(key, r.error());
+ cb->setChecked(def);
+ return;
+ }
+ cb->setChecked(r.value() != "false");
};
load_combo(app_font_size_, "appearance.font_size", kDefaultFontSize);
@@ -316,6 +345,15 @@ void AppearanceSection::reload() {
load_check(chat_bubble_toggle_, "appearance.show_chat_bubble", true);
load_check(ticker_bar_toggle_, "appearance.show_ticker_bar", true);
load_check(animations_toggle_, "appearance.animations", true);
+
+ setProperty(kAppearanceReadFailedProp, read_failed);
+ if (save_btn_) {
+ save_btn_->setEnabled(!read_failed);
+ save_btn_->setToolTip(read_failed ? tr("Your saved appearance settings could not be read — saving is "
+ "disabled so the defaults shown cannot overwrite them. Reopen "
+ "Settings to retry.")
+ : QString());
+ }
}
void AppearanceSection::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/settings/NotificationsSection.cpp b/fincept-qt/src/screens/settings/NotificationsSection.cpp
index 155937a23..7d94383ef 100644
--- a/fincept-qt/src/screens/settings/NotificationsSection.cpp
+++ b/fincept-qt/src/screens/settings/NotificationsSection.cpp
@@ -25,6 +25,15 @@ namespace fincept::screens {
namespace {
+/// Dynamic-property guards set by reload() when a settings *read* failed.
+/// `kNotifProviderReadFailedProp` lives on each provider's body_frame (the only
+/// handle save_provider_fields() has); `kNotifTriggersReadFailedProp` lives on
+/// the section itself and covers the eight alert-trigger booleans. While set,
+/// the corresponding save path refuses to write — the widgets hold defaults,
+/// not the user's values, and set() is an INSERT OR REPLACE.
+constexpr const char* kNotifProviderReadFailedProp = "fincept_notif_provider_read_failed";
+constexpr const char* kNotifTriggersReadFailedProp = "fincept_notif_triggers_read_failed";
+
struct FieldDef {
QString key;
QString label;
@@ -383,14 +392,19 @@ void NotificationsSection::build_ui() {
connect(save_btn_, &QPushButton::clicked, this, [this]() {
auto& repo = SettingsRepository::instance();
auto b = [](bool v) { return v ? "1" : "0"; };
- repo.set("notifications.inapp", b(trigger_inapp_->isChecked()), "notifications");
- repo.set("notifications.price_alerts", b(trigger_price_->isChecked()), "notifications");
- repo.set("notifications.news_alerts", b(trigger_news_->isChecked()), "notifications");
- repo.set("notifications.order_fills", b(trigger_orders_->isChecked()), "notifications");
- repo.set("notifications.news_breaking", b(news_breaking_->isChecked()), "notifications");
- repo.set("notifications.news_monitors", b(news_monitors_->isChecked()), "notifications");
- repo.set("notifications.news_deviations", b(news_deviations_->isChecked()), "notifications");
- repo.set("notifications.news_flash", b(news_flash_->isChecked()), "notifications");
+ if (property(kNotifTriggersReadFailedProp).toBool()) {
+ LOG_WARN("Settings", "Skipping alert-trigger save — the stored triggers could not be read, so the "
+ "checkboxes on screen are defaults, not the user's values");
+ } else {
+ repo.set("notifications.inapp", b(trigger_inapp_->isChecked()), "notifications");
+ repo.set("notifications.price_alerts", b(trigger_price_->isChecked()), "notifications");
+ repo.set("notifications.news_alerts", b(trigger_news_->isChecked()), "notifications");
+ repo.set("notifications.order_fills", b(trigger_orders_->isChecked()), "notifications");
+ repo.set("notifications.news_breaking", b(news_breaking_->isChecked()), "notifications");
+ repo.set("notifications.news_monitors", b(news_monitors_->isChecked()), "notifications");
+ repo.set("notifications.news_deviations", b(news_deviations_->isChecked()), "notifications");
+ repo.set("notifications.news_flash", b(news_flash_->isChecked()), "notifications");
+ }
for (const auto& def : provider_defs())
save_provider_fields(def.id, provider_widgets_.value(def.id));
@@ -410,9 +424,21 @@ void NotificationsSection::reload() {
return;
auto& repo = SettingsRepository::instance();
+ // A read error is not "unset". Every value loaded here is written straight
+ // back by the Save handler (and, for provider fields, by Test Send), so any
+ // failed read must disarm the corresponding save path instead of letting a
+ // default masquerade as the stored value.
+ bool triggers_read_failed = false;
auto get_bool = [&](const QString& key, bool def) -> bool {
auto r = repo.get(key);
- return r.is_ok() && !r.value().isEmpty() ? (r.value() == "1") : def;
+ if (r.is_err()) {
+ LOG_ERROR("Settings", QString("settings read failed for '%1' — showing the default, saving of the alert "
+ "triggers is disabled: %2")
+ .arg(key, QString::fromStdString(r.error())));
+ triggers_read_failed = true;
+ return def;
+ }
+ return !r.value().isEmpty() ? (r.value() == "1") : def;
};
if (trigger_inapp_)
@@ -437,24 +463,56 @@ void NotificationsSection::reload() {
if (news_subopts_frame_)
news_subopts_frame_->setVisible(news_on);
+ setProperty(kNotifTriggersReadFailedProp, triggers_read_failed);
+
for (const auto& def : provider_defs()) {
if (!provider_widgets_.contains(def.id))
continue;
const auto& pw = provider_widgets_[def.id];
const QString cat = QString("notif_%1").arg(def.id);
+ bool provider_read_failed = false;
if (pw.enabled) {
auto r = repo.get(cat + ".enabled");
- pw.enabled->setChecked(r.is_ok() && r.value() == "1");
+ if (r.is_err()) {
+ LOG_ERROR("Settings", QString("settings read failed for '%1' — leaving the stored value untouched: %2")
+ .arg(cat + ".enabled", QString::fromStdString(r.error())));
+ provider_read_failed = true;
+ } else {
+ pw.enabled->setChecked(r.value() == "1");
+ }
}
for (const auto& fd : def.fields) {
if (!pw.fields.contains(fd.key))
continue;
auto r = repo.get(cat + "." + fd.key);
- if (r.is_ok() && pw.fields[fd.key])
+ if (r.is_err()) {
+ // These fields are credentials — webhook URLs, bot tokens, SMTP
+ // passwords. Leave the box empty rather than pretending it is
+ // the stored value, and disarm the save path below so neither
+ // Save nor Test Send can write the blank over the real secret.
+ LOG_ERROR("Settings", QString("settings read failed for '%1' — leaving the stored credential "
+ "untouched: %2")
+ .arg(cat + "." + fd.key, QString::fromStdString(r.error())));
+ provider_read_failed = true;
+ continue;
+ }
+ if (pw.fields[fd.key])
pw.fields[fd.key]->setText(r.value());
}
+
+ // The guard lives on the provider's own widget so save_provider_fields()
+ // — which only receives the ProviderWidgets struct — can see it.
+ if (pw.body_frame)
+ pw.body_frame->setProperty(kNotifProviderReadFailedProp, provider_read_failed);
+ if (pw.test_btn)
+ pw.test_btn->setEnabled(!provider_read_failed);
+ if (provider_read_failed && pw.status_lbl)
+ pw.status_lbl->setText(tr("Could not read this provider's saved settings — saving is disabled so the "
+ "blank fields cannot overwrite them. Reopen Settings to retry."));
+ else if (pw.status_lbl)
+ pw.status_lbl->clear();
}
}
@@ -525,6 +583,13 @@ void NotificationsSection::retranslateUi() {
}
void NotificationsSection::save_provider_fields(const QString& provider_id, const ProviderWidgets& pw) {
+ if (pw.body_frame && pw.body_frame->property(kNotifProviderReadFailedProp).toBool()) {
+ LOG_WARN("Settings", QString("Skipping save for notification provider '%1' — its stored settings could not "
+ "be read, so the fields on screen are not its real values")
+ .arg(provider_id));
+ return;
+ }
+
auto& repo = SettingsRepository::instance();
const QString cat = QString("notif_%1").arg(provider_id);
diff --git a/fincept-qt/src/screens/settings/SecuritySection.cpp b/fincept-qt/src/screens/settings/SecuritySection.cpp
index 2eb76db3b..f903163c1 100644
--- a/fincept-qt/src/screens/settings/SecuritySection.cpp
+++ b/fincept-qt/src/screens/settings/SecuritySection.cpp
@@ -6,6 +6,7 @@
#include "auth/PinManager.h"
#include "auth/SecurityAuditLog.h"
#include "core/logging/Logger.h"
+#include "mcp/McpProvider.h"
#include "screens/settings/SettingsRowHelpers.h"
#include "screens/settings/SettingsStyles.h"
#include "storage/repositories/SettingsRepository.h"
@@ -25,6 +26,11 @@
namespace fincept::screens {
namespace {
+/// Dynamic-property guard set by reload() when a settings *read* failed. While
+/// it is set, Save is disabled and its handler refuses to write — the widgets
+/// hold defaults, not the user's values, and set() is an INSERT OR REPLACE.
+constexpr const char* kSecurityReadFailedProp = "fincept_security_read_failed";
+
// make_row() builds the label (and optional description) QLabel internally;
// grab them back from the row's direct child QLabels so retranslateUi() can
// re-apply text. Order is deterministic: title label first, description second.
@@ -35,6 +41,17 @@ void capture_row_labels(QWidget* row, QLabel** label_out, QLabel** desc_out = nu
if (labels.size() > 1 && desc_out)
*desc_out = labels.at(1);
}
+
+// Long-form explanation for the destructive-tools grant. One definition so
+// build_ui() and retranslateUi() cannot drift apart.
+QString destructive_tools_desc() {
+ return SecuritySection::tr(
+ "Off by default. With this off, AI chat and agents can read your terminal but cannot change anything "
+ "— no file writes, no spreadsheet, note, watchlist or portfolio edits, no dashboard or workspace "
+ "changes, no script execution. Turning it on lets them act for you; you can turn it back off at any "
+ "time. Live trading orders and access to your saved credentials stay blocked either way. Applies "
+ "immediately — no need to press Save.");
+}
} // namespace
SecuritySection::SecuritySection(QWidget* parent) : QWidget(parent) {
@@ -313,6 +330,12 @@ void SecuritySection::build_ui() {
save_btn_->setFixedWidth(200);
save_btn_->setStyleSheet(btn_primary_ss());
connect(save_btn_, &QPushButton::clicked, this, [this]() {
+ if (property(kSecurityReadFailedProp).toBool()) {
+ LOG_WARN("Settings", "Refusing to save security settings — the stored values could not be read, so the "
+ "widgets on screen are defaults rather than the user's settings");
+ return;
+ }
+
auto& repo = SettingsRepository::instance();
auto& guard = auth::InactivityGuard::instance();
auto& pm = auth::PinManager::instance();
@@ -358,6 +381,46 @@ void SecuritySection::build_ui() {
save_status_->hide();
vl->addWidget(save_status_);
+ // ── AI TOOL PERMISSIONS ───────────────────────────────────────────────────
+ //
+ // Backs `mcp/allow_destructive_tools`. Every MCP tool flagged
+ // `is_destructive` — spreadsheet and file writes, dashboard / workspace /
+ // layout mutations, notes, watchlist, portfolio, report builder, agent
+ // execution, run_python_script — fails closed unless this is on. It is the
+ // ONLY place that grant can be made, so without it the whole "let the
+ // assistant drive the terminal" surface is permanently read-only.
+ //
+ // Deliberately outside the Save button above: this is a capability grant,
+ // not a form field, and a half-applied capability is worse than either
+ // state. McpProvider::set_destructive_allowed persists it (AppConfig, same
+ // mechanism LoggingSection and VoiceConfigSection use) and updates the live
+ // session in one call — there is no second copy of this setting to keep in
+ // sync.
+ vl->addSpacing(16);
+ title_ai_tools_ = new QLabel(tr("AI TOOL PERMISSIONS"));
+ title_ai_tools_->setStyleSheet(sub_title_ss());
+ vl->addWidget(title_ai_tools_);
+ vl->addSpacing(4);
+
+ sec_allow_destructive_ = new QCheckBox(tr("Allow AI agents to modify files, workspaces and data"));
+ sec_allow_destructive_->setStyleSheet(check_ss());
+ sec_allow_destructive_->setAccessibleName(tr("Allow AI agents to modify files, workspaces and data"));
+ auto* row_destructive =
+ make_row(tr("Destructive AI Tools"), sec_allow_destructive_, destructive_tools_desc());
+ capture_row_labels(row_destructive, &row_destructive_lbl_, &row_destructive_desc_);
+ vl->addWidget(row_destructive);
+
+ connect(sec_allow_destructive_, &QCheckBox::toggled, this, [this](bool checked) {
+ mcp::McpProvider::set_destructive_allowed(checked);
+ // A capability grant belongs in the same audit stream the user is
+ // already looking at, two rows further down this page.
+ auth::SecurityAuditLog::instance().record(checked ? QStringLiteral("ai_destructive_tools_enabled")
+ : QStringLiteral("ai_destructive_tools_disabled"));
+ refresh_audit_log();
+ LOG_INFO("Settings",
+ QString("Destructive AI tools %1 from Security settings").arg(checked ? "enabled" : "disabled"));
+ });
+
// ── AUDIT LOG ─────────────────────────────────────────────────────────────
vl->addSpacing(16);
title_audit_ = new QLabel(tr("AUDIT LOG"));
@@ -419,6 +482,8 @@ void SecuritySection::retranslateUi() {
title_change_->setText(tr("CHANGE PIN"));
if (title_lock_)
title_lock_->setText(tr("AUTO-LOCK"));
+ if (title_ai_tools_)
+ title_ai_tools_->setText(tr("AI TOOL PERMISSIONS"));
if (title_audit_)
title_audit_->setText(tr("AUDIT LOG"));
if (audit_note_)
@@ -451,12 +516,20 @@ void SecuritySection::retranslateUi() {
row_minimize_lbl_->setText(tr("Lock on Minimize"));
if (row_minimize_desc_)
row_minimize_desc_->setText(tr("When on, minimizing the terminal immediately shows the PIN screen."));
+ if (row_destructive_lbl_)
+ row_destructive_lbl_->setText(tr("Destructive AI Tools"));
+ if (row_destructive_desc_)
+ row_destructive_desc_->setText(destructive_tools_desc());
// Checkbox texts.
if (sec_autolock_toggle_)
sec_autolock_toggle_->setText(tr("Enable auto-lock on inactivity"));
if (sec_lock_on_minimize_)
sec_lock_on_minimize_->setText(tr("Lock when the window is minimized"));
+ if (sec_allow_destructive_) {
+ sec_allow_destructive_->setText(tr("Allow AI agents to modify files, workspaces and data"));
+ sec_allow_destructive_->setAccessibleName(tr("Allow AI agents to modify files, workspaces and data"));
+ }
// PIN field placeholders.
if (sec_current_pin_)
@@ -516,21 +589,40 @@ void SecuritySection::reload() {
if (sec_change_pin_btn_)
sec_change_pin_btn_->setEnabled(pm.has_pin());
+ // A read error is not "unset". The Save handler writes every widget on this
+ // page straight back, so a failed read must disarm Save rather than let a
+ // default (10 min / lock-on-minimize off) overwrite the real setting.
+ bool read_failed = false;
+ auto log_read_error = [&read_failed](const char* key, const std::string& err) {
+ LOG_ERROR("Settings", QString("settings read failed for '%1' — leaving the stored value untouched and "
+ "disabling Save: %2")
+ .arg(QString::fromLatin1(key), QString::fromStdString(err)));
+ read_failed = true;
+ };
+
if (sec_autolock_toggle_ && sec_lock_timeout_) {
const QSignalBlocker b1(sec_autolock_toggle_);
const QSignalBlocker b2(sec_lock_timeout_);
auto r_enabled = repo.get("security.autolock_enabled");
- bool enabled = !r_enabled.is_ok() || r_enabled.value() != "false";
- sec_autolock_toggle_->setChecked(enabled);
- sec_lock_timeout_->setEnabled(enabled);
+ if (r_enabled.is_err()) {
+ log_read_error("security.autolock_enabled", r_enabled.error());
+ } else {
+ bool enabled = r_enabled.value() != "false";
+ sec_autolock_toggle_->setChecked(enabled);
+ sec_lock_timeout_->setEnabled(enabled);
+ }
auto r_timeout = repo.get("security.lock_timeout_minutes");
- int minutes = r_timeout.is_ok() ? r_timeout.value().toInt() : 10;
- for (int i = 0; i < sec_lock_timeout_->count(); ++i) {
- if (sec_lock_timeout_->itemData(i).toInt() == minutes) {
- sec_lock_timeout_->setCurrentIndex(i);
- break;
+ if (r_timeout.is_err()) {
+ log_read_error("security.lock_timeout_minutes", r_timeout.error());
+ } else {
+ int minutes = r_timeout.value().toInt();
+ for (int i = 0; i < sec_lock_timeout_->count(); ++i) {
+ if (sec_lock_timeout_->itemData(i).toInt() == minutes) {
+ sec_lock_timeout_->setCurrentIndex(i);
+ break;
+ }
}
}
}
@@ -538,7 +630,29 @@ void SecuritySection::reload() {
if (sec_lock_on_minimize_) {
const QSignalBlocker b(sec_lock_on_minimize_);
auto r = repo.get("security.lock_on_minimize");
- sec_lock_on_minimize_->setChecked(r.is_ok() && r.value() == "true");
+ if (r.is_err())
+ log_read_error("security.lock_on_minimize", r.error());
+ else
+ sec_lock_on_minimize_->setChecked(r.value() == "true");
+ }
+
+ setProperty(kSecurityReadFailedProp, read_failed);
+ if (save_btn_)
+ save_btn_->setEnabled(!read_failed);
+ if (read_failed && save_status_) {
+ save_status_->setText(tr("Could not read your saved security settings — saving is disabled so the values "
+ "shown cannot overwrite them. Reopen Settings to retry."));
+ save_status_->show();
+ }
+
+ if (sec_allow_destructive_) {
+ // Read back through McpProvider rather than the raw setting key: it is
+ // the owner of `mcp/allow_destructive_tools` and of the session grant
+ // seeded from it, so this can never show a state the tool gate does not
+ // actually apply. (Its per-call agent token path is thread-local and
+ // always false here on the GUI thread.)
+ const QSignalBlocker b(sec_allow_destructive_);
+ sec_allow_destructive_->setChecked(mcp::McpProvider::destructive_allowed());
}
refresh_audit_log();
diff --git a/fincept-qt/src/screens/settings/SecuritySection.h b/fincept-qt/src/screens/settings/SecuritySection.h
index 81cf97b01..435f28f35 100644
--- a/fincept-qt/src/screens/settings/SecuritySection.h
+++ b/fincept-qt/src/screens/settings/SecuritySection.h
@@ -47,6 +47,11 @@ class SecuritySection : public QWidget {
QLabel* sec_lockout_status_ = nullptr;
QPushButton* sec_change_pin_btn_ = nullptr;
+ /// Grants destructive MCP tools (`mcp/allow_destructive_tools`). Applies
+ /// immediately on toggle — it is a capability grant, not a form field, so
+ /// it deliberately does not wait for "Save Security Settings".
+ QCheckBox* sec_allow_destructive_ = nullptr;
+
// Change PIN form (shown/hidden dynamically)
QWidget* sec_change_pin_form_ = nullptr;
QLineEdit* sec_current_pin_ = nullptr;
@@ -59,6 +64,7 @@ class SecuritySection : public QWidget {
QLabel* title_pin_ = nullptr;
QLabel* title_change_ = nullptr;
QLabel* title_lock_ = nullptr;
+ QLabel* title_ai_tools_ = nullptr;
QLabel* title_audit_ = nullptr;
QLabel* audit_note_ = nullptr;
QPushButton* save_pin_btn_ = nullptr;
@@ -82,6 +88,8 @@ class SecuritySection : public QWidget {
QLabel* row_timeout_desc_ = nullptr;
QLabel* row_minimize_lbl_ = nullptr;
QLabel* row_minimize_desc_ = nullptr;
+ QLabel* row_destructive_lbl_ = nullptr;
+ QLabel* row_destructive_desc_ = nullptr;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/settings/SettingsScreen.cpp b/fincept-qt/src/screens/settings/SettingsScreen.cpp
index 8fc64d7c2..946beae92 100644
--- a/fincept-qt/src/screens/settings/SettingsScreen.cpp
+++ b/fincept-qt/src/screens/settings/SettingsScreen.cpp
@@ -344,8 +344,8 @@ void SettingsScreen::subscribe_mcp_events() {
};
auto& bus = EventBus::instance();
- mcp_event_subs_.append(bus.subscribe("settings.changed", on_settings_changed));
- mcp_event_subs_.append(bus.subscribe("llm.provider_changed", on_provider_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "settings.changed", on_settings_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "llm.provider_changed", on_provider_changed));
}
void SettingsScreen::unsubscribe_mcp_events() {
diff --git a/fincept-qt/src/screens/settings/StorageSection.cpp b/fincept-qt/src/screens/settings/StorageSection.cpp
index 2046484a4..e7e862a2d 100644
--- a/fincept-qt/src/screens/settings/StorageSection.cpp
+++ b/fincept-qt/src/screens/settings/StorageSection.cpp
@@ -637,7 +637,12 @@ void StorageSection::build_ui() {
}
}
- QSqlQuery query(use_cache ? CacheDatabase::instance().raw_db() : Database::instance().raw_db());
+ // Go through connection(), not raw_db(): raw_db() hands back the
+ // main-thread connection unconditionally, so it would silently
+ // diverge from the per-thread path if this console ever moved off
+ // the UI thread. connection() returns that same handle here and the
+ // correct per-thread clone anywhere else.
+ QSqlQuery query(use_cache ? CacheDatabase::instance().connection() : Database::instance().connection());
if (!query.exec(sql)) {
sql_status_->setText(tr("Error: %1").arg(query.lastError().text()));
sql_status_->setStyleSheet(QString("color:%1;background:transparent;").arg(ui::colors::NEGATIVE()));
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
index f3674b21e..24d066779 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
@@ -228,9 +228,9 @@ void WatchlistScreen::subscribe_mcp_events() {
};
auto& bus = EventBus::instance();
- mcp_event_subs_.append(bus.subscribe("watchlist.created", on_watchlists_changed));
- mcp_event_subs_.append(bus.subscribe("watchlist.deleted", on_watchlists_changed));
- mcp_event_subs_.append(bus.subscribe("watchlist.updated", on_watchlists_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "watchlist.created", on_watchlists_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "watchlist.deleted", on_watchlists_changed));
+ mcp_event_subs_.append(bus.subscribe(this, "watchlist.updated", on_watchlists_changed));
}
void WatchlistScreen::unsubscribe_mcp_events() {
diff --git a/fincept-qt/src/services/agents/AgentService.cpp b/fincept-qt/src/services/agents/AgentService.cpp
index 4808d52fe..f4b1e49b7 100644
--- a/fincept-qt/src/services/agents/AgentService.cpp
+++ b/fincept-qt/src/services/agents/AgentService.cpp
@@ -29,13 +29,85 @@
#include <QJsonDocument>
#include <QPointer>
#include <QProcess>
+#include <QTimer>
#include <QUuid>
#include <QVariant>
+#include <atomic>
#include <memory>
namespace fincept::services {
+namespace {
+// How long run_python_light() waits for PythonRunner's async interpreter
+// detection before giving up and failing the call.
+constexpr int kPythonReadyGraceMs = 30000;
+
+// Default excludes applied to every agent: UI-driving tools (navigation /
+// system / settings), the recursive chat tools (ai-chat), and the tool
+// discovery meta tools. Non-negotiable — per-agent config may only ADD to
+// them. TerminalMcpBridge enforces the same set at dispatch.
+const QStringList& default_tool_excludes() {
+ static const QStringList kCats = {QStringLiteral("navigation"), QStringLiteral("system"),
+ QStringLiteral("settings"), QStringLiteral("ai-chat"), QStringLiteral("meta")};
+ return kCats;
+}
+
+/// Resolve the effective tool filter for one agent from its config, merging the
+/// non-negotiable defaults with the agent's own `tool_filter` block.
+///
+/// Pulled out of build_payload so the SAME resolved filter can be handed to the
+/// bridge as a run scope. It used to be inline and reachable only when the
+/// catalog was being built, which meant the filter shaped what the agent was
+/// TOLD about and nothing else.
+///
+/// Supported `tool_filter` keys:
+/// categories[] — whitelist (empty = all enabled)
+/// exclude_categories[] — blacklist, ON TOP of the defaults
+/// name_patterns[] — regex include on tool name
+/// exclude_name_patterns[] — regex exclude on tool name
+/// max_tools (int) — hard cap on catalog size
+mcp::ToolFilter resolve_tool_filter(const QJsonObject& config) {
+ mcp::ToolFilter filter;
+ filter.exclude_categories = default_tool_excludes();
+
+ const QJsonObject tf = config.value("tool_filter").toObject();
+ if (tf.isEmpty())
+ return filter;
+
+ if (tf.contains("categories")) {
+ filter.categories.clear();
+ for (const auto& v : tf["categories"].toArray())
+ filter.categories.append(v.toString());
+ }
+ if (tf.contains("exclude_categories")) {
+ // User excludes are ADDITIVE on top of defaults — defaults are
+ // non-negotiable (UI tools are never safe for agents).
+ for (const auto& v : tf["exclude_categories"].toArray()) {
+ const QString cat = v.toString().trimmed();
+ if (!cat.isEmpty() && !filter.exclude_categories.contains(cat))
+ filter.exclude_categories.append(cat);
+ }
+ }
+ if (tf.contains("name_patterns")) {
+ for (const auto& v : tf["name_patterns"].toArray()) {
+ const QString p = v.toString().trimmed();
+ if (!p.isEmpty())
+ filter.name_patterns.append(p);
+ }
+ }
+ if (tf.contains("exclude_name_patterns")) {
+ for (const auto& v : tf["exclude_name_patterns"].toArray()) {
+ const QString p = v.toString().trimmed();
+ if (!p.isEmpty())
+ filter.exclude_name_patterns.append(p);
+ }
+ }
+ filter.max_tools = tf.value("max_tools").toInt(0);
+ return filter;
+}
+} // namespace
+
// ── Singleton ────────────────────────────────────────────────────────────────
AgentService& AgentService::instance() {
@@ -65,9 +137,49 @@ AgentService::AgentService(QObject* parent) : QObject(parent) {
// gate non-interactively)
// - is_destructive + agent → deny (agents can't show a confirm modal;
// opt-in via per-agent config is Phase 5 work)
- // - is_destructive + chat → allow (matches current advisory behaviour
- // until the Phase 6.12 modal lands)
+ // - is_destructive + chat → allow (subject to the fail-closed
+ // destructive capability gate McpProvider::check_authorization
+ // applies BEFORE this checker runs)
// - everything else → allow
+ //
+ // ── The confirmation-modal seam ──────────────────────────────────────────
+ //
+ // The `required >= AuthLevel::Verified` line below is the SINGLE line to
+ // change when the confirmation modal lands. It denies unconditionally, so
+ // the 28 tools declared AuthLevel::ExplicitConfirm are refused on every
+ // path — including for a user who has explicitly granted destructive
+ // capability in Settings → Security. That is deliberate and stays as-is:
+ // "ask the user" cannot be honoured while there is nobody to ask, and
+ // failing closed is the only safe reading of a tool that asked to be
+ // confirmed.
+ //
+ // What it currently blocks, so whoever builds the modal knows the blast
+ // radius:
+ // - Correctly blocked, and must STAY blocked without an explicit
+ // per-call confirmation — real money and live credentials:
+ // live-trading (6): live_place_order, live_smart_order,
+ // live_cancel_order, live_cancel_all_orders, live_close_position,
+ // live_close_all_positions
+ // profile (1): profile_get_api_key (returns live key material)
+ // mcp-servers (6): install_mcp_server_from_marketplace,
+ // add_mcp_server, remove_mcp_server, start_mcp_server,
+ // restart_mcp_server, call_external_mcp_tool
+ // (each spawns or drives an arbitrary local child process)
+ // - Over-blocked pending the modal — destructive but recoverable, and
+ // arguably covered by the Settings capability grant alone:
+ // workspace (7): apply_layout, delete_layout, apply_layout_template,
+ // restore_last_workspace, delete_workspace_snapshot,
+ // restore_workspace_snapshot, close_window
+ // dashboard (3): load_dashboard_layout, apply_dashboard_template,
+ // clear_dashboard_layout
+ // agents (3): delete_agent_config, delete_workflow,
+ // agent_paper_execute_trade
+ // excel (1): delete_excel_sheet
+ // file_manager (1): download_managed_file
+ //
+ // When the modal exists, replace the line with a call that prompts and
+ // returns the user's verdict. Do NOT relax it to `> Verified` or drop the
+ // ExplicitConfirm level — the 13 tools in the first group depend on it.
mcp::McpProvider::instance().set_auth_checker([](mcp::AuthLevel required, bool is_destructive) -> bool {
if (required >= mcp::AuthLevel::Verified)
return false;
@@ -238,8 +350,21 @@ QJsonObject AgentService::build_payload(const QString& action, const QJsonObject
if (bridge.is_active() && terminal_tools_enabled) {
if (!enriched_config.contains("terminal_mcp_endpoint"))
enriched_config["terminal_mcp_endpoint"] = bridge.endpoint();
- if (!enriched_config.contains("terminal_mcp_token"))
- enriched_config["terminal_mcp_token"] = bridge.token();
+
+ // Resolve the per-agent filter ONCE, up front — before the catalog is
+ // built and regardless of whether it is built at all. It is both the
+ // catalog shape AND the dispatch policy; a caller that pre-supplied
+ // `terminal_tools` must still be held to it.
+ const mcp::ToolFilter filter = resolve_tool_filter(enriched_config);
+ const bool include_external = enriched_config.value("include_external_mcp").toBool(true);
+
+ if (!enriched_config.contains("terminal_mcp_token")) {
+ // Run-scoped token, not the process token: it carries `filter` to
+ // the bridge so an agent that names a tool its own config excluded
+ // is refused at dispatch, not merely omitted from its catalog.
+ // Retired by run_python_stdin when the agent process exits.
+ enriched_config["terminal_mcp_token"] = bridge.begin_run(filter, include_external);
+ }
// Capability token — only injected when the agent config opts in.
// Without this header on each request the bridge will block any
// `is_destructive=true` tool call even if the agent's LLM tries one.
@@ -247,53 +372,8 @@ QJsonObject AgentService::build_payload(const QString& action, const QJsonObject
!enriched_config.contains("terminal_mcp_destructive_token")) {
enriched_config["terminal_mcp_destructive_token"] = bridge.destructive_token();
}
- if (!enriched_config.contains("terminal_tools")) {
- // Per-agent override via config["tool_filter"] supports:
- // categories[] — whitelist (empty = all enabled)
- // exclude_categories[] — blacklist, ON TOP of defaults below
- // name_patterns[] — regex include on tool name
- // exclude_name_patterns[] — regex exclude on tool name
- // max_tools (int) — hard cap
- // Default excludes UI-only and recursive categories so agents
- // don't drive the UI or call the chat LLM.
- mcp::ToolFilter filter;
- const QStringList default_excludes = {"navigation", "system", "settings", "ai-chat", "meta"};
- filter.exclude_categories = default_excludes;
- const QJsonObject tf = enriched_config.value("tool_filter").toObject();
- if (!tf.isEmpty()) {
- if (tf.contains("categories")) {
- filter.categories.clear();
- for (const auto& v : tf["categories"].toArray())
- filter.categories.append(v.toString());
- }
- if (tf.contains("exclude_categories")) {
- // User excludes are ADDITIVE on top of defaults — defaults
- // are non-negotiable (UI tools are never safe for agents).
- for (const auto& v : tf["exclude_categories"].toArray()) {
- const QString cat = v.toString().trimmed();
- if (!cat.isEmpty() && !filter.exclude_categories.contains(cat))
- filter.exclude_categories.append(cat);
- }
- }
- if (tf.contains("name_patterns")) {
- for (const auto& v : tf["name_patterns"].toArray()) {
- const QString p = v.toString().trimmed();
- if (!p.isEmpty())
- filter.name_patterns.append(p);
- }
- }
- if (tf.contains("exclude_name_patterns")) {
- for (const auto& v : tf["exclude_name_patterns"].toArray()) {
- const QString p = v.toString().trimmed();
- if (!p.isEmpty())
- filter.exclude_name_patterns.append(p);
- }
- }
- filter.max_tools = tf.value("max_tools").toInt(0);
- }
- const bool include_external = enriched_config.value("include_external_mcp").toBool(true);
+ if (!enriched_config.contains("terminal_tools"))
enriched_config["terminal_tools"] = bridge.tool_definitions(filter, include_external);
- }
// Dry-run mode is opt-in and read by the Python TerminalToolkit. When
// true, the toolkit short-circuits each call and returns a synthetic
@@ -311,37 +391,53 @@ QJsonObject AgentService::build_payload(const QString& action, const QJsonObject
return payload;
}
-// ── Python lightweight runner (via PythonRunner args) ─────────────────────────
+// ── Python lightweight runner ────────────────────────────────────────────────
void AgentService::run_python_light(const QString& action, const QJsonObject& params,
std::function<void(bool, QJsonObject)> on_result) {
- QJsonObject payload = build_payload(action, params);
- QString payload_str = QString::fromUtf8(QJsonDocument(payload).toJson(QJsonDocument::Compact));
+ // SECURITY: this used to hand the payload to PythonRunner::run() as a
+ // command-line argument. That payload is not "light" — build_payload()
+ // embeds every configured LLM provider API key, the Fincept session key,
+ // the MCP bridge token, the destructive-capability token, and the whole
+ // terminal_tools catalog. As argv it is readable by any process running as
+ // the same user (Win32_Process.CommandLine via WMI on Windows, no
+ // elevation; /proc/<pid>/cmdline on Linux) and it is captured by crash
+ // dumps and EDR telemetry. Worse, the catalog pushes it past PythonRunner's
+ // 8 KB argv-spill threshold, so it was written to a temp file in
+ // QStandardPaths::TempLocation with default (0644 in /tmp) permissions.
+ //
+ // stdin has neither problem: it is never visible outside the pipe and never
+ // touches disk. run_python_stdin() already does exactly this for the other
+ // ~40 actions, so the light path just delegates to it.
+ auto& py = python::PythonRunner::instance();
+ if (py.is_available()) {
+ run_python_stdin(action, params, {}, std::move(on_result));
+ return;
+ }
+ // Interpreter detection can still be in flight on a cold install, and
+ // discover_agents() fires from main.cpp at startup. PythonRunner::run()
+ // used to queue the request until detection finished; replicate that by
+ // waiting for python_ready, with a bounded fallback so the caller always
+ // gets an answer even when no interpreter is ever found (python_ready is
+ // not emitted in that case).
+ auto fired = std::make_shared<std::atomic_bool>(false);
QPointer<AgentService> self = this;
- python::PythonRunner::instance().run(
- "agents/finagent_core/main.py", {payload_str}, [self, action, on_result](python::PythonResult pr) {
- if (!self)
- return;
- if (!pr.success) {
- LOG_ERROR("AgentService", QString("%1 failed: %2").arg(action, pr.error.left(200)));
- on_result(false, QJsonObject{{"error", pr.error}});
- return;
- }
- LOG_INFO("AgentService", QString("%1: raw output length=%2, first 300 chars: %3")
- .arg(action)
- .arg(pr.output.size())
- .arg(pr.output.left(300)));
- QJsonDocument doc = QJsonDocument::fromJson(pr.output.toUtf8());
- if (doc.isNull()) {
- LOG_ERROR("AgentService", QString("%1: invalid JSON response").arg(action));
- on_result(false, QJsonObject{{"error", "Invalid JSON response from Python"}});
- return;
- }
- LOG_INFO("AgentService",
- QString("%1: parsed JSON keys: %2").arg(action, QStringList(doc.object().keys()).join(", ")));
- on_result(true, doc.object());
- });
+ auto resume = [self, action, params, on_result, fired](bool ready) {
+ if (fired->exchange(true))
+ return;
+ if (!self)
+ return;
+ if (!ready) {
+ LOG_WARN("AgentService", QString("%1 skipped — no Python interpreter available").arg(action));
+ on_result(false, QJsonObject{{"error", "Python not available"}});
+ return;
+ }
+ self->run_python_stdin(action, params, {}, on_result);
+ };
+ connect(&py, &python::PythonRunner::python_ready, this, [resume]() { resume(true); },
+ Qt::SingleShotConnection);
+ QTimer::singleShot(kPythonReadyGraceMs, this, [resume]() { resume(false); });
}
// ── Python stdin runner (for large payloads) ─────────────────────────────────
@@ -357,6 +453,12 @@ void AgentService::run_python_stdin(const QString& action, const QJsonObject& pa
QJsonObject payload = build_payload(action, params, config);
QByteArray payload_bytes = QJsonDocument(payload).toJson(QJsonDocument::Compact);
+ // Bridge run scope opened by build_payload — retire it the moment the agent
+ // process is gone so its token stops authenticating. Empty (or a
+ // caller-supplied token, which the bridge never registered) makes end_run a
+ // no-op, so this is safe for every action including the non-agent ones.
+ const QString run_token = payload.value("config").toObject().value("terminal_mcp_token").toString();
+
QString python_path = py.python_path();
QString script_path = py.scripts_dir() + "/agents/finagent_core/main.py";
@@ -377,7 +479,8 @@ void AgentService::run_python_stdin(const QString& action, const QJsonObject& pa
timer->start();
connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
- [self, proc, action, on_result, timer](int exit_code, QProcess::ExitStatus) {
+ [self, proc, action, on_result, timer, run_token](int exit_code, QProcess::ExitStatus) {
+ mcp::TerminalMcpBridge::instance().end_run(run_token);
int elapsed = timer->elapsed();
QString stdout_str = QString::fromUtf8(proc->readAllStandardOutput());
@@ -411,7 +514,9 @@ void AgentService::run_python_stdin(const QString& action, const QJsonObject& pa
on_result(true, result);
});
- connect(proc, &QProcess::errorOccurred, this, [self, proc, action, on_result, timer](QProcess::ProcessError) {
+ connect(proc, &QProcess::errorOccurred, this, [self, proc, action, on_result, timer,
+ run_token](QProcess::ProcessError) {
+ mcp::TerminalMcpBridge::instance().end_run(run_token);
QString err = proc->errorString();
proc->deleteLater();
if (!self)
diff --git a/fincept-qt/src/services/alpha_arena/ArenaStore.cpp b/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
index 9d467f90a..7e8dbd1d3 100644
--- a/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
+++ b/fincept-qt/src/services/alpha_arena/ArenaStore.cpp
@@ -245,13 +245,43 @@ Result<void> ArenaStore::set_cadence(const QString& id, int seconds) {
Result<void> ArenaStore::delete_competition_cascade(const QString& id) {
if (auto hr = ensure_hitl_table(); hr.is_err())
return hr;
- for (const char* table : {"arena_agents", "arena_rounds", "arena_decisions", "arena_orders", "arena_positions",
- "arena_accounts", "arena_equity_snapshots", "arena_events", "arena_hitl_pending"}) {
- auto r = exec_write(QStringLiteral("DELETE FROM %1 WHERE competition_id = ?").arg(QLatin1String(table)), {id});
- if (r.is_err())
+
+ // One transaction for the whole cascade — the ten DELETEs used to be
+ // independent, so a failure on the third left a half-deleted competition:
+ // orphaned rounds/orders/positions pointing at a competition row that was
+ // itself still present. Same shape as StorageManager::delete_cascade —
+ // every Result checked, rollback on the first error.
+ auto tx = db().begin_transaction();
+ if (tx.is_err())
+ return tx;
+
+ // Children first, parent last, so nothing is orphaned at any point.
+ static const char* const kCascadeTables[] = {
+ "arena_agents", "arena_rounds", "arena_decisions", "arena_orders",
+ "arena_positions", "arena_accounts", "arena_equity_snapshots",
+ "arena_events", "arena_hitl_pending", "arena_competitions",
+ };
+
+ for (const char* table : kCascadeTables) {
+ const QString table_name = QString::fromLatin1(table);
+ // arena_competitions keys on `id`, every child table on `competition_id`.
+ const QString column = (table_name == QLatin1String("arena_competitions")) ? QStringLiteral("id")
+ : QStringLiteral("competition_id");
+ auto r = exec_write(QStringLiteral("DELETE FROM %1 WHERE %2 = ?").arg(table_name, column), {id});
+ if (r.is_err()) {
+ db().rollback();
+ LOG_ERROR("ArenaStore", QString("Cascade delete of competition %1 aborted at %2: %3")
+ .arg(id, table_name, QString::fromStdString(r.error())));
return r;
+ }
+ }
+
+ auto c = db().commit();
+ if (c.is_err()) {
+ db().rollback();
+ return c;
}
- return exec_write("DELETE FROM arena_competitions WHERE id = ?", {id});
+ return Result<void>::ok();
}
Result<QStringList> ArenaStore::competitions_with_status(const QString& status) {
diff --git a/fincept-qt/src/services/cloud/SettingsCloudAdapter.cpp b/fincept-qt/src/services/cloud/SettingsCloudAdapter.cpp
index 5665e0b3f..9943d9807 100644
--- a/fincept-qt/src/services/cloud/SettingsCloudAdapter.cpp
+++ b/fincept-qt/src/services/cloud/SettingsCloudAdapter.cpp
@@ -1,5 +1,6 @@
#include "services/cloud/SettingsCloudAdapter.h"
+#include "core/logging/Logger.h"
#include "network/cloud/CloudClient.h"
#include "storage/repositories/SettingsRepository.h"
#include "storage/sync/CloudSyncSettings.h"
@@ -14,6 +15,8 @@ using fincept::cloud::CloudClient;
using fincept::cloud::CloudResponse;
namespace {
+constexpr const char* kSettingsCloudTag = "SettingsCloudAdapter";
+
QString st_entity() {
return QStringLiteral("setting");
}
@@ -67,8 +70,22 @@ void SettingsCloudAdapter::push(const OutboxRow& row, PushDone done) {
void SettingsCloudAdapter::push_upsert(const OutboxRow& row, PushDone done) {
const QString key = row.local_id;
auto v = SettingsRepository::instance().get(key);
+ if (v.is_err()) {
+ // Never sync a value we failed to read. Pushing the "" fallback would
+ // make the cloud authoritative for an empty string and fan it back out
+ // to every device on the account. Report a retryable failure so the
+ // outbox keeps the row and pushes it once the DB is healthy again.
+ LOG_ERROR(kSettingsCloudTag,
+ QString("settings read failed for '%1' — aborting cloud push, row stays queued: %2")
+ .arg(key, QString::fromStdString(v.error())));
+ AdapterResult r;
+ r.retry = true;
+ r.error = QStringLiteral("settings_read_failed");
+ done(r);
+ return;
+ }
QJsonObject body;
- body["value"] = v.is_ok() ? v.value() : QString();
+ body["value"] = v.value();
body["category"] = st_category(key);
CloudClient::instance().put(st_path(key), body, [done](CloudResponse r) { done(st_result(r)); }, this);
}
diff --git a/fincept-qt/src/services/crypto/TotpService.cpp b/fincept-qt/src/services/crypto/TotpService.cpp
index 695640153..45e3cba0d 100644
--- a/fincept-qt/src/services/crypto/TotpService.cpp
+++ b/fincept-qt/src/services/crypto/TotpService.cpp
@@ -23,10 +23,26 @@ void TotpService::generate(const QString& secret, TotpCallback cb) {
return;
}
- const QString script = fincept::python::PythonRunner::instance().scripts_dir() + "/exchange/totp_gen.py";
+ // Relative to PythonRunner::scripts_dir() — run() prepends it itself.
+ // (This used to pass the absolute scripts_dir() + "/exchange/totp_gen.py",
+ // which run() then prefixed a second time, so every call failed the
+ // QFileInfo::exists() check with "Script not found".)
+ const QString script = QStringLiteral("exchange/totp_gen.py");
+ // ── SECURITY: the seed goes on stdin, never argv ─────────────────────────
+ // `secret` is the broker's PERMANENT base32 TOTP seed — not a one-time
+ // code. In argv it is readable by any process running as the same user
+ // (Win32_Process.CommandLine via WMI on Windows with no elevation;
+ // /proc/<pid>/cmdline on Linux) and it lands in crash dumps and EDR
+ // telemetry. Stealing it is a lasting bypass of the broker's second factor,
+ // and this fires on every authenticated broker login.
+ //
+ // PythonRunner::run() now takes `stdin_data`: it writes the bytes to the
+ // child and closes the write channel, which is exactly what totp_gen.py's
+ // `--stdin` path waits for (it reads one line and must see EOF). The seed
+ // never appears in the command line and never touches disk.
fincept::python::PythonRunner::instance().run(
- script, {secret}, [cb = std::move(cb)](const fincept::python::PythonResult& result) {
+ script, {QStringLiteral("--stdin")}, [cb = std::move(cb)](const fincept::python::PythonResult& result) {
TotpResult out;
if (!result.success) {
out.error = result.output.isEmpty() ? QStringLiteral("totp_gen failed") : result.output;
@@ -53,7 +69,8 @@ void TotpService::generate(const QString& secret, TotpCallback cb) {
out.valid_for = obj.value("valid_for").toInt();
if (cb)
cb(out);
- });
+ },
+ /*on_line=*/{}, /*stdin_data=*/secret.toUtf8() + '\n');
}
} // namespace fincept::services::crypto
diff --git a/fincept-qt/src/services/data_normalization/DataNormalizationService.cpp b/fincept-qt/src/services/data_normalization/DataNormalizationService.cpp
index 1bec5f522..024096591 100644
--- a/fincept-qt/src/services/data_normalization/DataNormalizationService.cpp
+++ b/fincept-qt/src/services/data_normalization/DataNormalizationService.cpp
@@ -11,6 +11,7 @@
#include <QJsonValue>
#include <QPointer>
#include <QTimeZone>
+#include <QUrl>
#include <QUuid>
namespace fincept::services {
@@ -44,7 +45,11 @@ void DataNormalizationService::fetch_and_normalize(const DataMapping& mapping, N
apply_auth(mapping);
const QString url = build_url(mapping);
- LOG_INFO(TAG, QString("Fetching mapping '%1' from %2").arg(mapping.name, url));
+ // Log the URL WITHOUT its query string: the shipped mapping templates put
+ // `&apikey=`/`&token=` there, and this is LOG_INFO — the default level — so
+ // the raw URL would write a live third-party credential into fincept.log.
+ LOG_INFO(TAG, QString("Fetching mapping '%1' from %2")
+ .arg(mapping.name, QUrl(url).adjusted(QUrl::RemoveQuery).toString()));
QPointer<DataNormalizationService> self = this;
@@ -344,10 +349,28 @@ QString DataNormalizationService::build_url(const DataMapping& mapping) {
}
void DataNormalizationService::apply_auth(const DataMapping& mapping) {
- if (mapping.auth_type == "API Key") {
- HttpClient::instance().set_auth_header(mapping.auth_token);
- } else if (mapping.auth_type == "Bearer Token") {
- HttpClient::instance().set_session_token(mapping.auth_token);
+ // ── SECURITY: do NOT mutate the shared HttpClient singleton here ─────────
+ // This used to call set_auth_header() / set_session_token() with the saved
+ // mapping's third-party token and never restore the previous values. Two
+ // consequences, both bad:
+ //
+ // 1. It never worked. build_request() only attaches X-API-Key /
+ // X-Session-Token when the request host matches base_url_ (the Fincept
+ // API), so a third-party mapping host never received the token anyway.
+ // 2. It leaked. Every subsequent Fincept API call then transmitted the
+ // user's third-party credential to api.fincept.in, and the user's own
+ // session auth stayed broken until AuthManager happened to rewrite it.
+ //
+ // Applying mapping auth correctly needs per-request headers on HttpClient
+ // (or a scoped guard that restores api_key_ / session_token_). Until that
+ // API exists, mapping auth is inert — which is what it already was — but it
+ // no longer corrupts global auth state.
+ if (mapping.auth_type == "API Key" || mapping.auth_type == "Bearer Token") {
+ if (!mapping.auth_token.isEmpty()) {
+ LOG_WARN(TAG, QString("Mapping '%1' declares %2 auth, but per-request auth headers are not "
+ "supported yet — the request is being sent unauthenticated")
+ .arg(mapping.name, mapping.auth_type));
+ }
}
// Basic Auth and None require no setup on HttpClient
}
diff --git a/fincept-qt/src/services/dbnomics/DBnomicsService.cpp b/fincept-qt/src/services/dbnomics/DBnomicsService.cpp
index 04c145789..cd3ef9a70 100644
--- a/fincept-qt/src/services/dbnomics/DBnomicsService.cpp
+++ b/fincept-qt/src/services/dbnomics/DBnomicsService.cpp
@@ -196,6 +196,14 @@ void DBnomicsService::fetch_series(const QString& provider_code, const QString&
return;
}
QJsonObject root = result.value().object();
+ // A 2xx without a `series` envelope is a failure, not an empty
+ // result: num_found would default to 0 and the UI would render a
+ // rate-limit or outage as an honest "no series found".
+ if (!root.value(QStringLiteral("series")).isObject()) {
+ LOG_ERROR("DBnomicsService", QString("series fetch: malformed response for %1").arg(cache_key));
+ emit error_occurred("series", QStringLiteral("Malformed response from DBnomics"));
+ return;
+ }
QJsonObject s = root["series"].toObject();
QJsonArray docs = s["docs"].toArray();
int total = s["num_found"].toInt();
diff --git a/fincept-qt/src/services/llm/LlmContentExtractors.cpp b/fincept-qt/src/services/llm/LlmContentExtractors.cpp
index 97a0e71bd..a3e6f483a 100644
--- a/fincept-qt/src/services/llm/LlmContentExtractors.cpp
+++ b/fincept-qt/src/services/llm/LlmContentExtractors.cpp
@@ -2,7 +2,10 @@
#include "services/llm/LlmContentExtractors.h"
+#include <QJsonDocument>
#include <QJsonValue>
+#include <QRegularExpression>
+#include <QVector>
namespace fincept::ai_chat {
@@ -84,4 +87,210 @@ QString extract_gemini_parts_text(const QJsonArray& parts) {
return thought_fallback;
}
+// ── Text/XML tool-call recovery ────────────────────────────────────────────
+
+namespace {
+
+// Every brace-balanced top-level JSON object inside `s`, in order.
+//
+// A single <tool_call> block is NOT reliably one JSON object. MiniMax batches
+// several calls into one block, newline-separated:
+//
+// <tool_call>{"name":"tool_list","arguments":{...}}
+// {"name":"tool_list","arguments":{...}} </tool_call>
+//
+// Handing that whole span to QJsonDocument::fromJson fails (two concatenated
+// objects aren't a document), which used to yield ZERO extracted calls and let
+// the raw markup fall through into the chat bubble as if it were the answer.
+// Scanning for balanced spans instead also covers a JSON-array body — the outer
+// `[` is simply skipped and each element is picked up on its own.
+//
+// String-aware: braces inside quoted values (and escaped quotes) don't count.
+QVector<QJsonObject> scan_json_objects(const QString& s) {
+ QVector<QJsonObject> out;
+ int depth = 0;
+ qsizetype start = -1;
+ bool in_str = false;
+ bool esc = false;
+ for (qsizetype i = 0; i < s.size(); ++i) {
+ const QChar c = s[i];
+ if (in_str) {
+ if (esc)
+ esc = false;
+ else if (c == QLatin1Char('\\'))
+ esc = true;
+ else if (c == QLatin1Char('"'))
+ in_str = false;
+ continue;
+ }
+ if (c == QLatin1Char('"')) {
+ in_str = true;
+ } else if (c == QLatin1Char('{')) {
+ if (depth == 0)
+ start = i;
+ ++depth;
+ } else if (c == QLatin1Char('}') && depth > 0) {
+ if (--depth == 0 && start >= 0) {
+ const auto doc = QJsonDocument::fromJson(s.mid(start, i - start + 1).toUtf8());
+ if (doc.isObject())
+ out.append(doc.object());
+ start = -1;
+ }
+ }
+ }
+ return out;
+}
+
+// Pull {name, arguments} out of a JSON object emitted inside tool markup.
+// `arguments` is accepted both as an object and as a JSON-encoded string —
+// models disagree on which, and both appear in the wild from the same model.
+bool parse_tool_call_object(const QJsonObject& obj, TextToolCall& out) {
+ QString name = obj["name"].toString();
+ if (name.isEmpty())
+ name = obj["function"].toString();
+ if (name.isEmpty())
+ return false;
+ QJsonObject args = obj["arguments"].toObject();
+ if (args.isEmpty() && obj["arguments"].isString())
+ args = QJsonDocument::fromJson(obj["arguments"].toString().toUtf8()).object();
+ out = {name, args};
+ return true;
+}
+
+} // namespace
+
+bool has_text_tool_markup(const QString& content) {
+ static const QRegularExpression rx(QStringLiteral("<\\s*/?\\s*(?:\\w+\\s*:\\s*)?tool_call\\b"
+ "|<\\s*invoke\\s+name="
+ "|```\\s*tool_call\\b"),
+ QRegularExpression::CaseInsensitiveOption);
+ return rx.match(content).hasMatch();
+}
+
+std::vector<TextToolCall> extract_text_tool_calls(const QString& content, QStringList* raw_blocks) {
+ std::vector<TextToolCall> calls;
+
+ // --- Pattern 1: <tool_call> … </tool_call>, optionally namespaced ---
+ // The body is scanned for balanced JSON objects rather than parsed whole, so
+ // a block carrying several calls yields several calls.
+ {
+ static const QRegularExpression rx("<\\s*(?:\\w+\\s*:\\s*)?tool_call\\s*>([\\s\\S]*?)<\\s*/\\s*"
+ "(?:\\w+\\s*:\\s*)?tool_call\\s*>",
+ QRegularExpression::CaseInsensitiveOption |
+ QRegularExpression::DotMatchesEverythingOption);
+ auto it = rx.globalMatch(content);
+ bool any_block = false;
+ while (it.hasNext()) {
+ auto m = it.next();
+ any_block = true;
+ for (const QJsonObject& obj : scan_json_objects(m.captured(1))) {
+ TextToolCall tc;
+ if (parse_tool_call_object(obj, tc))
+ calls.push_back(tc);
+ }
+ }
+
+ // Unterminated block — the model opened <tool_call> and ran out of
+ // tokens (or just omitted the close). Scan the tail rather than lose
+ // the call and print the markup at the user.
+ if (!any_block) {
+ static const QRegularExpression rx_open("<\\s*(?:\\w+\\s*:\\s*)?tool_call\\s*>",
+ QRegularExpression::CaseInsensitiveOption);
+ const auto om = rx_open.match(content);
+ if (om.hasMatch()) {
+ for (const QJsonObject& obj : scan_json_objects(content.mid(om.capturedEnd()))) {
+ TextToolCall tc;
+ if (parse_tool_call_object(obj, tc))
+ calls.push_back(tc);
+ }
+ }
+ }
+ }
+
+ // --- Pattern 2: <invoke name="…"> with <parameter> children or JSON body ---
+ if (calls.empty()) {
+ static const QRegularExpression rx_invoke("<invoke\\s+name=\"([^\"]+)\"[^>]*>([\\s\\S]*?)</invoke>",
+ QRegularExpression::MultilineOption |
+ QRegularExpression::DotMatchesEverythingOption);
+ static const QRegularExpression rx_param("<parameter\\s+name=\"([^\"]+)\"[^>]*>([\\s\\S]*?)</parameter>",
+ QRegularExpression::MultilineOption |
+ QRegularExpression::DotMatchesEverythingOption);
+ auto it = rx_invoke.globalMatch(content);
+ while (it.hasNext()) {
+ auto m = it.next();
+ QString name = m.captured(1);
+ QString body = m.captured(2).trimmed();
+ QJsonObject args;
+
+ auto pit = rx_param.globalMatch(body);
+ bool has_params = false;
+ while (pit.hasNext()) {
+ auto pm = pit.next();
+ const QString pname = pm.captured(1);
+ const QString pval = pm.captured(2).trimmed();
+ has_params = true;
+ // Parse as JSON so arrays/objects survive; fall back to the literal.
+ auto pdoc = QJsonDocument::fromJson(pval.toUtf8());
+ if (pdoc.isArray())
+ args[pname] = pdoc.array();
+ else if (pdoc.isObject())
+ args[pname] = pdoc.object();
+ else
+ args[pname] = pval;
+ }
+
+ if (!has_params && !body.isEmpty()) {
+ auto jdoc = QJsonDocument::fromJson(body.toUtf8());
+ if (jdoc.isObject())
+ args = jdoc.object();
+ }
+
+ if (!name.isEmpty())
+ calls.push_back({name, args});
+ }
+ }
+
+ // --- Pattern 3: [ns:]tool_call … /[ns:]tool_call ---
+ if (calls.empty()) {
+ static const QRegularExpression rx("(?:\\w+:)?tool_call\\s+([\\s\\S]*?)\\s*/(?:\\w+:)?tool_call",
+ QRegularExpression::MultilineOption);
+ auto it = rx.globalMatch(content);
+ while (it.hasNext()) {
+ auto m = it.next();
+ const QString body = m.captured(1).trimmed();
+ bool got = false;
+ for (const QJsonObject& obj : scan_json_objects(body)) {
+ TextToolCall tc;
+ if (parse_tool_call_object(obj, tc)) {
+ calls.push_back(tc);
+ got = true;
+ }
+ }
+ if (got)
+ continue;
+ // Not JSON — an unnamed raw command (SQL, …). Hand it back for the
+ // caller to map; we can't name a tool without the registry.
+ if (raw_blocks && !body.isEmpty())
+ raw_blocks->append(body);
+ }
+ }
+
+ // --- Pattern 4: ```tool_call fenced JSON ---
+ if (calls.empty()) {
+ static const QRegularExpression rx("```tool_call\\s*\\n([\\s\\S]*?)\\n\\s*```",
+ QRegularExpression::MultilineOption);
+ auto it = rx.globalMatch(content);
+ while (it.hasNext()) {
+ auto m = it.next();
+ for (const QJsonObject& obj : scan_json_objects(m.captured(1))) {
+ TextToolCall tc;
+ if (parse_tool_call_object(obj, tc))
+ calls.push_back(tc);
+ }
+ }
+ }
+
+ return calls;
+}
+
} // namespace fincept::ai_chat
diff --git a/fincept-qt/src/services/llm/LlmContentExtractors.h b/fincept-qt/src/services/llm/LlmContentExtractors.h
index f2554d6fc..1f6458afb 100644
--- a/fincept-qt/src/services/llm/LlmContentExtractors.h
+++ b/fincept-qt/src/services/llm/LlmContentExtractors.h
@@ -7,6 +7,9 @@
#include <QJsonArray>
#include <QJsonObject>
#include <QString>
+#include <QStringList>
+
+#include <vector>
namespace fincept::ai_chat {
@@ -48,4 +51,30 @@ QString extract_anthropic_content_text(const QJsonArray& content);
/// skips `functionCall` parts which the caller handles separately.
QString extract_gemini_parts_text(const QJsonArray& parts);
+/// One tool invocation recovered from text/XML markup.
+struct TextToolCall {
+ QString name; // may be "<server>__<tool>" or the bare tool name
+ QJsonObject args;
+};
+
+/// True when `content` carries any recognised text/XML tool-call markup.
+/// Cheap pre-check — use before paying for full extraction.
+bool has_text_tool_markup(const QString& content);
+
+/// Recover tool invocations emitted as text instead of structured `tool_calls`.
+/// Models without native function calling (MiniMax, some OpenRouter routes) and
+/// every prompt-injected catalog path (Fincept /research/llm/async) land here.
+///
+/// Patterns, in precedence order — the first that yields any call wins:
+/// 1. <tool_call>{"name":…, "arguments":{…}}</tool_call>
+/// 2. <invoke name="…"> with <parameter> children or a JSON body
+/// 3. [ns:]tool_call … /[ns:]tool_call (minimax style)
+/// 4. ```tool_call fenced JSON
+///
+/// A pattern-3 block whose body is not JSON is not a tool call we can name; its
+/// raw text is appended to *raw_blocks (when non-null) so a caller with access
+/// to the tool registry can map it onto a query/sql-shaped tool. Keeps this
+/// translation unit free of MCP dependencies.
+std::vector<TextToolCall> extract_text_tool_calls(const QString& content, QStringList* raw_blocks = nullptr);
+
} // namespace fincept::ai_chat
diff --git a/fincept-qt/src/services/llm/LlmFinceptAsync.cpp b/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
index 107e5c903..790f46471 100644
--- a/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
+++ b/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
@@ -1,38 +1,135 @@
// LlmFinceptAsync.cpp — Fincept-specific async LLM path.
//
-// POST /research/llm/async to submit, then poll /research/llm/status/{id}
-// every 3s up to 120s. The submit endpoint takes a flat prompt (not OpenAI
-// messages), so we synthesise system + tool catalog + history into a single
-// string here. Follow-ups after tool execution use the sync /research/chat
-// endpoint via try_extract_and_execute_text_tool_calls.
+// POST /research/llm/async to submit, then poll /research/llm/status/{id}. The
+// submit endpoint takes a FLAT prompt (not an OpenAI messages array), so system
+// prompt + tool catalog + history are synthesised into a single string here.
+//
+// ── Why this is a loop ────────────────────────────────────────────────────
+// Tool calling on this path is MULTI-ROUND. It used to be single-shot: execute
+// whatever tool the first reply named, then ask for a summary with tool calls
+// forbidden. With Tool RAG on (the default) the model only ever sees the Tier-0
+// tools, so round one is ALWAYS a discovery call — tool_list. The turn then
+// ended there and the user got the raw tool_list JSON presented as the answer.
+// A discovery chain needs three rounds (tool_list → tool_describe → the real
+// call) before there is anything worth summarising, so the loop is the fix.
+//
+// Each round appends the assistant turn plus its tool results to the prompt
+// transcript and re-submits. Follow-ups stay on /research/llm/async: the old
+// code hopped to the sync /research/chat endpoint, which is a different surface
+// with its own model default (an OpenRouter slug), so the Fincept model id we
+// send was not valid there — that request failing is what left the raw JSON in
+// the chat bubble.
+//
+// ── Why `tools` is NOT sent ───────────────────────────────────────────────
+// The published AsyncLLMRequest model carries `tools`/`tool_choice` fields, so
+// sending a standard OpenAI tool array looks right. It isn't. The backend
+// rejects it upstream:
+//
+// Fincept async task failed: LLM service error:
+// {"type":"error","error":{"type":"invalid_request_error",
+// "message":"invalid params, function name is empty (2013)"}}
+//
+// That `(2013)` + request_id envelope is MiniMax's, and the array we send is
+// well-formed OpenAI ({"type":"function","function":{"name",...}}) — the exact
+// shape that works when talking to the minimax provider directly. So the
+// backend re-wraps or flattens `tools` on the way through and loses
+// function.name. The endpoint's own documented client contract is
+// `{ prompt, temperature, max_tokens }`, its `tools` field has no item schema
+// published, and its documented response is a plain `data.response` string with
+// no tool_calls — i.e. the field is not a supported surface here.
+//
+// Tools on this path therefore travel ONE way: injected into the prompt as a
+// text catalog, invoked back as <tool_call> markup, executed here, and spliced
+// into the transcript for the next round. Do not re-add `tools` to the submit
+// body without first probing the endpoint for an item shape it actually
+// accepts — it breaks every Fincept chat, not just tool-using ones.
+//
+// Response-side structured tool_calls are still parsed if they ever appear;
+// that costs nothing and is how we'd notice the backend gaining support.
#include "core/config/AppConfig.h"
#include "core/logging/Logger.h"
#include "mcp/McpProvider.h"
#include "mcp/McpService.h"
+#include "mcp/ResultStore.h"
+#include "services/llm/LlmContentExtractors.h"
#include "services/llm/LlmRequestPolicy.h"
#include "services/llm/LlmService.h"
#include <QByteArray>
+#include <QElapsedTimer>
+#include <QHash>
#include <QJsonArray>
#include <QJsonDocument>
+#include <QList>
#include <QJsonObject>
+#include <QJsonValue>
+#include <QRegularExpression>
#include <QSet>
#include <QString>
#include <QStringList>
#include <QThread>
#include <QVariant>
+#include <algorithm>
+#include <vector>
+
namespace fincept::ai_chat {
namespace {
constexpr const char* kLlmFinceptTag = "LlmService";
-}
+
+// Runaway backstop, NOT a budget.
+//
+// There is deliberately no round budget on this path. Tool RAG costs ~3 rounds
+// per action before any real work happens, so every ceiling tried here (10, then
+// 20) was hit during discovery — the model spent the turn learning what tools
+// exist and ran out before writing anything, then apologised. Work is bounded by
+// whether the model is still making progress (see kMaxNoProgressRounds), not by
+// a count. This number only exists so a pathological loop can't run forever; it
+// matches the [1,200] clamp on max_tool_rounds used by the structured providers.
+constexpr int kFinceptHardStop = 200;
+
+// Consecutive rounds in which every tool call was a verbatim repeat already
+// served from cache — i.e. the model learned nothing new. That, not elapsed
+// rounds, is the real signal that a turn is stuck.
+constexpr int kMaxNoProgressRounds = 3;
+
+// HARD server limit on the whole `prompt` field:
+//
+// HTTP 422: body -> prompt: Value error, Prompt too long (max 50000 characters)
+//
+// The whole prompt is re-sent every round, so an unbounded turn otherwise grows
+// an unbounded request — a 10-round turn already reached ~34 KB. Everything the
+// composer emits (system prompt + tool catalog + chat history + round
+// transcript + trailing instruction) has to fit under this together, so the
+// round budget is derived from what the fixed parts leave over, never fixed
+// independently. A previous 120000 constant here was above the server cap and
+// 422'd on long turns.
+constexpr int kServerMaxPromptChars = 50000;
+
+// Headroom for the trailing instruction and the elision notices, and so a
+// rounding slip can't land exactly on the cap.
+constexpr int kPromptSafetyMargin = 2000;
+
+// Wall-clock budget for polling a single submitted task.
+constexpr qint64 kPollBudgetMs = 120000;
+
+// Poll fast at first — most tasks finish in a few seconds and a flat 3 s floor
+// added a guaranteed 3 s to every single round of the loop.
+constexpr int kFastPollMs = 1000;
+constexpr int kFastPollCount = 6;
+constexpr int kSlowPollMs = 3000;
+
+// Tool results are spliced into a prompt string that is re-sent whole on every
+// later round, so an unshaped result is re-billed for the rest of the turn.
+// Mirrors the structured path's transcript discipline (see fit_llm_payload).
+constexpr int kToolResultBudgetBytes = 4000;
+} // namespace
// Build a compact tool catalog string for injection into the system prompt.
// This allows models that don't support structured tool_calls to still emit
-// text-based tool invocations that try_extract_and_execute_text_tool_calls
-// can detect and execute.
+// text-based tool invocations that extract_text_tool_calls can detect.
//
// Two modes:
// • Tool RAG ON + default filter: emit only the Tier-0 tools + explicit
@@ -54,7 +151,10 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {
QString catalog;
catalog += "You have access to tools. To use one, emit a <tool_call> block:\n";
- catalog += "<tool_call>{\"name\": \"TOOL_NAME\", \"arguments\": {\"param\": \"value\"}}</tool_call>\n\n";
+ catalog += "<tool_call>{\"name\": \"TOOL_NAME\", \"arguments\": {\"param\": \"value\"}}</tool_call>\n";
+ catalog += "Emit the block ALONE, with no commentary around it — you will be called again with the "
+ "result and can then continue. Only call a tool when the request needs live data or an "
+ "action in the terminal; answer greetings and general questions directly in plain text.\n\n";
if (use_rag) {
// Mirror McpService::tier_0_tool_names() (kept in sync manually — small
@@ -69,13 +169,32 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {
QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
catalog += "- " + fn_name + ": " + tool.description + "\n";
}
- const QString wire_list = QStringLiteral("tool_list");
- const QString wire_describe = QStringLiteral("tool_describe");
- catalog += QStringLiteral("\nFor any other capability, call fincept-terminal__%1 with a natural-language "
- "query (e.g. {\"query\": \"draft a research report\"}). It returns the top 5 most "
- "relevant tools. Then call fincept-terminal__%2(name) for the full schema, "
- "then invoke the tool. For multi-intent requests, call %1 multiple times.\n")
- .arg(wire_list, wire_describe);
+ // The three-step loop is spelled out with a worked example on purpose.
+ // The previous wording ended with "then invoke the tool", which never
+ // said HOW — and a model that has just discovered a tool has no reason
+ // to assume the mechanism is the same <tool_call> block it used for
+ // discovery. One observed turn burned 17 rounds searching for an
+ // execute/invoke/run tool (tool_list "call execute ma_sec_dcf_inputs
+ // ticker AAPL") while never once calling ma_sec_dcf_inputs itself.
+ catalog += QStringLiteral(
+ "\nThe two tools above are the only ones listed here, but they are NOT the only ones you can call.\n"
+ "You can call ANY tool name that tool_list returns, immediately, using the same <tool_call> block.\n"
+ "There is no separate execute/invoke/run step and no registration step — emitting the block IS "
+ "calling the tool.\n"
+ "\n"
+ "Worked example — the full three steps:\n"
+ " 1. <tool_call>{\"name\": \"tool_list\", \"arguments\": {\"query\": \"SEC DCF inputs for a "
+ "company\"}}</tool_call>\n"
+ " -> returns e.g. a tool named \"ma_sec_dcf_inputs\"\n"
+ " 2. <tool_call>{\"name\": \"tool_describe\", \"arguments\": {\"name\": "
+ "\"ma_sec_dcf_inputs\"}}</tool_call>\n"
+ " -> returns its input schema, e.g. {\"ticker\": \"string\"}\n"
+ " 3. <tool_call>{\"name\": \"ma_sec_dcf_inputs\", \"arguments\": {\"ticker\": \"AAPL\"}}</tool_call>\n"
+ " -> THIS is the call that returns the data. Step 3 is the point of steps 1 and 2.\n"
+ "\n"
+ "Do not call tool_list again looking for a way to run a tool you have already found — you already "
+ "have it; go straight to step 3. The server prefix (fincept-terminal__) is optional; a bare tool "
+ "name works. For requests with several intents, run the loop once per intent.\n");
return catalog;
}
@@ -102,45 +221,89 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {
return catalog;
}
-LlmResponse LlmService::fincept_async_request(const QString& user_message,
- const std::vector<ConversationMessage>& history) {
- LlmResponse resp;
+// Dig a human-readable failure reason out of a status payload.
+//
+// The old code checked exactly two spots — `error` at the top level and under
+// `data` — and fell back to the literal string "unknown error" while logging
+// nothing. A backend that reports its reason anywhere else (nested one level
+// deeper, or under `message`/`detail`, or as an object rather than a string)
+// was therefore indistinguishable from a backend that said nothing at all,
+// which makes "is this us or the server?" unanswerable from the logs.
+static QString fincept_extract_error(const QJsonObject& root) {
+ static const char* kKeys[] = {"error", "message", "detail", "reason", "error_message"};
- // Build prompt string for the async endpoint (it takes a plain prompt, not messages)
- QString prompt;
- if (!system_prompt_.isEmpty())
- prompt += system_prompt_ + "\n\n";
+ // Breadth-first over the payload and its nested `data` objects.
+ QList<QJsonObject> scopes{root};
+ if (root["data"].isObject()) {
+ const QJsonObject d = root["data"].toObject();
+ scopes.append(d);
+ if (d["data"].isObject())
+ scopes.append(d["data"].toObject());
+ }
- // Inject tool catalog so the model can emit text-based tool calls
- if (detail::effective_tools_enabled(tools_enabled_)) {
- QString tool_catalog = build_tool_catalog_for_prompt(detail::apply_request_policy(tool_filter_));
- if (!tool_catalog.isEmpty())
- prompt += tool_catalog + "\n";
+ for (const QJsonObject& scope : scopes) {
+ for (const char* key : kKeys) {
+ const QJsonValue v = scope.value(QLatin1String(key));
+ if (v.isString() && !v.toString().trimmed().isEmpty())
+ return v.toString().trimmed();
+ // Some gateways nest {"error": {"message": "..."}}.
+ if (v.isObject()) {
+ const QJsonObject o = v.toObject();
+ for (const char* inner : kKeys) {
+ const QJsonValue iv = o.value(QLatin1String(inner));
+ if (iv.isString() && !iv.toString().trimmed().isEmpty())
+ return iv.toString().trimmed();
+ }
+ return QString::fromUtf8(QJsonDocument(o).toJson(QJsonDocument::Compact));
+ }
+ }
}
+ return {};
+}
- for (const auto& m : history) {
- if (m.role == "user")
- prompt += "User: " + m.content + "\n\n";
- else if (m.role == "assistant")
- prompt += "Assistant: " + m.content + "\n\n";
+// Render one tool result for splicing back into the prompt transcript.
+static QString fincept_render_tool_result(const mcp::ToolResult& tr) {
+ // Failures are marked unmissably. A model that skims a JSON envelope for
+ // "success":false will happily report the action as done — one observed turn
+ // had set_excel_sheet_data denied by an auth gate and still told the user
+ // "the sheet was created successfully with all the DCF model data", reading
+ // the following recalculate_excel_sheet -> OK as confirmation.
+ if (!tr.success) {
+ const QString why = !tr.error.isEmpty() ? tr.error : (!tr.message.isEmpty() ? tr.message : QStringLiteral("unknown error"));
+ return QStringLiteral("FAILED - this action did NOT happen. Reason: ") + why;
}
- prompt += "User: " + user_message;
+ if (!tr.message.isEmpty())
+ return tr.message;
+ QJsonValue payload = (!tr.data.isNull() && !tr.data.isUndefined()) ? tr.data : QJsonValue(tr.to_json());
+ mcp::shrink_json(payload, kToolResultBudgetBytes);
+ if (payload.isObject())
+ return QString::fromUtf8(QJsonDocument(payload.toObject()).toJson(QJsonDocument::Compact));
+ if (payload.isArray())
+ return QString::fromUtf8(QJsonDocument(payload.toArray()).toJson(QJsonDocument::Compact));
+ return payload.toVariant().toString();
+}
+LlmResponse LlmService::fincept_submit_poll(const QString& prompt, QJsonArray* out_tool_calls) {
+ LlmResponse resp;
+ if (out_tool_calls)
+ *out_tool_calls = {};
+
+ // {prompt, max_tokens} only — the endpoint's documented contract. No
+ // `tools` (see the header note), no temperature (backend default).
QJsonObject submit_body;
submit_body["prompt"] = prompt;
submit_body["max_tokens"] = resolved_max_tokens();
- // Temperature intentionally omitted — Fincept backend uses its own default.
auto hdr = get_headers();
const QString fincept_base = fincept::AppConfig::instance().api_base_url();
const QString async_url = fincept_base + "/research/llm/async";
const QString status_base = fincept_base + "/research/llm/status/";
- LOG_INFO(kLlmFinceptTag,
- QString("Fincept async: submitting to %1 (api_key=%2, prompt_len=%3)")
- .arg(async_url)
- .arg(api_key_.isEmpty() ? QStringLiteral("EMPTY") : QStringLiteral("len=%1").arg(api_key_.size()))
- .arg(prompt.length()));
+ LOG_INFO(kLlmFinceptTag, QString("Fincept async: submitting to %1 (api_key=%2, prompt_len=%3)")
+ .arg(async_url)
+ .arg(api_key_.isEmpty() ? QStringLiteral("EMPTY")
+ : QStringLiteral("len=%1").arg(api_key_.size()))
+ .arg(prompt.length()));
QByteArray json_data = QJsonDocument(submit_body).toJson(QJsonDocument::Compact);
auto submit = eventloop_request("POST", async_url, json_data, hdr, 30000);
@@ -153,6 +316,7 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,
auto submit_doc = QJsonDocument::fromJson(submit.body);
if (submit_doc.isNull()) {
resp.error = "Fincept async: failed to parse submit response";
+ LOG_ERROR(kLlmFinceptTag, resp.error);
return resp;
}
@@ -163,15 +327,16 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,
task_id = sj["data"].toObject()["task_id"].toString();
if (task_id.isEmpty()) {
resp.error = "Fincept async: no task_id in submit response";
+ LOG_ERROR(kLlmFinceptTag, resp.error);
return resp;
}
LOG_INFO(kLlmFinceptTag, "Fincept async task_id: " + task_id);
- // Poll every 3 seconds, up to 120 seconds total
const QString poll_url = status_base + task_id;
- constexpr int MAX_POLLS = 40;
- for (int i = 0; i < MAX_POLLS; ++i) {
- QThread::msleep(3000);
+ QElapsedTimer clock;
+ clock.start();
+ for (int i = 0; clock.elapsed() < kPollBudgetMs; ++i) {
+ QThread::msleep(static_cast<unsigned long>(i < kFastPollCount ? kFastPollMs : kSlowPollMs));
auto poll = eventloop_request("GET", poll_url, {}, hdr, 15000);
if (!poll.success) {
@@ -189,56 +354,456 @@ LlmResponse LlmService::fincept_async_request(const QString& user_message,
if (status.isEmpty())
status = data_obj["status"].toString();
- LOG_INFO(kLlmFinceptTag, QString("Fincept async poll %1 status=%2").arg(i + 1).arg(status));
-
- if (status == "completed") {
- // data.data.response
- QString response = data_obj["data"].toObject()["response"].toString();
- if (response.isEmpty())
- response = data_obj["response"].toString();
- if (response.isEmpty()) {
- resp.error = "Fincept async completed but response is empty";
- LOG_WARN(kLlmFinceptTag, "Fincept async task completed with empty response field");
- return resp;
- }
- resp.content = response;
- resp.success = true;
-
- QJsonObject usage = data_obj["data"].toObject()["usage"].toObject();
- if (!usage.isEmpty()) {
- resp.prompt_tokens = usage["input_tokens"].toInt();
- resp.completion_tokens = usage["output_tokens"].toInt();
- resp.total_tokens = usage["total_tokens"].toInt();
+ LOG_INFO(kLlmFinceptTag, QString("Fincept async poll %1 status=%2 (%3 ms)").arg(i + 1).arg(status).arg(
+ clock.elapsed()));
+
+ if (status == "failed") {
+ const QString err = fincept_extract_error(pj);
+ // Always log the raw body when the reason can't be named. Without
+ // it "unknown error" is a dead end — there is no way to tell a
+ // silent backend from a reason we simply failed to look for.
+ if (err.isEmpty()) {
+ LOG_ERROR(kLlmFinceptTag, QStringLiteral("Fincept async task failed with no reason field. Raw "
+ "status body: ") +
+ QString::fromUtf8(poll.body.left(1200)));
}
+ resp.error = "Fincept async task failed: " +
+ (err.isEmpty() ? QStringLiteral("the server reported a failure but gave no reason "
+ "(see log for the raw response)")
+ : err);
+ LOG_ERROR(kLlmFinceptTag, resp.error);
+ resp.retryable = true; // upstream/model failure, not a bad request
+ return resp;
+ }
+ if (status != "completed")
+ continue;
+
+ // data.data.response, or data.response on the flatter shape.
+ const QJsonObject inner = data_obj["data"].toObject();
+ QString response = inner["response"].toString();
+ if (response.isEmpty())
+ response = data_obj["response"].toString();
- // Check for text-based tool calls in the response.
- // The model may have emitted <tool_call>...</tool_call> blocks.
- if (!resp.content.isEmpty()) {
- LOG_INFO(kLlmFinceptTag, "Fincept: checking response for text-based tool calls");
- // Use the sync /research/chat endpoint for follow-up after tool execution
- QString followup_url = get_endpoint_url();
- auto followup_hdr = get_headers();
- auto tool_result =
- try_extract_and_execute_text_tool_calls(resp.content, user_message, followup_url, followup_hdr);
- if (tool_result.has_value()) {
- LOG_INFO(kLlmFinceptTag, "Fincept: text tool calls detected and executed");
- return tool_result.value();
+ // Structured tool_calls, if this backend produces them. Checked in the
+ // same places the text response is found — the payload shape is not
+ // published, so accept any of them rather than guess one.
+ if (out_tool_calls) {
+ for (const QJsonObject& scope : {inner, data_obj, pj}) {
+ const QJsonArray tcs = scope["tool_calls"].toArray();
+ if (!tcs.isEmpty()) {
+ *out_tool_calls = tcs;
+ break;
}
}
- return resp;
}
- if (status == "failed") {
- QString err = pj["error"].toString();
- if (err.isEmpty())
- err = data_obj["error"].toString();
- resp.error = "Fincept async task failed: " + (err.isEmpty() ? "unknown error" : err);
+ if (response.isEmpty() && (!out_tool_calls || out_tool_calls->isEmpty())) {
+ resp.error = "Fincept async completed but response is empty";
+ LOG_WARN(kLlmFinceptTag, "Fincept async task completed with empty response field");
return resp;
}
+
+ resp.content = strip_think_blocks(response);
+ resp.success = true;
+
+ const QJsonObject usage = inner["usage"].toObject();
+ if (!usage.isEmpty()) {
+ resp.prompt_tokens = usage["input_tokens"].toInt();
+ resp.completion_tokens = usage["output_tokens"].toInt();
+ resp.total_tokens = usage["total_tokens"].toInt();
+ }
+ return resp;
}
resp.error = "Fincept async timed out waiting for response";
+ LOG_ERROR(kLlmFinceptTag, resp.error);
return resp;
}
+LlmResponse LlmService::fincept_async_request(const QString& user_message,
+ const std::vector<ConversationMessage>& history) {
+ const bool tools_on = detail::effective_tools_enabled(tools_enabled_);
+ const mcp::ToolFilter filter = detail::apply_request_policy(tool_filter_);
+
+ // ── Prompt parts, kept separate so each can be trimmed independently ──
+ // Priority when the 50 000-char cap bites, least valuable dropped first:
+ // 1. oldest prior-conversation turns (context from before this request)
+ // 2. oldest tool-round blocks (this turn's earlier findings)
+ // The instructions, the tool catalog and the user's actual question are
+ // never dropped — without them the model cannot act at all.
+ QString head;
+ if (!system_prompt_.isEmpty())
+ head += system_prompt_ + "\n\n";
+ if (tools_on) {
+ const QString tool_catalog = build_tool_catalog_for_prompt(filter);
+ if (!tool_catalog.isEmpty())
+ head += tool_catalog + "\n";
+ }
+
+ QStringList history_blocks;
+ for (const auto& m : history) {
+ if (m.role == "user")
+ history_blocks.append("User: " + m.content + "\n\n");
+ else if (m.role == "assistant")
+ history_blocks.append("Assistant: " + m.content + "\n\n");
+ }
+ const QString ask = "User: " + user_message;
+
+ // One block per round so the oldest can be dropped when the prompt no
+ // longer fits. Kept out of the fixed prefix so the trailing "continue"
+ // instruction is re-composed each round rather than accumulating a stale
+ // copy inside the transcript on every iteration.
+ QStringList round_blocks;
+ bool rounds_elided = false;
+ bool history_dropped = false;
+
+ static const QString kRoundsElidedNote =
+ QStringLiteral("\n\n[Earlier tool rounds were dropped to fit the context. Their results are no longer "
+ "available — if you need one again, call the tool again.]\n");
+ static const QString kHistoryElidedNote =
+ QStringLiteral("[Earlier messages in this conversation were dropped to fit the context.]\n\n");
+
+ auto total_size = [](const QStringList& l) {
+ qsizetype n = 0;
+ for (const auto& s : l)
+ n += s.size();
+ return n;
+ };
+
+ // Assemble head + history + ask + rounds + tail so the whole thing fits
+ // under the server cap, dropping the least valuable parts first.
+ auto compose_prompt = [&](const QString& tail) -> QString {
+ const qsizetype budget = kServerMaxPromptChars - kPromptSafetyMargin;
+ const qsizetype fixed = head.size() + ask.size() + tail.size();
+
+ qsizetype avail = budget - fixed;
+ if (avail < 0) {
+ // Degenerate: the instructions plus the question alone exceed the
+ // cap. Nothing to trim that wouldn't break the request outright —
+ // send it and let the server rule, but say so in the log.
+ LOG_ERROR(kLlmFinceptTag, QString("Fincept: fixed prompt parts are %1 chars, over the %2 cap — the "
+ "system prompt or tool catalog is too large")
+ .arg(fixed)
+ .arg(kServerMaxPromptChars));
+ avail = 0;
+ }
+
+ // Round blocks earn their space first — they are this turn's work.
+ while (total_size(round_blocks) > avail && round_blocks.size() > 1) {
+ round_blocks.removeFirst();
+ if (!rounds_elided) {
+ rounds_elided = true;
+ LOG_WARN(kLlmFinceptTag, "Fincept: prompt at the server cap — dropping oldest tool rounds");
+ }
+ }
+ // A single round can still exceed the budget on its own (several large
+ // tool results in one turn). Truncate rather than 422 — and mark it, so
+ // the model doesn't read a cut-off result as the whole answer.
+ if (round_blocks.size() == 1 && round_blocks.first().size() > avail && avail > 200) {
+ round_blocks[0] = round_blocks.first().left(avail - 120) +
+ QStringLiteral("\n[... tool output truncated to fit the context ...]\n");
+ LOG_WARN(kLlmFinceptTag, "Fincept: single round block exceeded the prompt budget — truncated");
+ }
+ qsizetype remaining = avail - total_size(round_blocks) - (rounds_elided ? kRoundsElidedNote.size() : 0);
+
+ // Whatever is left goes to prior conversation, oldest dropped first.
+ while (total_size(history_blocks) > remaining && !history_blocks.isEmpty()) {
+ history_blocks.removeFirst();
+ if (!history_dropped) {
+ history_dropped = true;
+ LOG_WARN(kLlmFinceptTag, "Fincept: prompt at the server cap — dropping oldest conversation turns");
+ }
+ remaining = avail - total_size(round_blocks) - (rounds_elided ? kRoundsElidedNote.size() : 0) -
+ kHistoryElidedNote.size();
+ }
+
+ QString out = head;
+ if (history_dropped)
+ out += kHistoryElidedNote;
+ out += history_blocks.join(QString());
+ out += ask;
+ if (rounds_elided)
+ out += kRoundsElidedNote;
+ out += round_blocks.join(QString());
+ out += tail;
+
+ if (out.size() > kServerMaxPromptChars) {
+ LOG_ERROR(kLlmFinceptTag,
+ QString("Fincept: composed prompt is %1 chars, still over the cap").arg(out.size()));
+ }
+ return out;
+ };
+
+ // No ActivationTracker here, unlike the structured providers: nothing is
+ // re-declared to the backend because nothing is declared to begin with.
+ // tool_describe's schema lands in the transcript as text, which is what the
+ // model reads before emitting the real call.
+ //
+ // Results are memoised per (tool, args) for the turn. A flat prompt gives the
+ // model no structural cue that a call already happened, and it will re-issue
+ // the identical call indefinitely — one observed turn spent 4 of its 10 rounds
+ // on the same tool_describe{"name":"set_excel_sheet_data"} and ran out of
+ // budget before writing anything. Re-serving the cached result with an
+ // explicit "you already called this" note breaks the cycle without wasting
+ // a round.
+ QHash<QString, QString> call_cache;
+
+ static const QString kContinueHint =
+ QStringLiteral("\nContinue. If you still need data or an action, emit the next <tool_call> block and nothing "
+ "else. Do NOT repeat a call already listed above — its result is there; use it. There is no "
+ "limit on how many tools you may call, so gather everything you need and COMPLETE the task "
+ "rather than stopping to report progress. A result marked FAILED means that action did NOT "
+ "happen: fix it and retry, or say plainly that it failed — never describe failed work as "
+ "done. Only when the work is actually done, write the final answer in plain text with no "
+ "markup.\n\nAssistant:");
+
+ QElapsedTimer turn_clock;
+ turn_clock.start();
+
+ // Rounds spent asking the model to re-emit malformed markup. Bounded so a
+ // model that simply cannot produce a clean block still terminates with text.
+ int malformed_rounds = 0;
+ constexpr int kMaxMalformedRounds = 2;
+
+ // Consecutive rounds that produced no new information (every call a cache
+ // hit). This is the stop condition — not a round count.
+ int no_progress_rounds = 0;
+
+ // Tools the model has fetched a schema for, and how many consecutive rounds
+ // it has spent searching/describing without calling any of them.
+ QStringList described_tools;
+ int discovery_only_rounds = 0;
+
+ // Outcome tally across the turn, excluding the discovery meta-tools. Used to
+ // catch the worst failure mode there is: every real call rejected, and the
+ // model reporting the task as done anyway.
+ int real_calls = 0;
+ int real_failures = 0;
+ bool challenged_fabrication = false;
+
+ LlmResponse resp;
+ for (int round = 0; round < kFinceptHardStop; ++round) {
+ QJsonArray structured_calls;
+ const QString prompt = compose_prompt(round_blocks.isEmpty() ? QString() : kContinueHint);
+ resp = fincept_submit_poll(prompt, &structured_calls);
+ // One retry on a transient upstream failure. An observed task ran 62 s
+ // and then reported failure with no reason on a 5 KB prompt — nothing
+ // about the request to fix, so resubmitting is the only useful response.
+ // The endpoint documents that failed tasks are not charged.
+ if (!resp.success && resp.retryable) {
+ LOG_WARN(kLlmFinceptTag, "Fincept: task failed upstream — resubmitting once");
+ resp = fincept_submit_poll(prompt, &structured_calls);
+ }
+ if (!resp.success)
+ return resp;
+
+ if (!tools_on)
+ return resp;
+
+ // ── Collect this round's tool calls ──
+ std::vector<TextToolCall> calls;
+ for (const auto& tc_val : structured_calls) {
+ const QJsonObject tc = tc_val.toObject();
+ const QJsonObject fn = tc["function"].toObject();
+ const QString name = fn["name"].toString();
+ if (name.isEmpty())
+ continue;
+ QJsonValue raw_args = fn["arguments"];
+ QJsonObject args = raw_args.isObject()
+ ? raw_args.toObject()
+ : QJsonDocument::fromJson(raw_args.toString("{}").toUtf8()).object();
+ calls.push_back({name, args});
+ }
+ if (calls.empty())
+ calls = extract_text_tool_calls(resp.content);
+
+ if (calls.empty()) {
+ // Markup we recognised but could not parse. Returning it verbatim
+ // dumps raw <tool_call> JSON into the chat bubble dressed up as an
+ // answer — the exact failure this loop exists to prevent. Show the
+ // model its own malformed output and ask for one clean block.
+ if (has_text_tool_markup(resp.content) && ++malformed_rounds <= kMaxMalformedRounds) {
+ LOG_WARN(kLlmFinceptTag, QString("Fincept: round %1 emitted unparsable tool markup (attempt %2/%3) — "
+ "asking the model to re-issue it")
+ .arg(round)
+ .arg(malformed_rounds)
+ .arg(kMaxMalformedRounds));
+ round_blocks.append("\n\nAssistant: " + resp.content.trimmed() +
+ "\n\nSystem: That tool call could not be parsed. Emit EXACTLY ONE tool call, as a "
+ "single JSON object on one line, wrapped in <tool_call> and </tool_call>, with no "
+ "other text:\n<tool_call>{\"name\": \"TOOL_NAME\", \"arguments\": {}}</tool_call>\n"
+ "If you need two tools, call the first one now and the second one next turn.\n");
+ continue;
+ }
+
+ // Retries exhausted and the markup is still unparsable. Scrub it —
+ // half a JSON blob is noise to the user either way.
+ if (has_text_tool_markup(resp.content)) {
+ LOG_WARN(kLlmFinceptTag, "Fincept: giving up on unparsable tool markup — stripping it from the answer");
+ static const QRegularExpression rx_block("<\\s*(?:\\w+\\s*:\\s*)?tool_call\\s*>[\\s\\S]*?(?:<\\s*/"
+ "\\s*(?:\\w+\\s*:\\s*)?tool_call\\s*>|$)",
+ QRegularExpression::CaseInsensitiveOption);
+ resp.content = resp.content.remove(rx_block).trimmed();
+ if (resp.content.isEmpty()) {
+ resp.success = false;
+ resp.error = QStringLiteral("The model kept emitting malformed tool calls. Please try again.");
+ return resp;
+ }
+ }
+
+ // Every real tool call was rejected, yet the model is answering.
+ // That is the shape of a fabricated report — one turn had
+ // create_workbook/add_tab (nonexistent) and 15 get_excel_cell calls
+ // all fail, then described a finished workbook down to the cell
+ // references and a per-share valuation. Send it back once with the
+ // tally; if it insists, the answer stands but the log records it.
+ if (real_calls > 0 && real_failures == real_calls && !challenged_fabrication) {
+ challenged_fabrication = true;
+ LOG_WARN(kLlmFinceptTag, QString("Fincept: all %1 real tool call(s) failed but the model produced an "
+ "answer — challenging it")
+ .arg(real_calls));
+ round_blocks.append("\n\nAssistant: " + resp.content.trimmed() +
+ "\n\nSystem: STOP. Every one of the " + QString::number(real_calls) +
+ " tool calls you made this turn FAILED. Nothing was created, written, read or "
+ "recalculated. Any file, workbook, tab, cell value or computed figure you just "
+ "described does not exist. Rewrite your reply: state plainly that the task was "
+ "not completed, list the calls that failed and why, and do not report any "
+ "number you did not receive from a successful tool result.\n");
+ continue;
+ }
+
+ // Plain text — the answer.
+ LOG_INFO(kLlmFinceptTag, QString("Fincept: finished after %1 round(s), %2 chars (%3/%4 real tool calls "
+ "failed)")
+ .arg(round + 1)
+ .arg(resp.content.length())
+ .arg(real_failures)
+ .arg(real_calls));
+ return resp;
+ }
+
+ if (round == kFinceptHardStop - 1) {
+ LOG_WARN(kLlmFinceptTag, QString("Fincept: hit the %1-round runaway backstop — forcing a summary turn")
+ .arg(kFinceptHardStop));
+ break;
+ }
+
+ // ── Execute and splice the results back into the transcript ──
+ QString block = "\n\nAssistant: " + resp.content.trimmed() + "\n\nTool results:\n";
+ int fresh_calls = 0;
+ bool only_discovery = true; // this round did nothing but search/describe
+ for (const auto& tc : calls) {
+ const int sep = tc.name.indexOf(QStringLiteral("__"));
+ QString display = (sep >= 0) ? tc.name.mid(sep + 2) : tc.name;
+ display.replace(QStringLiteral("-dot-"), QStringLiteral("."));
+
+ const QString args_json =
+ QString::fromUtf8(QJsonDocument(tc.args).toJson(QJsonDocument::Compact));
+ const QString cache_key = display + QLatin1Char('|') + args_json;
+
+ detail::emit_tool_progress(display, tc.args);
+
+ const auto cached = call_cache.constFind(cache_key);
+ if (cached != call_cache.constEnd()) {
+ LOG_WARN(kLlmFinceptTag, QString("Fincept tool round %1: %2 repeated verbatim — serving cached result")
+ .arg(round)
+ .arg(display));
+ block += "- " + display + " -> (ALREADY CALLED this turn with the same arguments; the result is "
+ "unchanged and repeated here. Do not call it again.) " +
+ cached.value() + "\n";
+ continue;
+ }
+ ++fresh_calls;
+
+ LOG_INFO(kLlmFinceptTag, QString("Fincept tool round %1: executing %2 args=%3")
+ .arg(round)
+ .arg(display, args_json.left(200)));
+
+ // allow_defer stays false: this path has no job_* protocol wired in,
+ // so a receipt would be mistaken for the result (see §M5).
+ auto tr = mcp::McpService::instance().execute_openai_function(tc.name, tc.args);
+ LOG_INFO(kLlmFinceptTag, QString("Fincept tool round %1: %2 -> %3 (err=%4)")
+ .arg(round)
+ .arg(display, tr.success ? "OK" : "FAIL", tr.error.left(120)));
+ const QString rendered = fincept_render_tool_result(tr);
+ call_cache.insert(cache_key, rendered);
+ block += "- " + display + " -> " + rendered + "\n";
+
+ // Remember which real tools the model has already looked up, and
+ // whether it ever got past looking things up this round.
+ if (display == QLatin1String("tool_describe")) {
+ const QString looked_up = tc.args.value(QStringLiteral("name")).toString();
+ if (tr.success && !looked_up.isEmpty() && !described_tools.contains(looked_up))
+ described_tools.append(looked_up);
+ } else if (display != QLatin1String("tool_list")) {
+ only_discovery = false;
+ ++real_calls;
+ if (!tr.success)
+ ++real_failures;
+ }
+ }
+
+ // Break the search-forever loop. tool_list with a fresh query always
+ // returns something, so the no-progress check never fires — a turn can
+ // spend every round hunting for a way to "execute" a tool it already
+ // holds the schema for. Name the tools it already has and tell it to
+ // call one.
+ if (only_discovery && !described_tools.isEmpty()) {
+ if (++discovery_only_rounds >= 2) {
+ block += "\nSystem: STOP SEARCHING. You already have the schema for: " +
+ described_tools.join(QStringLiteral(", ")) +
+ ". There is no separate execute/invoke/run tool — emitting a <tool_call> block IS how you "
+ "call it. Your next message must be exactly one <tool_call> block naming one of those "
+ "tools, e.g. <tool_call>{\"name\": \"" +
+ described_tools.last() +
+ "\", \"arguments\": {...}}</tool_call>, with the arguments its schema requires.\n";
+ LOG_WARN(kLlmFinceptTag, QString("Fincept: %1 discovery-only rounds — nudging the model to call %2")
+ .arg(discovery_only_rounds)
+ .arg(described_tools.last()));
+ }
+ } else {
+ discovery_only_rounds = 0;
+ }
+
+ round_blocks.append(block);
+
+ // Progress check. A round in which every call was already cached taught
+ // the model nothing, so repeating it will teach it nothing either. This
+ // — not a round count — is what ends a stuck turn.
+ if (fresh_calls == 0) {
+ if (++no_progress_rounds >= kMaxNoProgressRounds) {
+ LOG_WARN(kLlmFinceptTag, QString("Fincept: %1 consecutive rounds with no new tool results — stopping")
+ .arg(no_progress_rounds));
+ break;
+ }
+ } else {
+ no_progress_rounds = 0;
+ }
+ }
+
+ LOG_INFO(kLlmFinceptTag, QString("Fincept: tool phase ended after %1 round block(s), %2 ms — requesting close-out")
+ .arg(round_blocks.size())
+ .arg(turn_clock.elapsed()));
+
+ // Stopped with a tool call still pending. Ask for a close-out in plain text
+ // rather than leaving raw markup in the chat bubble. Passed as the tail so
+ // it survives trimming — dropping the instruction would defeat the turn.
+ const QString final_prompt = compose_prompt(QStringLiteral(
+ "\n\nStop calling tools now and reply in plain text with no tool calls or markup: state what you completed "
+ "and anything still incomplete.\n\nAssistant:"));
+ LlmResponse final_turn = fincept_submit_poll(final_prompt, nullptr);
+ if (!final_turn.success && final_turn.retryable) {
+ LOG_WARN(kLlmFinceptTag, "Fincept: close-out turn failed upstream — resubmitting once");
+ final_turn = fincept_submit_poll(final_prompt, nullptr);
+ }
+ if (final_turn.success && !final_turn.content.isEmpty())
+ return final_turn;
+
+ // Nothing usable — surface the failure instead of leaking tool markup.
+ LlmResponse err;
+ err.error = final_turn.error.isEmpty() ? QStringLiteral("Fincept LLM stopped without producing an answer.")
+ : final_turn.error;
+ return err;
+}
+
} // namespace fincept::ai_chat
diff --git a/fincept-qt/src/services/llm/LlmModelsApi.cpp b/fincept-qt/src/services/llm/LlmModelsApi.cpp
index 0777f7235..3c2c919e4 100644
--- a/fincept-qt/src/services/llm/LlmModelsApi.cpp
+++ b/fincept-qt/src/services/llm/LlmModelsApi.cpp
@@ -82,8 +82,9 @@ QString LlmService::get_models_url(const QString& provider, const QString& api_k
return "https://api.moonshot.ai/v1/models";
if (p == "aihubmix")
return "https://aihubmix.com/v1/models"; // fallback if prefilled base_url was cleared
- if (p == "fincept")
- return fincept::AppConfig::instance().api_base_url() + "/research/llm/models";
+ // fincept publishes no models endpoint — /research/llm/models is a 404, and
+ // /research/llm/async takes no `model` field at all (the backend picks).
+ // fetch_models() short-circuits to the known list before reaching here.
// minimax has no public /v1/models — caller falls back to known models.
return {};
}
diff --git a/fincept-qt/src/services/llm/LlmRequestPolicy.h b/fincept-qt/src/services/llm/LlmRequestPolicy.h
index b9a283a9d..8a8b82b7c 100644
--- a/fincept-qt/src/services/llm/LlmRequestPolicy.h
+++ b/fincept-qt/src/services/llm/LlmRequestPolicy.h
@@ -57,6 +57,56 @@ inline void emit_progress(const QString& text) {
t_progress_emitter(text);
}
+/// Human-readable one-line label for a tool call.
+///
+/// The discovery meta-tools are the ones a user sees most and understands least,
+/// so they get plain-English wording plus the argument that distinguishes one
+/// call from the next — without it, six `tool_describe` calls for six different
+/// tools all render as the identical string "tool_describe".
+inline QString tool_progress_label(const QString& display_name, const QJsonObject& args) {
+ if (display_name == QLatin1String("tool_list")) {
+ const QString q = args.value(QStringLiteral("query")).toString().trimmed();
+ return q.isEmpty() ? QStringLiteral("Finding tools") : QStringLiteral("Finding tools · ") + q;
+ }
+ if (display_name == QLatin1String("tool_describe")) {
+ const QString n = args.value(QStringLiteral("name")).toString().trimmed();
+ return n.isEmpty() ? QStringLiteral("Reading schema") : QStringLiteral("Reading schema · ") + n;
+ }
+ if (display_name == QLatin1String("result_fetch"))
+ return QStringLiteral("Fetching full result");
+
+ // Real tools: name plus the first short STRING argument as context
+ // ("get_news · MARKETS"). Positional indices are deliberately excluded — a
+ // run of set_excel_cell calls rendered as "· 0 / · 1 / · 3 / · 1 …", which
+ // tells the reader nothing and defeats run-collapsing downstream. Numbers in
+ // general make poor labels, so only strings qualify.
+ static const QSet<QString> kPositionalKeys = {
+ QStringLiteral("sheet_index"), QStringLiteral("row"), QStringLiteral("col"),
+ QStringLiteral("column"), QStringLiteral("index"), QStringLiteral("limit"),
+ QStringLiteral("offset"), QStringLiteral("top_k"), QStringLiteral("count"),
+ };
+ for (auto it = args.constBegin(); it != args.constEnd(); ++it) {
+ if (!it.value().isString() || kPositionalKeys.contains(it.key().toLower()))
+ continue;
+ const QString v = it.value().toString().trimmed();
+ if (v.isEmpty() || v.size() > 40 || v.contains(QLatin1Char('\n')))
+ continue;
+ return display_name + QStringLiteral(" · ") + v;
+ }
+ return display_name;
+}
+
+/// Emit one tool-progress line on the dedicated tool channel.
+///
+/// Every call is emitted; collapsing a run of the same tool into "name ×N" is
+/// the consumer's job, because only the consumer can rewrite a line it already
+/// rendered. Suppressing here would have cost the count entirely.
+inline void emit_tool_progress(const QString& display_name, const QJsonObject& args) {
+ if (!t_progress_emitter)
+ return;
+ t_progress_emitter(tool_stream_prefix() + tool_progress_label(display_name, args) + QStringLiteral("\n"));
+}
+
// Active chat session id for the in-flight LLM request. Set by the chat screen
// before calling chat_streaming(), read by MCP tools (e.g. report_session_context)
// to scope per-chat state — for example, "did this chat session already start a
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index 7c99f2025..8a6730af0 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -205,7 +205,10 @@ void LlmService::ensure_config() const {
"Then call tool_describe(name) for the full input schema, then invoke it. "
"For requests with multiple intents (\"get news AND add to watchlist\"), "
"call tool_list MULTIPLE TIMES — once per intent. "
- "Never decline an action you can fulfil via a discoverable tool.";
+ "Never decline an action you can fulfil via a discoverable tool. "
+ "Discovery is not free: only reach for a tool when the request needs live data "
+ "or an action inside the terminal. Greetings, small talk, and questions you can "
+ "answer from your own knowledge get a direct plain-text reply and NO tool call.";
if (!sorted_cats.isEmpty()) {
hint += "\nAvailable tool categories: " + sorted_cats.join(", ") + ".";
}
@@ -1104,6 +1107,12 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,
resp.error = QString("HTTP %1").arg(status);
}
+ // On the timeout path we fall straight out of `loop.exec()` with the reply
+ // still streaming, and drain_nam() makes the delete synchronous — tearing
+ // the reply down from under Qt's HTTP machinery. Abort first, as the
+ // sibling helper does (LlmHttpHelpers.cpp:120). No-op when already finished.
+ if (!reply->isFinished())
+ reply->abort();
drain_nam();
if (!done)
diff --git a/fincept-qt/src/services/llm/LlmService.h b/fincept-qt/src/services/llm/LlmService.h
index a6557de32..5161c3e75 100644
--- a/fincept-qt/src/services/llm/LlmService.h
+++ b/fincept-qt/src/services/llm/LlmService.h
@@ -43,6 +43,18 @@ inline QString think_stream_prefix() {
return QStringLiteral("\x02__THINK__");
}
+/// In-band sentinel marking a chunk as tool-activity progress ("Finding tools · …")
+/// rather than answer text. Same mechanism as think_stream_prefix (\x02) and the
+/// \x01 __TOOL_CALL_CLEAR__ sentinel; \x03 so the three can't collide.
+///
+/// Tool progress used to be appended straight into the answer bubble, which mixed
+/// plumbing into the reply and — because the label carried no arguments — rendered
+/// six different `tool_describe` calls as six identical "• tool_describe" lines.
+/// The AI Chat tab now routes these into their own collapsible Tools card.
+inline QString tool_stream_prefix() {
+ return QStringLiteral("\x03__TOOL__");
+}
+
struct ConversationMessage {
QString role; // system | user | assistant
QString content;
@@ -55,6 +67,9 @@ struct LlmResponse {
int completion_tokens = 0;
int total_tokens = 0;
bool success = false;
+ /// Failure looks transient (upstream/model error, not a malformed request),
+ /// so the caller may resubmit the identical prompt once.
+ bool retryable = false;
};
/// (chunk_text, is_done) — invoked on a background thread.
@@ -221,8 +236,16 @@ class LlmService : public QObject {
static HttpResult eventloop_request(const QString& method, const QString& url, const QByteArray& body,
const QMap<QString, QString>& headers, int timeout_ms = 30000);
- /// POST /research/llm/async then poll /research/llm/status/{id}.
+ /// POST /research/llm/async then poll /research/llm/status/{id}. Runs a
+ /// multi-round tool loop — the endpoint takes a flat prompt, so each round's
+ /// assistant turn and tool results are appended to the prompt transcript.
LlmResponse fincept_async_request(const QString& user_message, const std::vector<ConversationMessage>& history);
+
+ /// One submit+poll cycle against /research/llm/async. Body is {prompt,
+ /// max_tokens} only — see the note in LlmFinceptAsync.cpp on why `tools` is
+ /// NOT sent. Structured tool_calls, if the backend ever returns any, land in
+ /// *out_tool_calls (may be null).
+ LlmResponse fincept_submit_poll(const QString& prompt, QJsonArray* out_tool_calls);
};
} // namespace fincept::ai_chat
diff --git a/fincept-qt/src/services/llm/LlmToolLoop.cpp b/fincept-qt/src/services/llm/LlmToolLoop.cpp
index a4d809c21..b13bca10d 100644
--- a/fincept-qt/src/services/llm/LlmToolLoop.cpp
+++ b/fincept-qt/src/services/llm/LlmToolLoop.cpp
@@ -98,7 +98,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
if (sep > 0)
display = display.mid(sep + 2);
display.replace(QStringLiteral("-dot-"), QStringLiteral("."));
- detail::emit_progress(QStringLiteral("• ") + display + QStringLiteral("\n"));
+ detail::emit_tool_progress(display, fa);
// allow_defer: this is the one call site that knows about the
// job_* tools, so it is the one allowed to receive a receipt
// instead of a result for a long-running tool.
@@ -235,161 +235,41 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
// ── Pattern 4: ```tool_call\n{"name":"...", "arguments":{...}}\n```
// ── Pattern 5: function_name(arg1, arg2) style calls embedded in text
- struct TextToolCall {
- QString name;
- QJsonObject args;
- };
- std::vector<TextToolCall> calls;
-
LOG_INFO(kLlmToolLoopTag,
"Checking for text-based tool calls in response (" + QString::number(content.length()) + " chars)");
- // --- Pattern 1: XML <tool_call> blocks (without namespace prefix) ---
- {
- static const QRegularExpression rx("<tool_call>\\s*(\\{[\\s\\S]*?\\})\\s*</tool_call>",
- QRegularExpression::MultilineOption |
- QRegularExpression::DotMatchesEverythingOption);
- auto it = rx.globalMatch(content);
- while (it.hasNext()) {
- auto m = it.next();
- auto doc = QJsonDocument::fromJson(m.captured(1).toUtf8());
- if (doc.isObject()) {
- QJsonObject obj = doc.object();
- QString name = obj["name"].toString();
- if (name.isEmpty())
- name = obj["function"].toString();
- QJsonObject args = obj["arguments"].toObject();
- if (args.isEmpty() && obj["arguments"].isString())
- args = QJsonDocument::fromJson(obj["arguments"].toString().toUtf8()).object();
- if (!name.isEmpty())
- calls.push_back({name, args});
- }
- }
- }
-
- // --- Pattern 2: <invoke name="..."> with <parameter> children or JSON body ---
- if (calls.empty()) {
- static const QRegularExpression rx_invoke("<invoke\\s+name=\"([^\"]+)\"[^>]*>([\\s\\S]*?)</invoke>",
- QRegularExpression::MultilineOption |
- QRegularExpression::DotMatchesEverythingOption);
- static const QRegularExpression rx_param("<parameter\\s+name=\"([^\"]+)\"[^>]*>([\\s\\S]*?)</parameter>",
- QRegularExpression::MultilineOption |
- QRegularExpression::DotMatchesEverythingOption);
-
- LOG_INFO(kLlmToolLoopTag, "Pattern 2: invoke regex valid=" + QString(rx_invoke.isValid() ? "yes" : "no"));
- auto dbg_match = rx_invoke.match(content);
- LOG_INFO(kLlmToolLoopTag, "Pattern 2: hasMatch=" + QString(dbg_match.hasMatch() ? "yes" : "no"));
-
- auto it = rx_invoke.globalMatch(content);
- while (it.hasNext()) {
- auto m = it.next();
- QString name = m.captured(1);
- QString body = m.captured(2).trimmed();
- QJsonObject args;
-
- // Try parsing <parameter> children first
- auto pit = rx_param.globalMatch(body);
- bool has_params = false;
- while (pit.hasNext()) {
- auto pm = pit.next();
- QString pname = pm.captured(1);
- QString pval = pm.captured(2).trimmed();
- has_params = true;
-
- // Try to parse value as JSON (for arrays/objects)
- auto pdoc = QJsonDocument::fromJson(pval.toUtf8());
- if (!pdoc.isNull()) {
- if (pdoc.isArray())
- args[pname] = pdoc.array();
- else if (pdoc.isObject())
- args[pname] = pdoc.object();
- else
- args[pname] = pval;
- } else {
- args[pname] = pval;
- }
- }
-
- // Fallback: try body as JSON object (no <parameter> tags)
- if (!has_params && !body.isEmpty()) {
- auto jdoc = QJsonDocument::fromJson(body.toUtf8());
- if (jdoc.isObject())
- args = jdoc.object();
- }
-
- if (!name.isEmpty())
- calls.push_back({name, args});
- }
- }
-
- // --- Pattern 3: minimax:tool_call ... /minimax:tool_call or similar ---
- if (calls.empty()) {
- static const QRegularExpression rx("(?:\\w+:)?tool_call\\s+([\\s\\S]*?)\\s*/(?:\\w+:)?tool_call",
- QRegularExpression::MultilineOption);
- auto it = rx.globalMatch(content);
- while (it.hasNext()) {
- auto m = it.next();
- QString body = m.captured(1).trimmed();
-
- // Try as JSON first
- auto doc = QJsonDocument::fromJson(body.toUtf8());
- if (doc.isObject()) {
- QJsonObject obj = doc.object();
- QString name = obj["name"].toString();
- if (name.isEmpty())
- name = obj["function"].toString();
- QJsonObject args = obj["arguments"].toObject();
- if (args.isEmpty() && obj["arguments"].isString())
- args = QJsonDocument::fromJson(obj["arguments"].toString().toUtf8()).object();
- if (!name.isEmpty()) {
- calls.push_back({name, args});
- continue;
- }
- }
-
- // Not JSON — treat as raw SQL/command from the model.
- // Look for an external tool that accepts a "query"/"sql"/"statement" param
- // (the user's case: model emits raw SQL inside minimax:tool_call tags).
- auto all_tools = mcp::McpService::instance().get_all_tools();
+ // Pattern matching lives in LlmContentExtractors (shared with the Fincept
+ // async path, which is prompt-injected and therefore always text-mode).
+ QStringList raw_blocks;
+ std::vector<TextToolCall> calls = extract_text_tool_calls(content, &raw_blocks);
+
+ // A `[ns:]tool_call` block whose body isn't JSON is a raw command (the case
+ // that motivated this: the model emitting bare SQL inside minimax tags).
+ // Map it onto the first external tool with a query/sql/statement parameter.
+ if (calls.empty() && !raw_blocks.isEmpty()) {
+ auto all_tools = mcp::McpService::instance().get_all_tools();
+ for (const auto& body : raw_blocks) {
for (const auto& tool : all_tools) {
if (tool.is_internal)
continue;
- QJsonObject schema = tool.input_schema;
- QJsonObject props = schema["properties"].toObject();
+ const QJsonObject props = tool.input_schema["properties"].toObject();
+ bool matched = false;
for (auto pit = props.constBegin(); pit != props.constEnd(); ++pit) {
- QString key = pit.key().toLower();
+ const QString key = pit.key().toLower();
if (key == "query" || key == "sql" || key == "statement") {
- QString fn_name =
- tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
QJsonObject args;
args[pit.key()] = body;
- calls.push_back({fn_name, args});
+ calls.push_back(
+ {tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name), args});
+ matched = true;
break;
}
}
- if (!calls.empty())
+ if (matched)
break;
}
- }
- }
-
- // --- Pattern 4: ```tool_call\n...\n``` code blocks ---
- if (calls.empty()) {
- static const QRegularExpression rx("```tool_call\\s*\\n([\\s\\S]*?)\\n\\s*```",
- QRegularExpression::MultilineOption);
- auto it = rx.globalMatch(content);
- while (it.hasNext()) {
- auto m = it.next();
- auto doc = QJsonDocument::fromJson(m.captured(1).trimmed().toUtf8());
- if (doc.isObject()) {
- QJsonObject obj = doc.object();
- QString name = obj["name"].toString();
- QJsonObject args = obj["arguments"].toObject();
- if (args.isEmpty() && obj["arguments"].isString())
- args = QJsonDocument::fromJson(obj["arguments"].toString().toUtf8()).object();
- if (!name.isEmpty())
- calls.push_back({name, args});
- }
+ if (!calls.empty())
+ break;
}
}
@@ -405,7 +285,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
int sep_disp = tc.name.indexOf(QStringLiteral("__"));
QString display = (sep_disp >= 0) ? tc.name.mid(sep_disp + 2) : tc.name;
display.replace(QStringLiteral("-dot-"), QStringLiteral("."));
- detail::emit_progress(QStringLiteral("Using `") + display + QStringLiteral("` …\n"));
+ detail::emit_tool_progress(display, tc.args);
auto tr = mcp::McpService::instance().execute_openai_function(tc.name, tc.args);
// Shaped rather than clipped at a byte offset. Two reasons: `.left(4000)`
@@ -479,21 +359,24 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
follow_body["max_tokens"] = resolved_max_tokens();
}
- // No tools in follow-up to prevent infinite loop
- auto fu = blocking_post(url, follow_body, headers);
- if (!fu.success) {
- // Even if follow-up fails, return the raw tool results
- resp.content = tool_results;
+ // Last-resort rendering when the summarisation turn can't be obtained.
+ // Raw tool JSON is NOT an answer — label it so the user can tell the
+ // difference, and log the reason instead of silently passing it off as one.
+ auto raw_fallback = [&](const QString& reason) -> LlmResponse {
+ LOG_WARN(kLlmToolLoopTag, "Text-tool follow-up unavailable (" + reason + ") — returning raw tool output");
+ resp.content = "*(could not summarise — " + reason + ". Raw tool output below.)*\n" + tool_results;
resp.success = true;
return resp;
- }
+ };
+
+ // No tools in follow-up to prevent infinite loop
+ auto fu = blocking_post(url, follow_body, headers);
+ if (!fu.success)
+ return raw_fallback(fu.error.isEmpty() ? QStringLiteral("follow-up request failed") : fu.error);
auto fu_doc = QJsonDocument::fromJson(fu.body);
- if (fu_doc.isNull()) {
- resp.content = tool_results;
- resp.success = true;
- return resp;
- }
+ if (fu_doc.isNull())
+ return raw_fallback(QStringLiteral("follow-up response was not JSON"));
QJsonObject fu_rj = fu_doc.object();
@@ -513,7 +396,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
}
if (resp.content.isEmpty())
- resp.content = tool_results; // fallback to raw results
+ return raw_fallback(QStringLiteral("follow-up returned no text"));
resp.success = true;
parse_usage(resp, fu_rj, provider_);
diff --git a/fincept-qt/src/services/maritime/MaritimeService.cpp b/fincept-qt/src/services/maritime/MaritimeService.cpp
index 4006bb634..532efb838 100644
--- a/fincept-qt/src/services/maritime/MaritimeService.cpp
+++ b/fincept-qt/src/services/maritime/MaritimeService.cpp
@@ -209,6 +209,15 @@ void MaritimeService::get_vessel_position(const QString& imo) {
return;
}
auto data = unwrap(result.value().object());
+ // A 2xx that carries no vessel object is a failure, not an empty
+ // result. Writing the empty object into CacheManager would pin a
+ // blank "vessel" for kVesselTtlSec, so every retry inside the TTL
+ // is served the failure from cache without touching the network.
+ if (!data.value(QStringLiteral("vessel")).isObject()) {
+ LOG_ERROR("Maritime", "Vessel position: no vessel in response for IMO " + imo_trimmed);
+ emit self->error_occurred("vessel_position", QStringLiteral("No vessel data returned"));
+ return;
+ }
auto vessel_obj = data["vessel"].toObject();
fincept::CacheManager::instance().put(
cache_key, QVariant(QString::fromUtf8(QJsonDocument(vessel_obj).toJson(QJsonDocument::Compact))),
diff --git a/fincept-qt/src/services/markets/MarketDataService.cpp b/fincept-qt/src/services/markets/MarketDataService.cpp
index 548f6a867..d78a470ea 100644
--- a/fincept-qt/src/services/markets/MarketDataService.cpp
+++ b/fincept-qt/src/services/markets/MarketDataService.cpp
@@ -788,11 +788,29 @@ void MarketDataService::fetch_sparklines(const QStringList& symbols, SparklineCa
void MarketDataService::load_name_cache() {
if (name_cache_loaded_)
return;
- name_cache_loaded_ = true;
- auto load = [](const char* key, QHash<QString, QString>& cache) {
+ // Retry backoff. The loaded flag used to be latched *before* the read, so a
+ // single transient DB error marked the cache "loaded but empty" forever and
+ // the next persist_name_cache() wrote that empty object over the user's
+ // full cache. It is now latched only on success — but this function sits on
+ // a hot path (currency_prefix() runs per row), so a failing read must not
+ // hammer SQLite or spam the log on every call.
+ static qint64 retry_after_ms = 0;
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ if (now < retry_after_ms)
+ return;
+
+ bool read_failed = false;
+ auto load = [&read_failed](const char* key, QHash<QString, QString>& cache) {
auto res = SettingsRepository::instance().get(key);
- if (!res.is_ok() || res.value().isEmpty())
+ if (res.is_err()) {
+ LOG_ERROR("MarketData", QString("settings read failed for '%1' — name cache stays unloaded and will not "
+ "be persisted: %2")
+ .arg(QString::fromLatin1(key), QString::fromStdString(res.error())));
+ read_failed = true;
+ return;
+ }
+ if (res.value().isEmpty())
return;
auto doc = QJsonDocument::fromJson(res.value().toUtf8());
if (!doc.isObject())
@@ -803,9 +821,20 @@ void MarketDataService::load_name_cache() {
};
load("market_symbol_names", name_cache_);
load("market_symbol_currencies", currency_cache_);
+
+ name_cache_loaded_ = !read_failed;
+ retry_after_ms = read_failed ? now + 30000 : 0;
}
void MarketDataService::persist_name_cache() {
+ if (!name_cache_loaded_) {
+ // Never write a cache we never successfully read — the in-memory hash
+ // holds only whatever this run happened to resolve, and set() is an
+ // INSERT OR REPLACE.
+ LOG_WARN("MarketData", "Skipping name-cache persist — the stored cache was never read successfully");
+ return;
+ }
+
auto dump = [](const QHash<QString, QString>& cache) {
QJsonObject obj;
for (auto it = cache.constBegin(); it != cache.constEnd(); ++it)
diff --git a/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp b/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp
index 86dc37375..17f41e955 100644
--- a/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/DiscordProvider.cpp
@@ -47,17 +47,19 @@ void DiscordProvider::send(const NotificationRequest& req, std::function<void(bo
body["embeds"] = embeds;
HttpClient::instance().post(webhook_url_, body, [cb](Result<QJsonDocument> res) {
- // Discord returns 204 No Content on success — HttpClient may return empty body
- if (res.is_err()) {
- const auto& err = res.error();
- // "HTTP_204" is a successful empty response
- if (err.find("HTTP_204") != std::string::npos || err.find("204") != std::string::npos)
- cb(true, {});
- else
- cb(false, QString::fromStdString(err));
- } else {
+ // Discord answers a successful webhook post with 204 No Content. That is
+ // not an error path: QNetworkReply reports NoError for 2xx, so a real 204
+ // arrives here as is_ok() with an empty document.
+ //
+ // There used to be a `err.find("204")` substring test here. Once HttpClient
+ // began appending the server's message to the error string, that matched any
+ // 4xx/5xx whose body merely contained "204" — a Retry-After value, a byte
+ // count, a snowflake fragment — and reported a rejected webhook as delivered.
+ // Never infer a status code by substring-searching an error message.
+ if (res.is_err())
+ cb(false, QString::fromStdString(res.error()));
+ else
cb(true, {});
- }
});
}
diff --git a/fincept-qt/src/services/notifications/providers/EmailProvider.cpp b/fincept-qt/src/services/notifications/providers/EmailProvider.cpp
index e7440b978..bcdcac98c 100644
--- a/fincept-qt/src/services/notifications/providers/EmailProvider.cpp
+++ b/fincept-qt/src/services/notifications/providers/EmailProvider.cpp
@@ -3,6 +3,7 @@
#include "network/http/HttpClient.h"
#include <QJsonObject>
+#include <QUrl>
namespace fincept::notifications {
@@ -24,17 +25,58 @@ void EmailProvider::save_fields(SettingsRepository& r, const QString& cat) {
r.set(cat + ".from_addr", from_addr_, cat);
}
+QString EmailProvider::build_endpoint() const {
+ const QString host = smtp_host_.trimmed();
+ if (host.isEmpty())
+ return {};
+
+ // A bare host:port (no scheme) gets https, not http. The old code used
+ // `startsWith("http")` — which also matched "https" but forced http:// on
+ // literally every other value, including a hostname beginning with "http".
+ const bool has_scheme = host.startsWith(QStringLiteral("http://"), Qt::CaseInsensitive) ||
+ host.startsWith(QStringLiteral("https://"), Qt::CaseInsensitive);
+ const QString candidate =
+ has_scheme ? host
+ : QStringLiteral("https://%1:%2/send").arg(host, smtp_port_.isEmpty() ? "587" : smtp_port_);
+
+ const QUrl url(candidate);
+ if (!url.isValid() || url.host().isEmpty())
+ return {};
+
+ if (url.scheme().compare(QStringLiteral("http"), Qt::CaseInsensitive) == 0) {
+ // Only tolerate cleartext when the relay is on this machine — there is
+ // no network hop for an attacker to sit on. Everything else is refused.
+ const QString h = url.host();
+ const bool is_loopback = h == QStringLiteral("127.0.0.1") || h == QStringLiteral("::1") ||
+ h == QStringLiteral("[::1]") ||
+ h.compare(QStringLiteral("localhost"), Qt::CaseInsensitive) == 0;
+ if (!is_loopback)
+ return {};
+ }
+ return candidate;
+}
+
void EmailProvider::send(const NotificationRequest& req, std::function<void(bool, QString)> cb) {
if (!is_configured()) {
cb(false, "Not configured");
return;
}
- // POST to the configured SMTP relay HTTP endpoint
+ // POST to the configured SMTP relay HTTP endpoint.
// Expected API: POST /send with JSON {to, from, subject, body, auth}
- const QString url = smtp_host_.startsWith("http")
- ? smtp_host_
- : QString("http://%1:%2/send").arg(smtp_host_, smtp_port_.isEmpty() ? "587" : smtp_port_);
+ //
+ // SECURITY: the request body carries the SMTP password in cleartext. It is
+ // stored encrypted at rest, so shipping it over plain http would be the one
+ // place in the tree where an external credential crosses the network
+ // unprotected. The scheme therefore defaults to https, and an explicit
+ // http:// host is rejected unless it is loopback (a relay running on the
+ // user's own machine, where there is no network to sniff).
+ const QString url = build_endpoint();
+ if (url.isEmpty()) {
+ cb(false, "Refusing to send the SMTP password over an unencrypted connection. "
+ "Use an https:// relay endpoint (or a relay on 127.0.0.1).");
+ return;
+ }
QJsonObject auth;
auth["user"] = smtp_user_;
diff --git a/fincept-qt/src/services/notifications/providers/EmailProvider.h b/fincept-qt/src/services/notifications/providers/EmailProvider.h
index ef284d0f5..5fdef02a2 100644
--- a/fincept-qt/src/services/notifications/providers/EmailProvider.h
+++ b/fincept-qt/src/services/notifications/providers/EmailProvider.h
@@ -15,6 +15,14 @@ class EmailProvider final : public BaseProvider {
void send(const NotificationRequest& req, std::function<void(bool, QString)> cb) override;
+ /// Resolve smtp_host_ into the relay URL to POST to.
+ ///
+ /// Defaults the scheme to https — the request body carries the SMTP
+ /// password in cleartext, so it must not travel over plain http. Returns an
+ /// empty string when the configured host would force an unencrypted
+ /// non-loopback connection, and the caller must then refuse to send.
+ QString build_endpoint() const;
+
protected:
void load_fields(SettingsRepository& r, const QString& cat) override;
void save_fields(SettingsRepository& r, const QString& cat) override;
diff --git a/fincept-qt/src/services/quantlib/QuantLibClient.cpp b/fincept-qt/src/services/quantlib/QuantLibClient.cpp
index 86d86a3dc..0bbd50e09 100644
--- a/fincept-qt/src/services/quantlib/QuantLibClient.cpp
+++ b/fincept-qt/src/services/quantlib/QuantLibClient.cpp
@@ -7,7 +7,6 @@
#include "core/logging/Logger.h"
#include "storage/cache/CacheManager.h"
-#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QNetworkAccessManager>
@@ -222,19 +221,9 @@ void QuantLibClient::call(const QString& endpoint, const QJsonObject& body, Quan
});
}
-// ── Sync call (MCP tool handlers only — never call from UI thread) ───────────
-
-mcp::ToolResult QuantLibClient::call_sync(const QString& endpoint, const QJsonObject& body) {
- mcp::ToolResult result = mcp::ToolResult::fail("Timeout");
-
- QEventLoop loop;
- call(endpoint, body, [&](mcp::ToolResult r) {
- result = std::move(r);
- loop.quit();
- });
- loop.exec();
-
- return result;
-}
+// NOTE: call_sync() used to live here. It had zero call sites and parked the
+// calling thread in an unbounded `loop.exec()` with no timeout — a permanent
+// UI-freeze hazard for whoever reached for it next. Deleted; use the
+// callback-based call() above. Its declaration in QuantLibClient.h can go too.
} // namespace fincept::services
diff --git a/fincept-qt/src/services/quantlib/QuantLibClient.h b/fincept-qt/src/services/quantlib/QuantLibClient.h
index 57fb9e9ff..d3578a415 100644
--- a/fincept-qt/src/services/quantlib/QuantLibClient.h
+++ b/fincept-qt/src/services/quantlib/QuantLibClient.h
@@ -24,8 +24,9 @@ class QuantLibClient : public QObject {
/// Async call — callback posted on Qt event loop (use from UI thread).
void call(const QString& endpoint, const QJsonObject& body, QuantLibCallback callback);
- /// Sync call — blocks via QEventLoop (use from MCP tool handlers only, never from UI thread).
- mcp::ToolResult call_sync(const QString& endpoint, const QJsonObject& body);
+ // call_sync() was removed: it had zero call sites and blocked on an unbounded
+ // QEventLoop, so any future caller would have inherited a hang with no timeout.
+ // Use call() and continue from the callback. See the note in QuantLibClient.cpp.
/// GET-only endpoints (no request body).
static bool is_get_endpoint(const QString& endpoint);
diff --git a/fincept-qt/src/services/sectors/SectorResolver.cpp b/fincept-qt/src/services/sectors/SectorResolver.cpp
index 1c897bd95..22d4f9dea 100644
--- a/fincept-qt/src/services/sectors/SectorResolver.cpp
+++ b/fincept-qt/src/services/sectors/SectorResolver.cpp
@@ -16,6 +16,12 @@ namespace {
constexpr qint64 kNegativeTtlSeconds = 7 * 24 * 3600; // 7 days
+// quote_type marker written for rows whose sector is a fallback placeholder
+// rather than a real upstream answer. Distinguishes them from a user override
+// (which uses "override") and from legacy rows (empty).
+const QString kUnresolvedMarker = QStringLiteral("unresolved");
+const QString kOverrideMarker = QStringLiteral("override");
+
// Symbols that look like TSX bare tickers (letters only, 1–4 chars, no dot).
// We try a `.TO` suffix first before giving up, since many Canadian holdings
// in imported portfolios arrive without the exchange suffix.
@@ -60,53 +66,67 @@ void SectorResolver::load_cache() {
if (!db_mgr.is_open())
return;
- QSqlQuery q(db_mgr.raw_db());
- if (!q.exec("SELECT symbol, sector, resolved_at FROM sector_cache")) {
- LOG_WARN("SectorResolver", "Cache load failed: " + q.lastError().text());
+ // Route through Database::execute() — it hands back the CALLING thread's
+ // connection. raw_db() is the main-thread connection object, and this runs
+ // from the singleton ctor, i.e. on whichever thread touches the resolver
+ // first (see the rule documented in storage/secure/SecureStorage.cpp).
+ auto r = db_mgr.execute("SELECT symbol, sector, quote_type, resolved_at FROM sector_cache");
+ if (r.is_err()) {
+ LOG_WARN("SectorResolver", "Cache load failed: " + QString::fromStdString(r.error()));
return;
}
+ auto& q = r.value();
QMutexLocker lock(&mutex_);
- qint64 now = QDateTime::currentSecsSinceEpoch();
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
int loaded = 0;
+ int negatives = 0;
while (q.next()) {
- QString sym = q.value(0).toString();
- QString sec = q.value(1).toString();
- qint64 resolved = q.value(2).toLongLong();
-
- // Drop stale negative cache entries (sector == Unclassified/empty and
- // older than TTL) so we retry on next access.
- bool is_negative = sec.isEmpty() || sec == "Unclassified";
- if (is_negative && (now - resolved) > kNegativeTtlSeconds)
+ const QString sym = q.value(0).toString();
+ const QString sec = q.value(1).toString();
+ const QString quote_type = q.value(2).toString();
+ const qint64 resolved = q.value(3).toLongLong();
+ if (sym.isEmpty())
continue;
- if (!sec.isEmpty()) {
- cache_.insert(sym, sec);
- ++loaded;
- }
+ // A row is "negative" when its sector is a placeholder rather than an
+ // upstream answer. New rows say so explicitly via quote_type; legacy
+ // rows are detected by comparing against what the fallback would have
+ // produced for that symbol — this is what catches the old "Cash"
+ // entries written for TDB* codes, which the string-equality check
+ // against "Unclassified" missed and therefore never expired.
+ const bool negative =
+ quote_type != kOverrideMarker && (quote_type == kUnresolvedMarker || sec.isEmpty() ||
+ sec == fallback_for_unresolvable(sym) || sec == "Unclassified");
+
+ if (negative && (now - resolved) > kNegativeTtlSeconds)
+ continue; // expired placeholder — drop it so the next access retries
+ if (sec.isEmpty())
+ continue;
+
+ cache_.insert(sym, Entry{sec, resolved, negative});
+ ++loaded;
+ if (negative)
+ ++negatives;
}
- LOG_INFO("SectorResolver", QString("Loaded %1 sector cache entries").arg(loaded));
+ LOG_INFO("SectorResolver",
+ QString("Loaded %1 sector cache entries (%2 unresolved placeholders)").arg(loaded).arg(negatives));
}
void SectorResolver::persist(const QString& symbol, const QString& sector, const QString& industry,
- const QString& quote_type) {
+ const QString& quote_type, qint64 resolved_at) {
auto& db_mgr = fincept::Database::instance();
if (!db_mgr.is_open())
return;
- QSqlQuery q(db_mgr.raw_db());
- q.prepare("INSERT INTO sector_cache (symbol, sector, industry, quote_type, resolved_at) "
- "VALUES (?, ?, ?, ?, ?) "
- "ON CONFLICT(symbol) DO UPDATE SET "
- "sector=excluded.sector, industry=excluded.industry, "
- "quote_type=excluded.quote_type, resolved_at=excluded.resolved_at");
- q.addBindValue(symbol);
- q.addBindValue(sector);
- q.addBindValue(industry);
- q.addBindValue(quote_type);
- q.addBindValue(QDateTime::currentSecsSinceEpoch());
- if (!q.exec())
- LOG_WARN("SectorResolver", "Cache write failed: " + q.lastError().text());
+ auto r = db_mgr.execute("INSERT INTO sector_cache (symbol, sector, industry, quote_type, resolved_at) "
+ "VALUES (?, ?, ?, ?, ?) "
+ "ON CONFLICT(symbol) DO UPDATE SET "
+ "sector=excluded.sector, industry=excluded.industry, "
+ "quote_type=excluded.quote_type, resolved_at=excluded.resolved_at",
+ {symbol, sector, industry, quote_type, resolved_at});
+ if (r.is_err())
+ LOG_WARN("SectorResolver", "Cache write failed: " + QString::fromStdString(r.error()));
}
void SectorResolver::remember(const QString& symbol, const QString& sector) {
@@ -115,11 +135,12 @@ void SectorResolver::remember(const QString& symbol, const QString& sector) {
if (sym.isEmpty() || sec.isEmpty())
return;
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
{
QMutexLocker lock(&mutex_);
- cache_.insert(sym, sec);
+ cache_.insert(sym, Entry{sec, now, /*negative=*/false});
}
- persist(sym, sec, {}, "override");
+ persist(sym, sec, {}, kOverrideMarker, now);
emit sector_resolved(sym, sec);
}
@@ -129,9 +150,16 @@ QString SectorResolver::sector_for(const QString& symbol) {
return {};
QMutexLocker lock(&mutex_);
- auto it = cache_.constFind(sym);
- if (it != cache_.constEnd())
- return it.value();
+ auto it = cache_.find(sym);
+ if (it != cache_.end()) {
+ if (!it->negative)
+ return it->sector;
+ // Placeholder: honour the negative TTL HERE, not only at load. A session
+ // that outlives the TTL used to serve the stale placeholder forever.
+ if ((QDateTime::currentSecsSinceEpoch() - it->resolved_at) <= kNegativeTtlSeconds)
+ return it->sector;
+ cache_.erase(it); // expired — fall through and retry
+ }
if (!inflight_.contains(sym)) {
inflight_.insert(sym);
@@ -149,44 +177,73 @@ void SectorResolver::prefetch(const QStringList& symbols) {
void SectorResolver::resolve_async(const QString& symbol) {
QPointer<SectorResolver> self = this;
+ // Reached ONLY when the upstream lookup actually completed. An empty sector
+ // here is a real answer ("this instrument has no sector") and is cached as a
+ // TTL'd placeholder. A fetch FAILURE never reaches this lambda — see give_up.
auto finish = [self, symbol](QString sector, QString industry, QString quote_type) {
if (!self)
return;
QString final_sector = sector.trimmed();
- if (final_sector.isEmpty() || final_sector == "N/A") {
- // yfinance didn't resolve — use a graceful fallback.
+ const bool negative = final_sector.isEmpty() || final_sector == "N/A";
+ if (negative)
final_sector = SectorResolver::fallback_for_unresolvable(symbol);
- }
+
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
{
QMutexLocker lock(&self->mutex_);
- self->cache_.insert(symbol, final_sector);
+ self->cache_.insert(symbol, Entry{final_sector, now, negative});
self->inflight_.remove(symbol);
}
- self->persist(symbol, final_sector, industry, quote_type);
+ self->persist(symbol, final_sector, industry, negative ? kUnresolvedMarker : quote_type, now);
emit self->sector_resolved(symbol, final_sector);
};
+ // The fetch FAILED (script crash, network error, rate limit). Release the
+ // in-flight slot and touch NOTHING else: caching a transport failure as a
+ // sector persists a wrong answer that outlives the outage.
+ auto give_up = [self, symbol](const char* reason) {
+ if (!self)
+ return;
+ {
+ QMutexLocker lock(&self->mutex_);
+ self->inflight_.remove(symbol);
+ }
+ LOG_DEBUG("SectorResolver", QString("Lookup failed for %1 (%2) — not cached, will retry")
+ .arg(symbol, QString::fromLatin1(reason)));
+ };
+
// Try 1: as-is.
- MarketDataService::instance().fetch_info(symbol, [self, symbol, finish](bool ok, InfoData info) {
+ MarketDataService::instance().fetch_info(symbol, [self, symbol, finish, give_up](bool ok, InfoData info) {
if (!self)
return;
- QString sector = info.sector.trimmed();
- bool resolved = ok && !sector.isEmpty() && sector != "N/A";
- if (resolved) {
+ const QString sector = info.sector.trimmed();
+ if (ok && !sector.isEmpty() && sector != "N/A") {
finish(sector, info.industry, {});
return;
}
- // Try 2: TSX suffix fallback for bare Canadian tickers.
+ // Try 2: TSX suffix fallback for bare Canadian tickers. Worth doing even
+ // when try 1 errored — a bare TSX ticker often 404s before it resolves.
if (looks_like_canadian_bare(symbol)) {
- QString tsx_symbol = symbol + ".TO";
- MarketDataService::instance().fetch_info(tsx_symbol, [self, symbol, finish](bool ok2, InfoData info2) {
+ const QString tsx_symbol = symbol + ".TO";
+ // `finish` / `give_up` already carry `symbol`, so it is not captured again.
+ MarketDataService::instance().fetch_info(tsx_symbol, [self, finish, give_up](bool ok2, InfoData info2) {
if (!self)
return;
- finish(ok2 ? info2.sector : QString{}, info2.industry, {});
+ if (!ok2) {
+ give_up("both bare and .TO lookups failed");
+ return;
+ }
+ finish(info2.sector, info2.industry, {});
});
return;
}
+
+ if (!ok) {
+ give_up("fetch_info reported failure");
+ return;
+ }
+ // Fetch succeeded but the instrument genuinely carries no sector.
finish({}, info.industry, {});
});
}
diff --git a/fincept-qt/src/services/sectors/SectorResolver.h b/fincept-qt/src/services/sectors/SectorResolver.h
index c2f1bc161..d1e60f7f1 100644
--- a/fincept-qt/src/services/sectors/SectorResolver.h
+++ b/fincept-qt/src/services/sectors/SectorResolver.h
@@ -8,9 +8,17 @@
// suffix for Canadian TSX symbols that didn't resolve bare.
// 4. Persistent fallback "Unclassified".
//
-// Negative hits (yfinance returns N/A or request fails) are cached with a
-// 7-day TTL so we don't hammer the script every launch for tickers that
-// genuinely don't have a sector (mutual funds, cash, obscure ETFs).
+// Negative hits — yfinance ANSWERED but the instrument genuinely has no sector
+// (mutual funds, cash, obscure ETFs) — are cached with an explicit `negative`
+// flag and a 7-day TTL, checked both at load and on every sector_for() hit.
+//
+// A FETCH FAILURE is not a negative hit and is never cached. Previously the
+// completion path ran on success and failure alike, so a transient script/
+// network error was persisted as if it were data: the symbol resolved to
+// "Unclassified" (or "Cash" for TDB* codes) and, because the TTL was only
+// consulted at construction and only matched the literal string
+// "Unclassified", the wrong answer survived for the whole session and — for
+// the "Cash" case — forever.
//
// The resolver is sync-for-cache-hits and async-for-misses. Consumers should
// either:
@@ -53,15 +61,25 @@ class SectorResolver : public QObject {
SectorResolver(const SectorResolver&) = delete;
SectorResolver& operator=(const SectorResolver&) = delete;
+ /// One resolved symbol. `negative` marks a placeholder produced by
+ /// fallback_for_unresolvable() rather than a real upstream answer, so
+ /// sector_for() can expire it after kNegativeTtlSeconds and retry.
+ struct Entry {
+ QString sector;
+ qint64 resolved_at = 0;
+ bool negative = false;
+ };
+
void load_cache();
- void persist(const QString& symbol, const QString& sector, const QString& industry, const QString& quote_type);
+ void persist(const QString& symbol, const QString& sector, const QString& industry, const QString& quote_type,
+ qint64 resolved_at);
void resolve_async(const QString& symbol);
static QString normalize(const QString& symbol);
static QString fallback_for_unresolvable(const QString& symbol);
mutable QMutex mutex_;
- QHash<QString, QString> cache_; // symbol → sector
- QSet<QString> inflight_; // symbols currently being fetched
+ QHash<QString, Entry> cache_; // symbol → resolved sector + provenance
+ QSet<QString> inflight_; // symbols currently being fetched
};
} // namespace fincept::services
diff --git a/fincept-qt/src/services/stt/SpeechService.cpp b/fincept-qt/src/services/stt/SpeechService.cpp
index 5f326f6ac..3fde3f485 100644
--- a/fincept-qt/src/services/stt/SpeechService.cpp
+++ b/fincept-qt/src/services/stt/SpeechService.cpp
@@ -29,7 +29,6 @@
namespace fincept::services {
static constexpr auto TAG = "SpeechService";
-static constexpr int kShutdownTimeoutMs = 2000;
// ── PythonSttProvider (base) ─────────────────────────────────────────────────
//
@@ -141,15 +140,23 @@ class PythonSttProvider : public SttProvider {
if (!process_)
return;
- disconnect(process_, nullptr, this, nullptr);
-
- if (process_->state() != QProcess::NotRunning) {
- process_->kill();
- process_->waitForFinished(kShutdownTimeoutMs);
- }
- process_->deleteLater();
+ // Fire-and-forget teardown (§P1) — stop() is UI-reachable (mic toggle,
+ // fatal-event handler, reload_config), so no waitForFinished here.
+ // Detaching FIRST means the eventual exit cannot re-enter
+ // on_process_finished and emit a second active_changed(false); letting
+ // the child reap itself on `finished` avoids ~QProcess's own blocking
+ // waitForFinished() on a still-Running handle.
+ QProcess* dying = process_;
process_ = nullptr;
stdout_buffer_.clear();
+ disconnect(dying, nullptr, this, nullptr);
+ if (dying->state() == QProcess::NotRunning) {
+ dying->deleteLater();
+ } else {
+ connect(dying, &QProcess::finished, dying, &QObject::deleteLater);
+ connect(dying, &QProcess::errorOccurred, dying, &QObject::deleteLater);
+ dying->kill();
+ }
const bool was_active = active_.exchange(false, std::memory_order_acq_rel);
if (was_active) {
diff --git a/fincept-qt/src/services/tts/TtsService.cpp b/fincept-qt/src/services/tts/TtsService.cpp
index 713f81468..cc860ee8b 100644
--- a/fincept-qt/src/services/tts/TtsService.cpp
+++ b/fincept-qt/src/services/tts/TtsService.cpp
@@ -26,7 +26,6 @@ namespace fincept::services {
// SpeechService's identically-named constants.
namespace {
constexpr auto TTS_TAG = "TtsService";
-constexpr int kTtsShutdownTimeoutMs = 1500;
} // namespace
// ── PythonTtsProvider (base) ─────────────────────────────────────────────────
@@ -111,11 +110,28 @@ class PythonTtsProvider : public TtsProvider {
connect(process_, &QProcess::readyReadStandardOutput, this, &PythonTtsProvider::on_stdout_ready);
connect(process_, &QProcess::readyReadStandardError, this, &PythonTtsProvider::on_stderr_ready);
- connect(process_, &QProcess::started, this, [this]() {
- LOG_INFO(TTS_TAG, QString("Provider[%1]: QProcess::started — pid=%2")
- .arg(name())
- .arg(process_ ? process_->processId() : 0));
- });
+ // The utterance is piped on stdin from the `started` signal rather than
+ // after a blocking waitForStarted(). speak() is reached straight from the
+ // AI-chat `finished_streaming` handler, i.e. the pure UI thread, so any
+ // wait here freezes the terminal for the whole Python launch (§P1).
+ // `proc` is captured by value so a newer speak() swapping process_ out
+ // from under us can never misroute this write; `this` as the context
+ // object keeps the connection scoped to the provider's lifetime, and
+ // stop() disconnects before tearing the child down.
+ {
+ QProcess* proc = process_;
+ const QByteArray payload = text.toUtf8();
+ connect(process_, &QProcess::started, this, [this, proc, payload]() {
+ LOG_INFO(TTS_TAG,
+ QString("Provider[%1]: QProcess::started — pid=%2").arg(name()).arg(proc->processId()));
+ const qint64 written = proc->write(payload);
+ proc->closeWriteChannel();
+ LOG_INFO(TTS_TAG, QString("Provider[%1]: wrote %2/%3 bytes to stdin")
+ .arg(name())
+ .arg(written)
+ .arg(payload.size()));
+ });
+ }
connect(process_, &QProcess::finished, this, &PythonTtsProvider::on_process_finished);
connect(process_, &QProcess::errorOccurred, this, [this](QProcess::ProcessError err) {
LOG_ERROR(TTS_TAG,
@@ -129,35 +145,32 @@ class PythonTtsProvider : public TtsProvider {
stdout_buffer_.clear();
LOG_INFO(TTS_TAG,
QString("Provider[%1]: launching '%2' '%3' (cwd='%4')").arg(name(), python_exe, script, scripts_dir));
+ // Fire-and-forget: a failed launch arrives as errorOccurred(FailedToStart),
+ // which already emits error_occurred() and calls stop().
process_->start(python_exe, {script});
-
- if (!process_->waitForStarted(2000)) {
- LOG_ERROR(TTS_TAG, "TTS process did not start within 2 s");
- emit error_occurred(QStringLiteral("TTS process failed to start"));
- stop();
- return;
- }
-
- // Pipe text on stdin and close so the child sees EOF.
- const QByteArray payload = text.toUtf8();
- const qint64 written = process_->write(payload);
- process_->closeWriteChannel();
- LOG_INFO(TTS_TAG,
- QString("Provider[%1]: wrote %2/%3 bytes to stdin").arg(name()).arg(written).arg(payload.size()));
}
void stop() override {
if (!process_)
return;
- disconnect(process_, nullptr, this, nullptr);
- if (process_->state() != QProcess::NotRunning) {
- process_->kill();
- process_->waitForFinished(kTtsShutdownTimeoutMs);
- }
- process_->deleteLater();
+ // Fire-and-forget teardown (§P1) — no waitForFinished on the UI thread.
+ // Detach the child from us FIRST so its eventual exit cannot re-enter
+ // on_process_finished and emit a second speaking_finished, then let it
+ // reap itself once the OS reports the exit. A bare deleteLater() would
+ // risk ~QProcess seeing a still-Running state, and that destructor does
+ // its own blocking waitForFinished() — the very thing we're removing.
+ QProcess* dying = process_;
process_ = nullptr;
stdout_buffer_.clear();
+ disconnect(dying, nullptr, this, nullptr);
+ if (dying->state() == QProcess::NotRunning) {
+ dying->deleteLater();
+ } else {
+ connect(dying, &QProcess::finished, dying, &QObject::deleteLater);
+ connect(dying, &QProcess::errorOccurred, dying, &QObject::deleteLater);
+ dying->kill();
+ }
const bool was_active = active_.exchange(false, std::memory_order_acq_rel);
if (was_active) {
diff --git a/fincept-qt/src/services/updater/UpdateService.cpp b/fincept-qt/src/services/updater/UpdateService.cpp
index aa4230033..b4ffc06eb 100644
--- a/fincept-qt/src/services/updater/UpdateService.cpp
+++ b/fincept-qt/src/services/updater/UpdateService.cpp
@@ -1,9 +1,11 @@
#include "services/updater/UpdateService.h"
#include "core/logging/Logger.h"
+#include "services/wallet/Ed25519Verifier.h"
#include <QAbstractButton>
#include <QApplication>
+#include <QByteArray>
#include <QCryptographicHash>
#include <QDesktopServices>
#include <QDir>
@@ -23,6 +25,51 @@
namespace fincept::services {
+// ── Update-manifest signing: OFFLINE RUNBOOK ─────────────────────────────────
+//
+// The manifest is only trusted if it carries a valid detached Ed25519
+// signature made with a key that never enters the repository or CI. Generate
+// the keypair ONCE, on an offline / trusted machine, and keep the private key
+// off every build machine.
+//
+// # 1. Generate the keypair (OpenSSL 3.x).
+// openssl genpkey -algorithm ed25519 -out fincept-update-signing.key
+// chmod 600 fincept-update-signing.key
+//
+// # 2. Extract the RAW 32-byte public key as hex. The DER SubjectPublicKeyInfo
+// # for Ed25519 is a fixed 12-byte prefix + the 32 key bytes, so the last
+// # 32 bytes are exactly what UPDATE_SIGNING_PUBLIC_KEY_HEX wants.
+// openssl pkey -in fincept-update-signing.key -pubout -outform DER \
+// | tail -c 32 | xxd -p -c 32
+//
+// # 3. Paste that 64-hex-character string into
+// # UPDATE_SIGNING_PUBLIC_KEY_HEX in UpdateService.h and ship the build.
+//
+// # 4. For EVERY release, after updates.json is final, sign it and commit the
+// # signature next to it. Ed25519 signs the message directly (-rawin);
+// # there is no pre-hash step and `openssl dgst -sign` is NOT equivalent.
+// openssl pkeyutl -sign -rawin -inkey fincept-update-signing.key \
+// -in updates.json -out updates.json.sig.bin
+// base64 -w0 updates.json.sig.bin > updates.json.sig
+//
+// # 5. Verify locally before pushing.
+// base64 -d updates.json.sig > /tmp/sig.bin
+// openssl pkeyutl -verify -rawin -pubin \
+// -inkey <(openssl pkey -in fincept-update-signing.key -pubout) \
+// -in updates.json -sigfile /tmp/sig.bin
+//
+// # 6. Commit BOTH files together. updates.json.sig must sit beside
+// # updates.json at the same URL + ".sig".
+//
+// The signature covers the manifest bytes EXACTLY as served. Any reformatting,
+// trailing-newline change, or CRLF conversion after signing invalidates it —
+// sign the exact file you commit, and make sure .gitattributes does not
+// normalise line endings for updates.json.
+//
+// Key rotation: ship a build carrying the NEW public key first, wait for it to
+// propagate, then start signing with the new private key. A client only ever
+// trusts the single key compiled into it.
+
UpdateService& UpdateService::instance() {
static UpdateService inst;
return inst;
@@ -143,7 +190,24 @@ void UpdateService::check_for_updates(bool silent) {
return;
}
+ // Fail closed: without a pinned signing key we cannot tell an authentic
+ // manifest from one pushed by whoever last compromised the repo, and the
+ // installer we would fetch is auto-launched. Refuse rather than proceed
+ // unsigned. See the signing runbook at the top of this file.
+ if (signing_public_key().isEmpty()) {
+ LOG_ERROR("UpdateService", "AUTO-UPDATE DISABLED — no update-signing public key is pinned in this build. "
+ "Set UpdateService::UPDATE_SIGNING_PUBLIC_KEY_HEX and sign updates.json (see the "
+ "runbook in UpdateService.cpp) before shipping auto-update.");
+ if (!silent_) {
+ show_error(QStringLiteral("Auto-update is disabled in this build because no update-signing key is "
+ "configured.\n\nPlease download updates from the releases page."));
+ }
+ emit check_finished(false);
+ return;
+ }
+
in_progress_ = true;
+ pending_manifest_body_.clear();
LOG_INFO("UpdateService", QString("Checking for updates — platform=%1, local=%2, manifest=%3")
.arg(platform_key, local_version, manifest_url_));
@@ -155,6 +219,52 @@ void UpdateService::check_for_updates(bool silent) {
connect(reply, &QNetworkReply::finished, this, &UpdateService::on_manifest_reply_finished);
}
+// ── Manifest signature ──────────────────────────────────────────────────────
+
+QByteArray UpdateService::signing_public_key() {
+ const QByteArray hex =
+ QByteArray::fromRawData(UPDATE_SIGNING_PUBLIC_KEY_HEX,
+ static_cast<qsizetype>(qstrlen(UPDATE_SIGNING_PUBLIC_KEY_HEX)))
+ .trimmed();
+ if (hex.isEmpty())
+ return {};
+ const QByteArray raw = QByteArray::fromHex(hex);
+ if (raw.size() != 32) {
+ LOG_ERROR("UpdateService", QString("UPDATE_SIGNING_PUBLIC_KEY_HEX is malformed (%1 bytes after hex decode, "
+ "expected 32) — auto-update stays disabled")
+ .arg(raw.size()));
+ return {};
+ }
+ return raw;
+}
+
+bool UpdateService::verify_manifest_signature(const QByteArray& manifest, const QByteArray& signature) {
+ const QByteArray pubkey = signing_public_key();
+ if (pubkey.isEmpty())
+ return false; // fail closed — never "no key means no check"
+
+ // Accept the signature as base64 (what the runbook produces) or as hex.
+ const QByteArray trimmed = signature.trimmed();
+ QByteArray raw_sig;
+ if (trimmed.size() == 128) {
+ raw_sig = QByteArray::fromHex(trimmed);
+ }
+ if (raw_sig.size() != 64) {
+ raw_sig = QByteArray::fromBase64(trimmed, QByteArray::AbortOnBase64DecodingErrors);
+ }
+ if (raw_sig.size() != 64) {
+ LOG_ERROR("UpdateService",
+ QString("Update signature is not 64 bytes (got %1) — rejecting manifest").arg(raw_sig.size()));
+ return false;
+ }
+
+ // Ed25519Verifier is already linked (orlp/ed25519, used by the wallet
+ // connect handshake). Its API speaks base58, so re-encode both blobs.
+ const QString pubkey_b58 = wallet::Ed25519Verifier::encode_base58(pubkey);
+ const QString sig_b58 = wallet::Ed25519Verifier::encode_base58(raw_sig);
+ return wallet::Ed25519Verifier::verify(pubkey_b58, manifest, sig_b58);
+}
+
// ── Manifest response ───────────────────────────────────────────────────────
void UpdateService::on_manifest_reply_finished() {
@@ -172,7 +282,59 @@ void UpdateService::on_manifest_reply_finished() {
return;
}
- const QByteArray body = reply->readAll();
+ // Hold the raw bytes and fetch the detached signature. NOTHING in the
+ // manifest is read — not even the version — until the signature verifies.
+ pending_manifest_body_ = reply->readAll();
+
+ const QString sig_url = manifest_url_ + QStringLiteral(".sig");
+ LOG_DEBUG("UpdateService", QString("Fetching manifest signature: %1").arg(sig_url));
+ QNetworkRequest sig_req{QUrl(sig_url)};
+ sig_req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
+ sig_req.setHeader(QNetworkRequest::UserAgentHeader,
+ QString("FinceptTerminal/%1").arg(QApplication::applicationVersion()));
+ QNetworkReply* sig_reply = net_.get(sig_req);
+ connect(sig_reply, &QNetworkReply::finished, this, &UpdateService::on_signature_reply_finished);
+}
+
+void UpdateService::on_signature_reply_finished() {
+ auto* reply = qobject_cast<QNetworkReply*>(sender());
+ if (!reply)
+ return;
+ reply->deleteLater();
+
+ const QByteArray manifest = pending_manifest_body_;
+ pending_manifest_body_.clear();
+
+ if (reply->error() != QNetworkReply::NoError) {
+ // A missing or unreachable signature is a hard failure, not a reason to
+ // fall back to the unsigned path. Downgrade-to-unsigned is exactly what
+ // an attacker who can serve the manifest would arrange.
+ LOG_ERROR("UpdateService", QString("Update manifest signature could not be fetched (%1) — refusing to apply "
+ "an unverified update")
+ .arg(reply->errorString()));
+ if (!silent_)
+ show_error(QStringLiteral("This update could not be authenticated (its signature is missing). "
+ "Nothing has been downloaded."));
+ finish_check(false);
+ return;
+ }
+
+ const QByteArray signature = reply->readAll();
+ if (manifest.isEmpty() || !verify_manifest_signature(manifest, signature)) {
+ LOG_ERROR("UpdateService", "Update manifest FAILED signature verification — refusing to apply. The manifest "
+ "was not produced by the holder of the pinned signing key.");
+ if (!silent_)
+ show_error(QStringLiteral("This update failed authenticity verification and has been rejected. "
+ "Nothing has been downloaded."));
+ finish_check(false);
+ return;
+ }
+
+ LOG_INFO("UpdateService", "Update manifest signature verified");
+ process_verified_manifest(manifest);
+}
+
+void UpdateService::process_verified_manifest(const QByteArray& body) {
QJsonParseError parse_err{};
const QJsonDocument doc = QJsonDocument::fromJson(body, &parse_err);
if (parse_err.error != QJsonParseError::NoError || !doc.isObject()) {
@@ -384,6 +546,15 @@ void UpdateService::on_download_reply_finished() {
void UpdateService::launch_installer(const QString& path) {
LOG_INFO("UpdateService", QString("Launching installer: %1").arg(path));
+ // TODO(security, needs build change): on Windows, verify the installer's
+ // Authenticode signature here — before startDetached — via WinVerifyTrust
+ // with WINTRUST_ACTION_GENERIC_VERIFY_V2 over a WINTRUST_FILE_INFO, and
+ // abort on anything other than ERROR_SUCCESS. That needs `wintrust` (and
+ // `crypt32`, already linked) added to target_link_libraries in
+ // CMakeLists.txt, so it is deliberately not done inline here. It is a
+ // second, independent gate: the manifest signature proves who chose the
+ // installer, Authenticode proves who built it.
+
#ifdef Q_OS_LINUX
// Linux installers (.run) need the executable bit set before they can be
// launched. QDesktopServices::openUrl on a non-executable .run just hands
diff --git a/fincept-qt/src/services/updater/UpdateService.h b/fincept-qt/src/services/updater/UpdateService.h
index dbfeaf941..77381820a 100644
--- a/fincept-qt/src/services/updater/UpdateService.h
+++ b/fincept-qt/src/services/updater/UpdateService.h
@@ -1,5 +1,6 @@
#pragma once
+#include <QByteArray>
#include <QNetworkAccessManager>
#include <QObject>
#include <QPointer>
@@ -48,6 +49,7 @@ class UpdateService : public QObject {
QString changelog() const { return changelog_; }
/// Override the manifest URL (default: GitHub raw updates.json).
+ /// The detached signature is always fetched from `<manifest_url> + ".sig"`.
void set_manifest_url(const QString& url) { manifest_url_ = url; }
/// Parent widget for dialogs (defaults to QApplication::activeWindow()).
@@ -62,12 +64,26 @@ class UpdateService : public QObject {
private slots:
void on_manifest_reply_finished();
+ void on_signature_reply_finished();
void on_download_reply_finished();
void on_download_progress(qint64 received, qint64 total);
private:
explicit UpdateService(QObject* parent = nullptr);
+ /// Parse + act on a manifest whose detached signature has already been
+ /// verified. Never call this with unverified bytes.
+ void process_verified_manifest(const QByteArray& body);
+
+ /// True iff `signature` (base64 or hex, 64 raw bytes) is a valid Ed25519
+ /// signature over `manifest` under UPDATE_SIGNING_PUBLIC_KEY_HEX.
+ static bool verify_manifest_signature(const QByteArray& manifest, const QByteArray& signature);
+
+ /// Raw 32-byte signing public key, or an empty QByteArray when no key is
+ /// pinned (or the pinned value is malformed) — in which case auto-update is
+ /// refused outright.
+ static QByteArray signing_public_key();
+
/// Return the lookup key for the current runtime (e.g. "windows-x64").
/// Returns empty string if the platform/arch combination isn't supported.
static QString current_platform_key();
@@ -90,7 +106,28 @@ class UpdateService : public QObject {
static constexpr const char* DEFAULT_MANIFEST_URL =
"https://raw.githubusercontent.com/Fincept-Corporation/FinceptTerminal/main/updates.json";
+ // ── Update-manifest signing key ─────────────────────────────────────────
+ // Raw Ed25519 public key, 32 bytes as 64 lowercase hex characters.
+ //
+ // WHY: `download-url` and `sha256` both come out of the same updates.json
+ // on raw.githubusercontent.com. The sha256 check proves the installer
+ // matches what the manifest claimed — it says nothing about whether the
+ // manifest is ours. Anyone who can push to `main`, or who takes over that
+ // account, otherwise gets code execution on every installation at next
+ // launch, because the verified installer is auto-launched via
+ // startDetached and silent checks fire at startup.
+ //
+ // A detached signature over the manifest bytes fixes that: the private key
+ // never touches CI or the repo, so a repo compromise alone cannot produce a
+ // manifest this binary will accept.
+ //
+ // EMPTY = auto-update is DISABLED (fail closed). See the signing runbook in
+ // UpdateService.cpp for how to generate the keypair and produce
+ // updates.json.sig.
+ static constexpr const char* UPDATE_SIGNING_PUBLIC_KEY_HEX = "";
+
QNetworkAccessManager net_;
+ QByteArray pending_manifest_body_;
QString manifest_url_ = DEFAULT_MANIFEST_URL;
QString latest_version_;
QString changelog_;
diff --git a/fincept-qt/src/services/voice_trigger/ClapDetectorService.cpp b/fincept-qt/src/services/voice_trigger/ClapDetectorService.cpp
index d0e830042..b70eff1a2 100644
--- a/fincept-qt/src/services/voice_trigger/ClapDetectorService.cpp
+++ b/fincept-qt/src/services/voice_trigger/ClapDetectorService.cpp
@@ -22,7 +22,6 @@ namespace {
// Anon-namespaced + uniquely-prefixed to avoid the unity-build symbol
// collision trap that bit SpeechService / TtsService earlier.
constexpr auto CLAP_TAG = "ClapDetector";
-constexpr int kClapShutdownTimeoutMs = 1500;
} // namespace
ClapDetectorService& ClapDetectorService::instance() {
@@ -140,14 +139,22 @@ void ClapDetectorService::stop() {
return;
LOG_INFO(CLAP_TAG, "stop — terminating clap detector");
- disconnect(process_, nullptr, this, nullptr);
- if (process_->state() != QProcess::NotRunning) {
- process_->kill();
- process_->waitForFinished(kClapShutdownTimeoutMs);
- }
- process_->deleteLater();
+ // Fire-and-forget teardown (§P1) — stop() is UI-reachable (clap-to-start
+ // toggle in Settings, AI-chat voice mode). Detach first so the eventual exit
+ // cannot re-enter on_process_finished and emit a second
+ // listening_changed(false); the child reaps itself on `finished`, which also
+ // avoids ~QProcess's own blocking waitForFinished() on a running handle.
+ QProcess* dying = process_;
process_ = nullptr;
stdout_buffer_.clear();
+ disconnect(dying, nullptr, this, nullptr);
+ if (dying->state() == QProcess::NotRunning) {
+ dying->deleteLater();
+ } else {
+ connect(dying, &QProcess::finished, dying, &QObject::deleteLater);
+ connect(dying, &QProcess::errorOccurred, dying, &QObject::deleteLater);
+ dying->kill();
+ }
const bool was_active = active_.exchange(false, std::memory_order_acq_rel);
if (was_active)
diff --git a/fincept-qt/src/services/wallet/LocalWalletBridge.cpp b/fincept-qt/src/services/wallet/LocalWalletBridge.cpp
index a92c4bf04..587651ab7 100644
--- a/fincept-qt/src/services/wallet/LocalWalletBridge.cpp
+++ b/fincept-qt/src/services/wallet/LocalWalletBridge.cpp
@@ -1,5 +1,7 @@
#include "services/wallet/LocalWalletBridge.h"
+#include "auth/ConstantTime.h"
+#include "auth/LoopbackGuard.h"
#include "core/logging/Logger.h"
#include <QByteArray>
@@ -104,6 +106,17 @@ bool LocalWalletBridge::is_listening() const noexcept {
return server_ != nullptr && server_->isListening();
}
+quint16 LocalWalletBridge::own_port() const noexcept {
+ return server_ ? server_->serverPort() : 0;
+}
+
+QByteArray LocalWalletBridge::own_origin() const {
+ const quint16 p = own_port();
+ if (p == 0)
+ return {};
+ return "http://127.0.0.1:" + QByteArray::number(p);
+}
+
void LocalWalletBridge::timerEvent(QTimerEvent* e) {
if (e->timerId() == timer_id_) {
LOG_WARN("WalletBridge", "timed out before callback");
@@ -154,6 +167,18 @@ void LocalWalletBridge::on_new_connection() {
socket->disconnectFromHost();
return;
}
+ // Host + fetch-metadata guard. Blocks DNS rebinding and any
+ // cross-origin subresource request from another page the user has
+ // open; our own served page is same-origin and always passes.
+ // See auth/LoopbackGuard.h for the full threat model.
+ const auto guard = fincept::auth::check_loopback_request(header_block, own_port());
+ if (!guard.allowed) {
+ LOG_WARN("WalletBridge", "rejected request: " + guard.reason);
+ write_response(socket, 403, "text/plain", "forbidden");
+ socket->disconnectFromHost();
+ return;
+ }
+
const QByteArray method = parts.value(0);
const QByteArray path = parts.value(1);
const QByteArray body = buf.mid(header_end + 4, content_length);
@@ -185,8 +210,11 @@ void LocalWalletBridge::handle_request(QTcpSocket* socket, const QByteArray& /*r
return;
}
+ // Constant-time compare — `!=` on QByteArray short-circuits at the first
+ // differing byte, and the timing difference leaks the token byte by byte to
+ // anything that can hammer this port.
const auto token_in_query = query_param(path, "token");
- if (token_in_query != connect_token_) {
+ if (!fincept::auth::constant_time_equals(token_in_query, connect_token_)) {
LOG_WARN("WalletBridge", QStringLiteral("token mismatch on %1 (got %2 chars)")
.arg(QString::fromLatin1(path))
.arg(token_in_query.size()));
@@ -302,10 +330,16 @@ void LocalWalletBridge::write_response(QTcpSocket* socket, int status, const QBy
response.append("Referrer-Policy: no-referrer\r\n");
// Same-origin in practice (page + fetch both served by us), but some
// browsers (and some Phantom builds) trip on missing CORS for any
- // localhost POST. Echoing the page's own origin keeps it safe.
- response.append("Access-Control-Allow-Origin: *\r\n");
- response.append("Access-Control-Allow-Headers: Content-Type\r\n");
- response.append("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n");
+ // localhost POST. Send the page's OWN origin — the comment here used to
+ // claim that while the code actually sent `*`, which invites every origin
+ // on the web to read this bridge's responses.
+ const QByteArray origin = own_origin();
+ if (!origin.isEmpty()) {
+ response.append("Access-Control-Allow-Origin: " + origin + "\r\n");
+ response.append("Vary: Origin\r\n");
+ response.append("Access-Control-Allow-Headers: Content-Type\r\n");
+ response.append("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n");
+ }
response.append("\r\n");
response.append(body);
socket->write(response);
diff --git a/fincept-qt/src/services/wallet/LocalWalletBridge.h b/fincept-qt/src/services/wallet/LocalWalletBridge.h
index f0a815adf..d449c079e 100644
--- a/fincept-qt/src/services/wallet/LocalWalletBridge.h
+++ b/fincept-qt/src/services/wallet/LocalWalletBridge.h
@@ -26,10 +26,15 @@ namespace fincept::wallet {
/// Security:
/// - listens only on QHostAddress::LocalHost (no LAN, no public).
/// - random port, random connect_token (32 bytes hex) bound to one connect.
-/// - any request with a missing/wrong token is rejected with 403.
+/// - any request with a missing/wrong token is rejected with 403; the token
+/// is compared in constant time.
+/// - Host + Sec-Fetch-* validation rejects DNS rebinding and cross-origin
+/// subresource injection from any other page the user has open
+/// (auth/LoopbackGuard.h).
+/// - Access-Control-Allow-Origin names our own loopback origin, never `*`.
/// - server self-destructs after success or timeout.
-/// - never speaks HTTP/2, never allows CORS, never serves anything besides
-/// the embedded connect page and a tiny 200 OK on /callback.
+/// - never speaks HTTP/2, never serves anything besides the embedded connect
+/// page and a tiny 200 OK on /callback.
class LocalWalletBridge : public QObject {
Q_OBJECT
public:
@@ -60,6 +65,10 @@ class LocalWalletBridge : public QObject {
const QByteArray& path, const QByteArray& method);
QByteArray render_connect_page() const;
void write_response(QTcpSocket* socket, int status, const QByteArray& content_type, const QByteArray& body);
+ /// Port we are actually bound to, or 0 when not listening.
+ quint16 own_port() const noexcept;
+ /// "http://127.0.0.1:<port>" — the only origin allowed to talk to us.
+ QByteArray own_origin() const;
QTcpServer* server_ = nullptr;
QByteArray nonce_hex_;
diff --git a/fincept-qt/src/services/wallet/WalletTxBridge.cpp b/fincept-qt/src/services/wallet/WalletTxBridge.cpp
index 3c7672cae..83ce6ca67 100644
--- a/fincept-qt/src/services/wallet/WalletTxBridge.cpp
+++ b/fincept-qt/src/services/wallet/WalletTxBridge.cpp
@@ -1,5 +1,7 @@
#include "services/wallet/WalletTxBridge.h"
+#include "auth/ConstantTime.h"
+#include "auth/LoopbackGuard.h"
#include "core/logging/Logger.h"
#include <QByteArray>
@@ -222,6 +224,18 @@ void WalletTxBridge::on_new_connection() {
socket->disconnectFromHost();
return;
}
+ // Host + fetch-metadata guard — blocks DNS rebinding and any
+ // cross-origin subresource request. Our own swap page is
+ // same-origin and passes. See auth/LoopbackGuard.h.
+ const auto guard =
+ fincept::auth::check_loopback_request(header_block, server_ ? server_->serverPort() : quint16(0));
+ if (!guard.allowed) {
+ LOG_WARN("WalletTxBridge", "rejected request: " + guard.reason);
+ write_response(socket, 403, "text/plain", "forbidden");
+ socket->disconnectFromHost();
+ return;
+ }
+
const QByteArray method = parts.value(0);
const QByteArray path = parts.value(1);
const QByteArray body = buf.mid(header_end + 4, content_length);
@@ -266,8 +280,10 @@ void WalletTxBridge::handle_request(QTcpSocket* socket, const QByteArray& body,
return;
}
+ // Constant-time compare — a short-circuiting `!=` leaks the token byte by
+ // byte through response timing to anything that can hammer this port.
const auto token_in_query = tx_query_param(path, "token");
- if (token_in_query != session_token_) {
+ if (!fincept::auth::constant_time_equals(token_in_query, session_token_)) {
LOG_WARN("WalletTxBridge", "token mismatch — rejecting");
write_response(socket, 403, "text/plain", "forbidden");
socket->disconnectFromHost();
diff --git a/fincept-qt/src/services/workflow/RiskManager.cpp b/fincept-qt/src/services/workflow/RiskManager.cpp
index 45f642958..58a333003 100644
--- a/fincept-qt/src/services/workflow/RiskManager.cpp
+++ b/fincept-qt/src/services/workflow/RiskManager.cpp
@@ -2,6 +2,7 @@
#include "core/logging/Logger.h"
+#include <QCoreApplication>
#include <QDate>
namespace fincept::workflow {
@@ -13,6 +14,14 @@ RiskManager& RiskManager::instance() {
RiskManager::RiskManager() : QObject(nullptr) {
daily_stats_.date = QDate::currentDate().toString(Qt::ISODate);
+ // The gate is consulted from QtConcurrent worker threads (basket / split /
+ // algo order paths), so this singleton can end up first constructed on a pool
+ // thread that later dies — leaving its signals and its end-of-process
+ // destruction homed to a dead thread. Re-home it on the application thread.
+ // Moving is only legal from the object's current thread, which is exactly
+ // where we are during construction.
+ if (auto* app = QCoreApplication::instance(); app && thread() != app->thread())
+ moveToThread(app->thread());
}
QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, const QString& side, double quantity,
@@ -30,8 +39,12 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
const double eff_volume = same_day ? daily_stats_.volume : 0.0;
const double eff_realized_pnl = same_day ? daily_stats_.realized_pnl : 0.0;
+ // Every numeric limit below is OPT-IN: a value of 0 (the default) means "no
+ // limit". This gate runs on the real order path, so an unset limit must pass
+ // the order through rather than reject everything.
+
// Position size check
- if (quantity > limits_.max_position_size) {
+ if (limits_.max_position_size > 0 && quantity > limits_.max_position_size) {
results.append({false, RiskSeverity::Error, "position_size",
QString("Quantity %1 exceeds max %2").arg(quantity).arg(limits_.max_position_size)});
} else {
@@ -39,7 +52,7 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Position value check
- if (order_value > limits_.max_position_value) {
+ if (limits_.max_position_value > 0 && order_value > limits_.max_position_value) {
results.append({false, RiskSeverity::Error, "position_value",
QString("Value $%1 exceeds max $%2")
.arg(order_value, 0, 'f', 2)
@@ -49,7 +62,7 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Single order value check
- if (order_value > limits_.max_single_order_value) {
+ if (limits_.max_single_order_value > 0 && order_value > limits_.max_single_order_value) {
results.append({false, RiskSeverity::Error, "order_value",
QString("Order value $%1 exceeds single order limit $%2")
.arg(order_value, 0, 'f', 2)
@@ -59,7 +72,7 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Daily trade count check
- if (eff_trade_count >= limits_.max_daily_trades) {
+ if (limits_.max_daily_trades > 0 && eff_trade_count >= limits_.max_daily_trades) {
results.append(
{false, RiskSeverity::Warning, "daily_trades",
QString("Daily trade count %1 at limit %2").arg(eff_trade_count).arg(limits_.max_daily_trades)});
@@ -68,7 +81,7 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Daily volume check
- if (eff_volume + order_value > limits_.max_daily_volume) {
+ if (limits_.max_daily_volume > 0 && eff_volume + order_value > limits_.max_daily_volume) {
results.append({false, RiskSeverity::Warning, "daily_volume",
QString("Daily volume would exceed $%1 limit").arg(limits_.max_daily_volume, 0, 'f', 2)});
} else {
@@ -76,7 +89,7 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Daily loss limit check
- if (eff_realized_pnl < -limits_.daily_loss_limit) {
+ if (limits_.daily_loss_limit > 0 && eff_realized_pnl < -limits_.daily_loss_limit) {
results.append({false, RiskSeverity::Critical, "daily_loss",
QString("Daily loss $%1 exceeds limit $%2")
.arg(-eff_realized_pnl, 0, 'f', 2)
@@ -103,13 +116,24 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
bool RiskManager::is_order_allowed(const QString& symbol, const QString& side, double quantity, double price,
- bool paper_trading) const {
+ bool paper_trading, QString* reason_out) const {
auto results = validate_order(symbol, side, quantity, price, paper_trading);
+ QStringList reasons;
for (const auto& r : results) {
if (!r.passed && (r.severity == RiskSeverity::Error || r.severity == RiskSeverity::Critical))
- return false;
+ reasons.append(r.message);
}
- return true;
+ if (reasons.isEmpty())
+ return true;
+ // Report WHICH limit bit — a bare "rejected" gives the user nothing to act on.
+ LOG_INFO("RiskManager", QString("Order rejected by risk limits: %1 %2 x%3 @ %4 — %5")
+ .arg(side, symbol)
+ .arg(quantity)
+ .arg(price)
+ .arg(reasons.join("; ")));
+ if (reason_out)
+ *reason_out = reasons.join("; ");
+ return false;
}
void RiskManager::record_trade(double pnl, double volume) {
@@ -144,11 +168,15 @@ void RiskManager::reset_daily_stats() {
}
RiskSeverity RiskManager::current_risk_level() const {
- if (daily_stats_.realized_pnl < -limits_.daily_loss_limit)
- return RiskSeverity::Critical;
- if (daily_stats_.realized_pnl < -limits_.daily_loss_limit * 0.8)
- return RiskSeverity::Error;
- if (daily_stats_.trade_count > limits_.max_daily_trades * 0.8)
+ // Unset limits (0) mean "no limit" — without these guards a zero daily_loss_limit
+ // would report Critical the instant realized P&L went a cent negative.
+ if (limits_.daily_loss_limit > 0) {
+ if (daily_stats_.realized_pnl < -limits_.daily_loss_limit)
+ return RiskSeverity::Critical;
+ if (daily_stats_.realized_pnl < -limits_.daily_loss_limit * 0.8)
+ return RiskSeverity::Error;
+ }
+ if (limits_.max_daily_trades > 0 && daily_stats_.trade_count > limits_.max_daily_trades * 0.8)
return RiskSeverity::Warning;
return RiskSeverity::Info;
}
diff --git a/fincept-qt/src/services/workflow/RiskManager.h b/fincept-qt/src/services/workflow/RiskManager.h
index ccc056c6a..5ea530842 100644
--- a/fincept-qt/src/services/workflow/RiskManager.h
+++ b/fincept-qt/src/services/workflow/RiskManager.h
@@ -19,32 +19,40 @@ struct RiskCheckResult {
};
/// Comprehensive risk limits configuration.
+///
+/// IMPORTANT — every limit is OPT-IN and defaults to "no limit" (0). These are
+/// enforced on the real order path (UnifiedTrading::place_order and the basket /
+/// split / smart paths), so a non-zero default would silently start rejecting
+/// trades that work today on an install nobody ever configured. A limit only
+/// applies once an operator has set it to a positive value; `blocked_symbols` is
+/// likewise empty and short selling is allowed (selling is normal trading — this
+/// flag exists to opt *out*).
struct RiskLimits {
- // Position limits
- double max_position_size = 1000; // max shares per position
- double max_position_value = 50000; // max $ value per position
- double max_portfolio_exposure = 0.25; // max % of portfolio
- int max_total_positions = 20;
-
- // Order limits
- double max_single_order_value = 25000;
- int max_daily_trades = 100;
- double max_daily_volume = 500000;
-
- // Loss limits
- double daily_loss_limit = 5000;
- double weekly_loss_limit = 15000;
- double per_position_stop_loss = 0.05; // 5%
+ // Position limits (0 = unlimited)
+ double max_position_size = 0; // max units per order
+ double max_position_value = 0; // max value per position
+ double max_portfolio_exposure = 0; // max fraction of portfolio
+ int max_total_positions = 0;
+
+ // Order limits (0 = unlimited)
+ double max_single_order_value = 0;
+ int max_daily_trades = 0;
+ double max_daily_volume = 0;
+
+ // Loss limits (0 = unlimited)
+ double daily_loss_limit = 0;
+ double weekly_loss_limit = 0;
+ double per_position_stop_loss = 0;
// Asset restrictions
QStringList allowed_asset_classes = {"equity", "etf", "crypto"};
QStringList blocked_symbols;
- bool allow_short_selling = false;
- bool allow_margin = false;
+ bool allow_short_selling = true;
+ bool allow_margin = true;
// Time restrictions
- bool trading_hours_only = true;
- bool allow_premarket = false;
+ bool trading_hours_only = false;
+ bool allow_premarket = true;
};
/// Tracks daily P&L and trade counts.
@@ -66,9 +74,12 @@ class RiskManager : public QObject {
QVector<RiskCheckResult> validate_order(const QString& symbol, const QString& side, double quantity, double price,
bool paper_trading = true) const;
- /// Check if all validations pass.
+ /// Check if all validations pass. On failure `reason_out` (optional) receives
+ /// the joined messages of the failing Error/Critical checks, so the caller can
+ /// tell the user exactly which limit blocked the order instead of a bare
+ /// "rejected".
bool is_order_allowed(const QString& symbol, const QString& side, double quantity, double price,
- bool paper_trading = true) const;
+ bool paper_trading = true, QString* reason_out = nullptr) const;
/// Get/set risk limits.
const RiskLimits& limits() const { return limits_; }
diff --git a/fincept-qt/src/storage/StorageManager.cpp b/fincept-qt/src/storage/StorageManager.cpp
index 14158d436..18e6d10a8 100644
--- a/fincept-qt/src/storage/StorageManager.cpp
+++ b/fincept-qt/src/storage/StorageManager.cpp
@@ -5,12 +5,18 @@
#include "storage/cache/CacheManager.h"
#include "storage/sqlite/CacheDatabase.h"
#include "storage/sqlite/Database.h"
+#include "storage/workspace/WorkspaceDb.h"
+#include <QCoreApplication>
+#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QSqlQuery>
+#include <QTimer>
+#include <QtConcurrent>
+#include <QPointer>
namespace fincept {
@@ -51,6 +57,47 @@ Result<void> StorageManager::delete_from(const QString& table, const QString& wh
return db.exec(sql);
}
+bool StorageManager::table_exists(const QString& table) const {
+ auto& db = Database::instance();
+ if (!db.is_open())
+ return false;
+ auto r = db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ? LIMIT 1", {table});
+ return r.is_ok() && r.value().next();
+}
+
+Result<void> StorageManager::delete_cascade(const QStringList& tables) {
+ auto& db = Database::instance();
+ if (!db.is_open())
+ return Result<void>::err("Database not open");
+
+ auto tx = db.begin_transaction();
+ if (tx.is_err())
+ return tx;
+
+ for (const QString& table : tables) {
+ // A table this build never creates is not a failure — the old code
+ // discarded every intermediate Result, so a missing auxiliary table was
+ // silently tolerated. Preserve that, but make REAL errors atomic.
+ if (!table_exists(table))
+ continue;
+
+ auto r = delete_from(table);
+ if (r.is_err()) {
+ db.rollback();
+ LOG_ERROR("StorageManager",
+ QString("Cascade delete aborted at %1: %2").arg(table, QString::fromStdString(r.error())));
+ return r;
+ }
+ }
+
+ auto c = db.commit();
+ if (c.is_err()) {
+ db.rollback();
+ return c;
+ }
+ return Result<void>::ok();
+}
+
// ── Category definitions ─────────────────────────────────────────────────────
QVector<StorageCategoryInfo> StorageManager::all_stats() const {
@@ -200,11 +247,9 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Chat: clear messages first (FK), then sessions ---
if (category_id == "chat_sessions") {
- auto r1 = delete_from("chat_context_links");
- auto r2 = delete_from("chat_messages");
- auto r3 = delete_from("chat_sessions");
- if (r3.is_err())
- return r3;
+ auto r = delete_cascade({"chat_context_links", "chat_messages", "chat_sessions"});
+ if (r.is_err())
+ return r;
emit category_cleared(category_id);
return Result<void>::ok();
}
@@ -217,10 +262,9 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Context recordings ---
if (category_id == "context_recordings") {
- auto r1 = delete_from("recording_sessions");
- auto r2 = delete_from("recorded_contexts");
- if (r2.is_err())
- return r2;
+ auto r = delete_cascade({"recording_sessions", "recorded_contexts"});
+ if (r.is_err())
+ return r;
emit category_cleared(category_id);
return Result<void>::ok();
}
@@ -235,8 +279,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- LLM configs ---
if (category_id == "llm_configs") {
- delete_from("llm_global_settings");
- auto r = delete_from("llm_configs");
+ auto r = delete_cascade({"llm_global_settings", "llm_configs"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -250,21 +293,17 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- LLM profiles + assignments ---
if (category_id == "llm_profiles") {
- auto r1 = delete_from("llm_profile_assignments");
- auto r2 = delete_from("llm_profiles");
- if (r2.is_err())
- return r2;
+ auto r = delete_cascade({"llm_profile_assignments", "llm_profiles"});
+ if (r.is_err())
+ return r;
emit category_cleared(category_id);
return Result<void>::ok();
}
// --- News ---
if (category_id == "news_articles") {
- delete_from("news_entity_cache");
- delete_from("news_instability");
- delete_from("news_baselines");
- auto r = delete_from("news_articles");
- // FTS table clears automatically with content table
+ // FTS table clears automatically with content table (delete triggers).
+ auto r = delete_cascade({"news_entity_cache", "news_instability", "news_baselines", "news_articles"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -292,8 +331,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Reports ---
if (category_id == "reports") {
- delete_from("report_templates");
- auto r = delete_from("reports");
+ auto r = delete_cascade({"report_templates", "reports"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -301,11 +339,8 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Portfolios (cascade: snapshots, assets, transactions) ---
if (category_id == "portfolios") {
- delete_from("portfolio_snapshots");
- delete_from("portfolio_transactions");
- delete_from("portfolio_assets");
- delete_from("portfolio_holdings");
- auto r = delete_from("portfolios");
+ auto r = delete_cascade({"portfolio_snapshots", "portfolio_transactions", "portfolio_assets",
+ "portfolio_holdings", "portfolios"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -319,8 +354,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Watchlists ---
if (category_id == "watchlists") {
- delete_from("watchlist_stocks");
- auto r = delete_from("watchlists");
+ auto r = delete_cascade({"watchlist_stocks", "watchlists"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -328,8 +362,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Custom indices ---
if (category_id == "custom_indices") {
- delete_from("custom_index_values");
- auto r = delete_from("custom_indices");
+ auto r = delete_cascade({"custom_index_values", "custom_indices"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -337,11 +370,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Paper Trading ---
if (category_id == "pt_portfolios") {
- delete_from("pt_margin_blocks");
- delete_from("pt_trades");
- delete_from("pt_positions");
- delete_from("pt_orders");
- auto r = delete_from("pt_portfolios");
+ auto r = delete_cascade({"pt_margin_blocks", "pt_trades", "pt_positions", "pt_orders", "pt_portfolios"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -361,9 +390,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Workflows (cascade: edges, nodes) ---
if (category_id == "workflows") {
- delete_from("workflow_edges");
- delete_from("workflow_nodes");
- auto r = delete_from("workflows");
+ auto r = delete_cascade({"workflow_edges", "workflow_nodes", "workflows"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -371,16 +398,13 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Data sources ---
if (category_id == "data_sources") {
- delete_from("data_source_connections");
- delete_from("ws_provider_configs");
- auto r = delete_from("data_sources");
+ auto r = delete_cascade({"data_source_connections", "ws_provider_configs", "data_sources"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
}
if (category_id == "data_mappings") {
- delete_from("normalized_data");
- auto r = delete_from("data_mappings");
+ auto r = delete_cascade({"normalized_data", "data_mappings"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -388,10 +412,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- MCP servers ---
if (category_id == "mcp_servers") {
- delete_from("mcp_tool_usage_logs");
- delete_from("mcp_tools");
- delete_from("internal_mcp_tool_settings");
- auto r = delete_from("mcp_servers");
+ auto r = delete_cascade({"mcp_tool_usage_logs", "mcp_tools", "internal_mcp_tool_settings", "mcp_servers"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -399,8 +420,7 @@ Result<void> StorageManager::clear_category(const QString& category_id) {
// --- Dashboard layouts ---
if (category_id == "dashboard_layouts") {
- delete_from("dashboard_widget_instances");
- auto r = delete_from("dashboard_layouts");
+ auto r = delete_cascade({"dashboard_widget_instances", "dashboard_layouts"});
if (r.is_ok())
emit category_cleared(category_id);
return r;
@@ -516,6 +536,161 @@ Result<void> StorageManager::clear_workspace_files() {
return Result<void>::ok();
}
+// ── Retention ────────────────────────────────────────────────────────────────
+
+namespace {
+// Retention windows. Deliberately generous — these tables exist for forensics.
+constexpr int kAuditLogRetentionDays = 90;
+constexpr int kTelemetryRetentionDays = 30;
+// A push that has failed this many times is never going to succeed; the row is
+// dead-lettered rather than retried forever. `bump_attempt` has no other bound.
+constexpr int kOutboxMaxAttempts = 20;
+} // namespace
+
+int StorageManager::prune_main_db(const QString& table, const QString& where, const QVariantList& params) {
+ auto& db = Database::instance();
+ if (!db.is_open())
+ return 0;
+
+ // A table that was never created (its owning subsystem never ran) is not an
+ // error — the sweeper is unattended and must stay quiet.
+ if (!table_exists(table))
+ return 0;
+
+ auto r = db.execute("DELETE FROM " + table + " WHERE " + where, params);
+ if (r.is_err()) {
+ LOG_WARN("StorageManager",
+ QString("Retention sweep of %1 failed: %2").arg(table, QString::fromStdString(r.error())));
+ return -1;
+ }
+ return r.value().numRowsAffected();
+}
+
+void StorageManager::prune_off_thread() {
+ // prune_all() issues four bulk DELETEs across three databases. Deferring it
+ // with singleShot() moved it off the *startup* path but left it on the UI
+ // thread (P1) — and worse, it takes a write lock on the main DB, so any
+ // screen doing a synchronous read in its showEvent stalls behind it until
+ // busy_timeout. That is what made the alpha_arena screen miss an 8s
+ // construction deadline in the smoke walk: it was waiting on this prune.
+ //
+ // Safe to run on a worker now: Database/CacheDatabase/WorkspaceDb all hand
+ // out per-thread connections (this release's fix), so the prune gets its own
+ // handle instead of borrowing the main thread's.
+ // Never start a sweep during teardown. The databases this touches are
+ // singletons that TerminalShell::shutdown() closes, so a worker launched
+ // now would outlive them.
+ if (QCoreApplication::closingDown())
+ return;
+
+ if (prune_running_.exchange(true))
+ return; // a sweep is still going — skip this tick rather than pile up
+
+ QPointer<StorageManager> self = this;
+ prune_future_ = QtConcurrent::run([self]() {
+ if (self)
+ (void)self->prune_all();
+ if (self)
+ self->prune_running_.store(false);
+ });
+}
+
+Result<void> StorageManager::prune_all() {
+ int total = 0;
+
+ // workflow_audit_log — one row per node execution, written by AuditLogger and
+ // read by nothing outside it. `timestamp` is stored via datetime('now'), so
+ // the same 'YYYY-MM-DD HH:MM:SS' form compares lexicographically.
+ const int audit = prune_main_db("workflow_audit_log", QString("timestamp < datetime('now', '-%1 days')")
+ .arg(kAuditLogRetentionDays));
+ if (audit > 0) {
+ total += audit;
+ LOG_INFO("StorageManager", QString("Retention: removed %1 workflow_audit_log rows older than %2 days")
+ .arg(audit)
+ .arg(kAuditLogRetentionDays));
+ }
+
+ // sync_outbox — rows leave only via mark_done(); a permanently failing push
+ // was retried forever with no ceiling.
+ const int outbox = prune_main_db("sync_outbox", "attempts > ?", {kOutboxMaxAttempts});
+ if (outbox > 0) {
+ total += outbox;
+ LOG_WARN("StorageManager", QString("Retention: dead-lettered %1 sync_outbox rows past %2 push attempts")
+ .arg(outbox)
+ .arg(kOutboxMaxAttempts));
+ }
+
+ // unified_cache (cache.db) — was swept once at startup only, so a terminal
+ // left open for days never reclaimed expired rows.
+ {
+ auto& cdb = CacheDatabase::instance();
+ if (cdb.is_open()) {
+ const int expired = cdb.sweep_expired();
+ if (expired > 0) {
+ total += expired;
+ LOG_INFO("StorageManager", QString("Retention: removed %1 expired unified_cache rows").arg(expired));
+ }
+ }
+ }
+
+ // telemetry_events (workspace.db) — one row per action.invoke, no reader.
+ {
+ auto& wdb = WorkspaceDb::instance();
+ if (wdb.is_open()) {
+ const qint64 cutoff_ms =
+ QDateTime::currentMSecsSinceEpoch() - static_cast<qint64>(kTelemetryRetentionDays) * 86400LL * 1000LL;
+ auto r = wdb.execute("DELETE FROM telemetry_events WHERE ts_ms < ?", {cutoff_ms});
+ if (r.is_ok()) {
+ const int removed = r.value().numRowsAffected();
+ if (removed > 0) {
+ total += removed;
+ LOG_INFO("StorageManager", QString("Retention: removed %1 telemetry_events rows older than %2 days")
+ .arg(removed)
+ .arg(kTelemetryRetentionDays));
+ }
+ }
+ // A missing telemetry_events table just means telemetry never wrote
+ // this session — nothing to report.
+ }
+ }
+
+ if (total > 0)
+ LOG_INFO("StorageManager", QString("Retention sweep removed %1 rows in total").arg(total));
+ return Result<void>::ok();
+}
+
+void StorageManager::start_retention_sweeper(int interval_ms) {
+ if (retention_timer_)
+ return; // already running
+
+ retention_timer_ = new QTimer(this);
+ retention_timer_->setInterval(interval_ms);
+ retention_timer_->setTimerType(Qt::VeryCoarseTimer);
+ connect(retention_timer_, &QTimer::timeout, this, [this]() { prune_off_thread(); });
+ retention_timer_->start();
+
+ // First pass deferred off the startup critical path.
+ QTimer::singleShot(0, this, [this]() { prune_off_thread(); });
+
+ // Join the worker before the app tears the databases down. Without this the
+ // sweep is an unowned QtConcurrent task that keeps using Database /
+ // CacheDatabase / WorkspaceDb while TerminalShell::shutdown() closes them —
+ // an access violation during static destruction, i.e. after the crash
+ // handler is gone, so it produces no dump and no log line.
+ if (auto* app = QCoreApplication::instance()) {
+ connect(app, &QCoreApplication::aboutToQuit, this, [this]() {
+ if (retention_timer_)
+ retention_timer_->stop();
+ if (prune_future_.isRunning()) {
+ LOG_INFO("StorageManager", "Waiting for in-flight retention sweep before shutdown");
+ prune_future_.waitForFinished();
+ }
+ });
+ }
+
+ LOG_INFO("StorageManager", QString("Retention sweeper started (every %1 min)").arg(interval_ms / 60000));
+}
+
Result<void> StorageManager::clear_qsettings() {
LOG_INFO("StorageManager", "Clearing QSettings (window geometry, perspectives, UI state)");
QSettings settings("Fincept", "FinceptTerminal");
diff --git a/fincept-qt/src/storage/StorageManager.h b/fincept-qt/src/storage/StorageManager.h
index 4688068c4..ee9257d9a 100644
--- a/fincept-qt/src/storage/StorageManager.h
+++ b/fincept-qt/src/storage/StorageManager.h
@@ -3,7 +3,13 @@
#include <QObject>
#include <QString>
+#include <QStringList>
+#include <QVariantList>
#include <QVector>
+#include <QFuture>
+#include <atomic>
+
+class QTimer;
namespace fincept {
@@ -53,6 +59,32 @@ class StorageManager : public QObject {
/// Clears all QSettings (window geometry, perspectives, UI state).
Result<void> clear_qsettings();
+ // ── Retention ────────────────────────────────────────────────────────────
+ //
+ // Several tables were append-only with no reader and no retention, so they
+ // grew for the life of the install: `workflow_audit_log` (a row per node
+ // execution), `telemetry_events` (a row per action.invoke), `sync_outbox`
+ // rows whose push kept failing, and `unified_cache`, which was swept only
+ // once at startup — a terminal left open for days never reclaimed anything.
+
+ /// Apply every retention policy once. Safe to call repeatedly; each policy
+ /// is independent and a failure in one is logged, not propagated (this runs
+ /// unattended on a timer — one missing table must not stop the rest).
+ ///
+ /// Policies: workflow_audit_log > 90 days, telemetry_events > 30 days,
+ /// sync_outbox with attempts > 20 (dead-lettered), expired unified_cache.
+ Result<void> prune_all();
+
+ /// Dispatch `prune_all()` onto a worker thread. Never call `prune_all()`
+ /// directly from the UI thread: it takes a write lock on the main DB, so a
+ /// screen doing a synchronous read in its showEvent stalls behind it.
+ /// Skips the tick if a sweep is already in flight.
+ void prune_off_thread();
+
+ /// Run `prune_all()` now and every `interval_ms` thereafter (default 15 min).
+ /// Idempotent — calling twice does not create a second timer.
+ void start_retention_sweeper(int interval_ms = 15 * 60 * 1000);
+
signals:
void category_cleared(const QString& category_id);
@@ -61,6 +93,26 @@ class StorageManager : public QObject {
int count_table(const QString& table, const QString& where = {}) const;
Result<void> delete_from(const QString& table, const QString& where = {});
+
+ /// True when `table` exists in the main DB. Used so a cascade / retention
+ /// sweep can skip auxiliary tables this build never creates instead of
+ /// treating them as a failure.
+ bool table_exists(const QString& table) const;
+
+ /// Delete from every table in `tables` (children first) inside ONE
+ /// transaction, checking each statement. Any failure rolls the whole cascade
+ /// back — a half-cleared "Clear chat history" is worse than a failed one.
+ Result<void> delete_cascade(const QStringList& tables);
+
+ /// DELETE with params on the main DB; returns rows removed, or -1 on error.
+ /// Logs and swallows a missing table (returns 0) so the sweeper stays quiet.
+ int prune_main_db(const QString& table, const QString& where, const QVariantList& params = {});
+
+ QTimer* retention_timer_ = nullptr;
+ /// Guards against overlapping sweeps if one pass outlives the timer interval.
+ std::atomic<bool> prune_running_{false};
+ /// Held so aboutToQuit can join the sweep before the DBs are closed.
+ QFuture<void> prune_future_;
};
} // namespace fincept
diff --git a/fincept-qt/src/storage/repositories/BaseRepository.h b/fincept-qt/src/storage/repositories/BaseRepository.h
index 68fa6faa4..49a23a1c0 100644
--- a/fincept-qt/src/storage/repositories/BaseRepository.h
+++ b/fincept-qt/src/storage/repositories/BaseRepository.h
@@ -22,13 +22,35 @@ class BaseRepository {
static Database& db() { return Database::instance(); }
+ /// One-line summary of a failing statement, for the error log.
+ ///
+ /// These helpers used to log only the driver's message — "Parameter count
+ /// mismatch" or "No query Unable to fetch row" — with no indication of WHICH
+ /// statement failed, across ~16 repositories. That is unactionable: the
+ /// driver text alone cannot be traced back to a table, and both of those
+ /// strings are actually symptoms of `prepare()` having failed (Qt reports a
+ /// failed prepare as a bind/param error at exec time, not at prepare time).
+ /// Including the SQL and the bound-parameter count turns a mystery into a
+ /// one-line diagnosis.
+ ///
+ /// Truncated because some statements are long column lists, and the leading
+ /// clause is what identifies the table.
+ static QString sql_context(const QString& sql, const QVariantList& params) {
+ QString flat = sql.simplified();
+ constexpr int kMaxSqlChars = 160;
+ if (flat.size() > kMaxSqlChars)
+ flat = flat.left(kMaxSqlChars) + QStringLiteral("…");
+ return QStringLiteral("[params=%1] %2").arg(params.size()).arg(flat);
+ }
+
/// Execute a SELECT and return all matching rows mapped to a different type.
template <typename T>
Result<QVector<T>> query_list_as(const QString& sql, const QVariantList& params,
std::function<T(QSqlQuery&)> mapper) const {
auto r = db().execute(sql, params);
if (r.is_err()) {
- LOG_ERROR("Repo", QString("query_list_as failed: %1").arg(QString::fromStdString(r.error())));
+ LOG_ERROR("Repo", QString("query_list_as failed: %1 %2")
+ .arg(QString::fromStdString(r.error()), sql_context(sql, params)));
return Result<QVector<T>>::err(r.error());
}
QVector<T> result;
@@ -43,7 +65,8 @@ class BaseRepository {
Result<QVector<Entity>> query_list(const QString& sql, const QVariantList& params, RowMapper mapper) const {
auto r = db().execute(sql, params);
if (r.is_err()) {
- LOG_ERROR("Repo", QString("query_list failed: %1").arg(QString::fromStdString(r.error())));
+ LOG_ERROR("Repo", QString("query_list failed: %1 %2")
+ .arg(QString::fromStdString(r.error()), sql_context(sql, params)));
return Result<QVector<Entity>>::err(r.error());
}
QVector<Entity> result;
@@ -82,7 +105,8 @@ class BaseRepository {
Result<void> exec_write(const QString& sql, const QVariantList& params = {}) const {
auto r = db().execute(sql, params);
if (r.is_err()) {
- LOG_ERROR("Repo", QString("exec_write failed: %1").arg(QString::fromStdString(r.error())));
+ LOG_ERROR("Repo", QString("exec_write failed: %1 %2")
+ .arg(QString::fromStdString(r.error()), sql_context(sql, params)));
return Result<void>::err(r.error());
}
return Result<void>::ok();
@@ -92,7 +116,8 @@ class BaseRepository {
Result<qint64> exec_insert(const QString& sql, const QVariantList& params) const {
auto r = db().execute(sql, params);
if (r.is_err()) {
- LOG_ERROR("Repo", QString("exec_insert failed: %1").arg(QString::fromStdString(r.error())));
+ LOG_ERROR("Repo", QString("exec_insert failed: %1 %2")
+ .arg(QString::fromStdString(r.error()), sql_context(sql, params)));
return Result<qint64>::err(r.error());
}
return Result<qint64>::ok(r.value().lastInsertId().toLongLong());
diff --git a/fincept-qt/src/storage/repositories/FeedItemRepository.cpp b/fincept-qt/src/storage/repositories/FeedItemRepository.cpp
index 47e60c012..28266d1ef 100644
--- a/fincept-qt/src/storage/repositories/FeedItemRepository.cpp
+++ b/fincept-qt/src/storage/repositories/FeedItemRepository.cpp
@@ -30,19 +30,43 @@ FeedItem FeedItemRepository::map_row(QSqlQuery& q) {
Result<void> FeedItemRepository::upsert(const QString& feed_id, const QVector<FeedItem>& items,
qint64 fetched_at) const {
+ if (items.isEmpty())
+ return Result<void>::ok();
+
+ // One transaction for the whole batch. Without it every row is its own
+ // implicit commit — a 50-item RSS refresh cost 50 fsync-bearing commits, on
+ // EVERY poll of EVERY subscribed feed. Pattern copied from
+ // InstrumentRepository::replace_all / NewsArticleRepository.
+ auto tx = db().begin_transaction();
+ if (tx.is_err())
+ return tx;
+
+ const QString sql = "INSERT INTO feed_items "
+ "(feed_id, item_id, title, summary, link, source, sort_ts, time, fields_json, fetched_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(feed_id, item_id) DO NOTHING";
+
+ QVector<QVariantList> rows;
+ rows.reserve(items.size());
for (const auto& it : items) {
QJsonObject o;
for (auto i = it.fields.begin(); i != it.fields.end(); ++i)
o[i.key()] = i.value();
const QString fj = QString::fromUtf8(QJsonDocument(o).toJson(QJsonDocument::Compact));
- auto r =
- exec_write("INSERT INTO feed_items "
- "(feed_id, item_id, title, summary, link, source, sort_ts, time, fields_json, fetched_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
- "ON CONFLICT(feed_id, item_id) DO NOTHING",
- {feed_id, it.id, it.title, it.summary, it.link, it.source, it.sort_ts, it.time, fj, fetched_at});
- if (r.is_err())
- return r;
+ rows.append({feed_id, it.id, it.title, it.summary, it.link, it.source, it.sort_ts, it.time, fj, fetched_at});
+ }
+
+ auto w = db().execute_many(sql, rows);
+ if (w.is_err()) {
+ db().rollback();
+ LOG_ERROR("FeedItemRepo", QString("upsert failed: %1").arg(QString::fromStdString(w.error())));
+ return w;
+ }
+
+ auto c = db().commit();
+ if (c.is_err()) {
+ db().rollback();
+ return c;
}
return Result<void>::ok();
}
diff --git a/fincept-qt/src/storage/repositories/NewsArticleRepository.cpp b/fincept-qt/src/storage/repositories/NewsArticleRepository.cpp
index aa8f4ff00..977b49b05 100644
--- a/fincept-qt/src/storage/repositories/NewsArticleRepository.cpp
+++ b/fincept-qt/src/storage/repositories/NewsArticleRepository.cpp
@@ -287,12 +287,12 @@ Result<bool> NewsArticleRepository::toggle_saved(const QString& id) {
// ── load_saved ────────────────────────────────────────────────────────────────
-Result<QVector<fincept::services::NewsArticle>> NewsArticleRepository::load_saved() const {
+Result<QVector<fincept::services::NewsArticle>> NewsArticleRepository::load_saved(int limit) const {
return query_list("SELECT id, headline, summary, source, region, category, link, sort_ts, "
" priority, sentiment, impact, tickers, tier, lang, "
" threat_level, threat_cat, threat_conf, source_flag "
- "FROM news_articles WHERE saved = 1 ORDER BY sort_ts DESC",
- {}, map_row);
+ "FROM news_articles WHERE saved = 1 ORDER BY sort_ts DESC LIMIT ?",
+ {limit}, map_row);
}
// ── save_analysis / load_analysis ─────────────────────────────────────────────
@@ -381,10 +381,14 @@ Result<QVector<fincept::services::NewsArticle>> NewsArticleRepository::search_ft
// ── load_seen_ids ─────────────────────────────────────────────────────────────
-Result<QSet<QString>> NewsArticleRepository::load_seen_ids(int64_t since_ts) const {
- auto r = db().execute(since_ts > 0 ? "SELECT id FROM news_articles WHERE seen_at IS NOT NULL AND sort_ts >= ?"
- : "SELECT id FROM news_articles WHERE seen_at IS NOT NULL",
- since_ts > 0 ? QVariantList{static_cast<qint64>(since_ts)} : QVariantList{});
+Result<QSet<QString>> NewsArticleRepository::load_seen_ids(int64_t since_ts, int limit) const {
+ // ORDER BY before LIMIT so the cap keeps the *newest* seen IDs — those are
+ // the ones the feed model can still be showing.
+ auto r = db().execute(since_ts > 0 ? "SELECT id FROM news_articles WHERE seen_at IS NOT NULL AND sort_ts >= ? "
+ "ORDER BY sort_ts DESC LIMIT ?"
+ : "SELECT id FROM news_articles WHERE seen_at IS NOT NULL "
+ "ORDER BY sort_ts DESC LIMIT ?",
+ since_ts > 0 ? QVariantList{static_cast<qint64>(since_ts), limit} : QVariantList{limit});
if (r.is_err())
return Result<QSet<QString>>::err(r.error());
QSet<QString> ids;
diff --git a/fincept-qt/src/storage/repositories/NewsArticleRepository.h b/fincept-qt/src/storage/repositories/NewsArticleRepository.h
index 8be48c6fe..310af2742 100644
--- a/fincept-qt/src/storage/repositories/NewsArticleRepository.h
+++ b/fincept-qt/src/storage/repositories/NewsArticleRepository.h
@@ -30,9 +30,12 @@ class NewsArticleRepository : public BaseRepository<fincept::services::NewsArtic
/// Mark an article as read (sets seen_at = now). No-op if already seen.
Result<void> mark_seen(const QString& id);
- /// Return all article IDs seen since since_ts (unix seconds).
- /// Pass 0 to load all. Used to pre-populate the feed model on startup.
- Result<QSet<QString>> load_seen_ids(int64_t since_ts = 0) const;
+ /// Return article IDs seen since since_ts (unix seconds), newest first.
+ /// Pass 0 for "no lower bound". Used to pre-populate the feed model on
+ /// startup. Bounded like load_recent(): news_articles is the fastest-growing
+ /// table, and an unbounded scan made first entry to the News screen cost
+ /// proportional to all accumulated history.
+ Result<QSet<QString>> load_seen_ids(int64_t since_ts = 0, int limit = 5000) const;
/// Ensure the seen_at column exists (idempotent ALTER TABLE).
/// Called once at startup before any seen operations.
@@ -41,8 +44,8 @@ class NewsArticleRepository : public BaseRepository<fincept::services::NewsArtic
/// Toggle bookmark state for an article. Returns the new saved state.
Result<bool> toggle_saved(const QString& id);
- /// Return all bookmarked articles, newest first.
- Result<QVector<fincept::services::NewsArticle>> load_saved() const;
+ /// Return bookmarked articles, newest first. Bounded like load_recent().
+ Result<QVector<fincept::services::NewsArticle>> load_saved(int limit = 2000) const;
/// Ensure the saved column exists (idempotent ALTER TABLE).
void ensure_saved_column();
diff --git a/fincept-qt/src/storage/repositories/SettingsRepository.cpp b/fincept-qt/src/storage/repositories/SettingsRepository.cpp
index d2dd2d08b..6fdbce14b 100644
--- a/fincept-qt/src/storage/repositories/SettingsRepository.cpp
+++ b/fincept-qt/src/storage/repositories/SettingsRepository.cpp
@@ -29,11 +29,20 @@ Result<void> SettingsRepository::set(const QString& key, const QString& value, c
Result<QString> SettingsRepository::get(const QString& key, const QString& default_val) {
auto r = db().execute("SELECT value FROM settings WHERE key = ?", {key});
- if (r.is_err())
- return Result<QString>::ok(default_val);
+ if (r.is_err()) {
+ // A failed read is NOT "never set". Reporting it as ok(default_val) made
+ // a locked database or a wrong-thread connection indistinguishable from
+ // a genuine default — and every read-modify-write caller then wrote that
+ // default back through set()'s INSERT OR REPLACE, permanently destroying
+ // the user's real value. Callers must distinguish the two.
+ LOG_ERROR("SettingsRepository",
+ QString("get('%1') failed — reporting error, NOT the default: %2")
+ .arg(key, QString::fromStdString(r.error())));
+ return Result<QString>::err(r.error());
+ }
auto& q = r.value();
if (!q.next())
- return Result<QString>::ok(default_val);
+ return Result<QString>::ok(default_val); // genuinely never set
QString val = q.value(0).toString();
return Result<QString>::ok(val.isEmpty() ? default_val : val);
}
diff --git a/fincept-qt/src/storage/repositories/SettingsRepository.h b/fincept-qt/src/storage/repositories/SettingsRepository.h
index f56b02bca..b61231841 100644
--- a/fincept-qt/src/storage/repositories/SettingsRepository.h
+++ b/fincept-qt/src/storage/repositories/SettingsRepository.h
@@ -16,6 +16,21 @@ class SettingsRepository : public BaseRepository<Setting> {
static SettingsRepository& instance();
Result<void> set(const QString& key, const QString& value, const QString& category = "general");
+
+ /// Reads a setting.
+ ///
+ /// Three distinct outcomes — do not collapse them:
+ /// - `ok(stored value)` — the key is set.
+ /// - `ok(default_val)` — the key is genuinely absent (or stored empty).
+ /// - `err(message)` — the **read failed** (locked DB, wrong-thread
+ /// connection, schema error). The stored value is
+ /// unknown; it is NOT the default.
+ ///
+ /// A caller that reads a setting, populates UI from it, and later writes it
+ /// back MUST abort that write on `is_err()`. Treating an error as the
+ /// default persists the default over the user's real value — set() is an
+ /// `INSERT OR REPLACE`, so the original is gone. Read-only display paths may
+ /// fall back to the default, but must not write it back.
Result<QString> get(const QString& key, const QString& default_val = {});
Result<void> remove(const QString& key);
Result<QVector<Setting>> get_by_category(const QString& category);
diff --git a/fincept-qt/src/storage/sqlite/CacheDatabase.cpp b/fincept-qt/src/storage/sqlite/CacheDatabase.cpp
index 2938753c4..16a7fea15 100644
--- a/fincept-qt/src/storage/sqlite/CacheDatabase.cpp
+++ b/fincept-qt/src/storage/sqlite/CacheDatabase.cpp
@@ -2,24 +2,40 @@
#include "core/logging/Logger.h"
-#include <QMutexLocker>
+#include <QSqlRecord>
+#include <QThread>
namespace fincept {
+namespace {
+constexpr const char* kCacheConnectionName = "fincept_cache";
+constexpr const char* kCacheDbTag = "CacheDB";
+
+QString cache_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
+
CacheDatabase& CacheDatabase::instance() {
static CacheDatabase s;
return s;
}
Result<void> CacheDatabase::open(const QString& path) {
- db_ = QSqlDatabase::addDatabase("QSQLITE", "fincept_cache");
+ main_thread_ = QThread::currentThread();
+ db_path_ = path;
+
+ db_ = QSqlDatabase::addDatabase("QSQLITE", QString::fromLatin1(kCacheConnectionName));
db_.setDatabaseName(path);
if (!db_.open()) {
return Result<void>::err(db_.lastError().text().toStdString());
}
- LOG_INFO("CacheDB", "Opened cache database: " + path);
+ LOG_INFO(kCacheDbTag, "Opened cache database: " + path);
- auto pr = apply_pragmas();
+ auto pr = apply_pragmas(db_, /*include_database_wide=*/true);
if (pr.is_err())
return pr;
@@ -27,14 +43,12 @@ Result<void> CacheDatabase::open(const QString& path) {
if (tr.is_err())
return tr;
- // One-shot startup sweep of expired rows — prevents unbounded growth of unified_cache
- // across sessions. Cheap: idx_cache_expires makes this a range scan.
- auto sweep = execute("DELETE FROM unified_cache WHERE expires_at < datetime('now')");
- if (sweep.is_ok()) {
- const int removed = sweep.value().numRowsAffected();
- if (removed > 0)
- LOG_INFO("CacheDB", QString("Startup sweep removed %1 expired cache rows").arg(removed));
- }
+ // Startup sweep of expired rows. StorageManager::start_retention_sweeper()
+ // repeats this on a ~15 min timer — a terminal left open for days used to
+ // accumulate expired rows until the next relaunch.
+ const int removed = sweep_expired();
+ if (removed > 0)
+ LOG_INFO(kCacheDbTag, QString("Startup sweep removed %1 expired cache rows").arg(removed));
return Result<void>::ok();
}
@@ -48,10 +62,72 @@ bool CacheDatabase::is_open() const {
return db_.isOpen();
}
+QSqlDatabase CacheDatabase::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 pool workers, which keep their
+ // connection across tasks and clean up at pool shutdown.
+ struct Guard {
+ QString name;
+ ~Guard() {
+ if (!name.isEmpty())
+ QSqlDatabase::removeDatabase(name);
+ }
+ };
+ thread_local Guard guard;
+
+ if (guard.name.isEmpty()) {
+ if (db_path_.isEmpty()) {
+ LOG_ERROR(kCacheDbTag, "connection() called before open() — refusing to clone");
+ return {};
+ }
+
+ guard.name = QStringLiteral("fincept_cache_thread_%1_%2")
+ .arg(cache_thread_label(t))
+ .arg(reinterpret_cast<quintptr>(t), 0, 16);
+
+ // Clone by connection NAME: the QSqlDatabase-object overload would read
+ // the main thread's handle and its live driver from this thread.
+ QSqlDatabase clone = QSqlDatabase::cloneDatabase(QString::fromLatin1(kCacheConnectionName), guard.name);
+ if (!clone.open()) {
+ const QString err = clone.lastError().text();
+ LOG_ERROR(kCacheDbTag,
+ QString("Failed to open per-thread cache connection on [%1]: %2").arg(cache_thread_label(t), err));
+ QSqlDatabase::removeDatabase(guard.name);
+ guard.name.clear();
+ return {};
+ }
+ // journal_mode is file-global and already set by the main connection —
+ // only re-apply the per-connection PRAGMAs.
+ apply_pragmas(clone, /*include_database_wide=*/false);
+ const int n = ++per_thread_connections_;
+ LOG_INFO(kCacheDbTag,
+ QString("Opened per-thread cache connection on [%1] (total=%2)").arg(cache_thread_label(t)).arg(n));
+ }
+ return QSqlDatabase::database(guard.name, /*open=*/false);
+}
+
Result<QSqlQuery> CacheDatabase::execute(const QString& sql, const QVariantList& params) {
- QMutexLocker lock(&mutex_);
- QSqlQuery query(db_);
- query.prepare(sql);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen()) {
+ return Result<QSqlQuery>::err("Cache DB connection unavailable on this thread");
+ }
+ QSqlQuery query(conn);
+
+ // Check prepare() — see the identical note in Database::execute(). An
+ // unchecked prepare turns "no such column" into a misleading "Parameter
+ // count mismatch" at exec time, because bindValue() no-ops on a statement
+ // that was never prepared.
+ if (!query.prepare(sql)) {
+ return Result<QSqlQuery>::err("prepare failed: " + query.lastError().text().toStdString());
+ }
+
for (int i = 0; i < params.size(); ++i) {
query.bindValue(i, params[i]);
}
@@ -61,29 +137,81 @@ Result<QSqlQuery> CacheDatabase::execute(const QString& sql, const QVariantList&
return Result<QSqlQuery>::ok(std::move(query));
}
+Result<QVector<QVariantList>> CacheDatabase::query_rows(const QString& sql, const QVariantList& params) {
+ auto r = execute(sql, params);
+ if (r.is_err())
+ return Result<QVector<QVariantList>>::err(r.error());
+
+ QVector<QVariantList> rows;
+ auto& q = r.value();
+ const int cols = q.record().count();
+ while (q.next()) {
+ QVariantList row;
+ row.reserve(cols);
+ for (int c = 0; c < cols; ++c)
+ row.append(q.value(c));
+ rows.append(std::move(row));
+ }
+ return Result<QVector<QVariantList>>::ok(std::move(rows));
+}
+
+int CacheDatabase::sweep_expired() {
+ if (!is_open())
+ return -1;
+ // idx_cache_expires makes this a range scan, not a table scan.
+ auto r = execute("DELETE FROM unified_cache WHERE expires_at < datetime('now')");
+ if (r.is_err()) {
+ LOG_WARN(kCacheDbTag, QString("Expiry sweep failed: %1").arg(QString::fromStdString(r.error())));
+ return -1;
+ }
+ return r.value().numRowsAffected();
+}
+
Result<void> CacheDatabase::exec(const QString& sql) {
- QMutexLocker lock(&mutex_);
- QSqlQuery query(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen()) {
+ return Result<void>::err("Cache DB connection unavailable on this thread");
+ }
+ QSqlQuery query(conn);
if (!query.exec(sql)) {
return Result<void>::err(query.lastError().text().toStdString());
}
return Result<void>::ok();
}
-Result<void> CacheDatabase::apply_pragmas() {
+Result<void> CacheDatabase::apply_pragmas(QSqlDatabase& conn, bool include_database_wide) {
+ // journal_mode is a property of the FILE — one connection sets it for all.
+ // Everything else is per-connection and must be re-applied to every clone or
+ // the workers silently run with SQLite defaults (synchronous=FULL, 0 ms busy
+ // timeout → spurious SQLITE_BUSY under concurrent writers).
+ static const char* kDatabaseWide[] = {
+ "PRAGMA journal_mode = WAL",
+ };
// synchronous=NORMAL under WAL is the standard safe/fast combo. OFF risked full DB
// corruption on power loss — now that cache.db also holds tab_sessions and
// screen_state, durability matters more than the marginal write gain of OFF.
- const char* pragmas[] = {
- "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -10000",
- "PRAGMA temp_store = MEMORY", "PRAGMA mmap_size = 134217728", "PRAGMA busy_timeout = 3000",
+ // journal_size_limit bounds the -wal file: without it SQLite never truncates
+ // it back after a checkpoint, so a one-off burst leaves it at high water.
+ static const char* kPerConnection[] = {
+ "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -10000",
+ "PRAGMA temp_store = MEMORY", "PRAGMA mmap_size = 134217728",
+ "PRAGMA busy_timeout = 3000", "PRAGMA journal_size_limit = 67108864",
};
- for (auto* p : pragmas) {
- auto r = exec(p);
- if (r.is_err()) {
- LOG_WARN("CacheDB", 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(kCacheDbTag, QString("PRAGMA failed: %1 — %2").arg(sql, q.lastError().text()));
}
+ };
+
+ if (include_database_wide) {
+ for (auto* p : kDatabaseWide)
+ run(p);
}
+ for (auto* p : kPerConnection)
+ run(p);
+
return Result<void>::ok();
}
@@ -152,8 +280,8 @@ Result<void> CacheDatabase::create_tables() {
// ADD COLUMN runs only if instance_uuid is missing. Safe to call on
// every CacheDatabase::open across upgrades.
{
- QMutexLocker lock(&mutex_);
- QSqlQuery info(db_);
+ QSqlDatabase conn = connection();
+ QSqlQuery info(conn);
if (info.exec("PRAGMA table_info(screen_state)")) {
bool has_instance_uuid = false;
while (info.next()) {
@@ -163,11 +291,11 @@ Result<void> CacheDatabase::create_tables() {
}
}
if (!has_instance_uuid) {
- QSqlQuery alter(db_);
+ QSqlQuery alter(conn);
if (alter.exec("ALTER TABLE screen_state ADD COLUMN instance_uuid TEXT")) {
- LOG_INFO("CacheDB", "screen_state migrated: added instance_uuid column");
+ LOG_INFO(kCacheDbTag, "screen_state migrated: added instance_uuid column");
} else {
- LOG_WARN("CacheDB",
+ LOG_WARN(kCacheDbTag,
QString("Failed to add instance_uuid column: %1").arg(alter.lastError().text()));
}
}
@@ -181,7 +309,7 @@ Result<void> CacheDatabase::create_tables() {
if (r.is_err())
return r;
- LOG_INFO("CacheDB", "Cache tables initialized");
+ LOG_INFO(kCacheDbTag, "Cache tables initialized");
return Result<void>::ok();
}
diff --git a/fincept-qt/src/storage/sqlite/CacheDatabase.h b/fincept-qt/src/storage/sqlite/CacheDatabase.h
index 79e34f5ef..647fe1787 100644
--- a/fincept-qt/src/storage/sqlite/CacheDatabase.h
+++ b/fincept-qt/src/storage/sqlite/CacheDatabase.h
@@ -1,20 +1,34 @@
#pragma once
#include "core/result/Result.h"
-#include <QMutex>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QString>
#include <QVariantList>
+#include <QVector>
+
+#include <atomic>
+
+class QThread;
namespace fincept {
-/// Separate SQLite database for ephemeral cache data.
+/// Separate SQLite database for ephemeral cache data (cache.db).
/// Uses synchronous=NORMAL under WAL for safe, fast writes.
-/// A QMutex serializes access: Qt's QSqlDatabase connection is not thread-safe,
-/// and this cache is read/written from services whose callbacks may run on
-/// worker threads (HttpClient, PythonRunner finished signals).
+///
+/// Thread-safety: identical scheme to `Database`. QSqlDatabase has thread
+/// AFFINITY — a connection may only be used on the thread that created it. A
+/// mutex does not make a shared connection legal, and the previous design made
+/// that worse by returning a live `QSqlQuery` after the lock was released, so a
+/// caller stepped a statement on a connection another thread could already be
+/// preparing on. `connection()` now hands out a per-thread cloned connection;
+/// under WAL those need no serialisation, so there is no mutex any more.
+///
+/// Consequence for callers: the `QSqlQuery` returned by `execute()` belongs to
+/// the CALLING thread's connection and must be stepped on that same thread —
+/// which is what every call site already does. To hand results to another
+/// thread, use `query_rows()`, which materialises them.
class CacheDatabase {
public:
static CacheDatabase& instance();
@@ -23,18 +37,40 @@ class CacheDatabase {
void close();
bool is_open() const;
+ /// Returns a `QSqlDatabase` handle valid for the current thread.
+ /// Main thread: the primary connection opened by `open()`. Any other
+ /// thread: a lazily-created thread-local clone, removed from Qt's registry
+ /// when that thread exits.
+ QSqlDatabase connection();
+
Result<QSqlQuery> execute(const QString& sql, const QVariantList& params = {});
Result<void> exec(const QString& sql);
+ /// Like `execute()`, but copies every row out before the statement dies.
+ /// The result is a plain value type, so it is safe to move across threads.
+ Result<QVector<QVariantList>> query_rows(const QString& sql, const QVariantList& params = {});
+
+ /// Delete `unified_cache` rows whose TTL has lapsed.
+ /// Returns the number of rows removed, or -1 on error.
+ int sweep_expired();
+
+ /// The owning (main-thread) connection object.
+ /// MAIN THREAD ONLY — bypasses `connection()`. Kept for the settings SQL
+ /// console and diagnostics; everything else must use `execute()`/`exec()`.
QSqlDatabase& raw_db() { return db_; }
+ /// File path of the open database (empty if not open).
+ QString path() const { return db_path_; }
+
private:
CacheDatabase() = default;
- Result<void> apply_pragmas();
+ Result<void> apply_pragmas(QSqlDatabase& conn, bool include_database_wide);
Result<void> create_tables();
- QSqlDatabase db_;
- mutable QMutex mutex_;
+ 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/storage/sqlite/Database.cpp b/fincept-qt/src/storage/sqlite/Database.cpp
index 5b04adf79..03529d65d 100644
--- a/fincept-qt/src/storage/sqlite/Database.cpp
+++ b/fincept-qt/src/storage/sqlite/Database.cpp
@@ -89,7 +89,13 @@ QSqlDatabase Database::connection() {
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);
+ // Clone BY CONNECTION NAME, not by QSqlDatabase object. The object
+ // overload dereferences `db_` — the main thread's handle and its live
+ // QSqlDriver — from this worker thread, which is exactly the cross-thread
+ // access the per-thread scheme exists to avoid. Qt added this overload
+ // for precisely this case: it resolves the source inside the registry
+ // under Qt's own lock.
+ QSqlDatabase clone = QSqlDatabase::cloneDatabase(QString::fromLatin1(kMainConnectionName), 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));
@@ -113,7 +119,18 @@ Result<QSqlQuery> Database::execute(const QString& sql, const QVariantList& para
return Result<QSqlQuery>::err("DB connection unavailable on this thread");
}
QSqlQuery query(conn);
- query.prepare(sql);
+
+ // Check prepare(). Ignoring it hid the real error on every failing
+ // statement in the app: when prepare() fails, bindValue() silently does
+ // nothing and the subsequent exec() reports the *symptom* — "Parameter
+ // count mismatch", or "No query Unable to fetch row" when results are then
+ // read — instead of the actual cause, which is usually "no such table" or
+ // "no such column". Those two useless strings were what every repository
+ // logged, so a schema mismatch was undiagnosable from the log alone.
+ if (!query.prepare(sql)) {
+ return Result<QSqlQuery>::err("prepare failed: " + query.lastError().text().toStdString());
+ }
+
for (int i = 0; i < params.size(); ++i) {
query.bindValue(i, params[i]);
}
@@ -123,6 +140,36 @@ Result<QSqlQuery> Database::execute(const QString& sql, const QVariantList& para
return Result<QSqlQuery>::ok(std::move(query));
}
+Result<void> Database::execute_many(const QString& sql, const QVector<QVariantList>& rows) {
+ if (rows.isEmpty())
+ return Result<void>::ok();
+
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen()) {
+ return Result<void>::err("DB connection unavailable on this thread");
+ }
+
+ // Prepare ONCE. `execute()` re-prepares per call, which costs one
+ // sqlite3_prepare_v2 per row — a 100k-row broker instrument import paid
+ // 100k compilations of the same statement.
+ QSqlQuery query(conn);
+ if (!query.prepare(sql)) {
+ return Result<void>::err(query.lastError().text().toStdString());
+ }
+
+ int index = 0;
+ for (const auto& row : rows) {
+ for (int i = 0; i < row.size(); ++i)
+ query.bindValue(i, row[i]);
+ if (!query.exec()) {
+ return Result<void>::err("row " + std::to_string(index) + ": " +
+ query.lastError().text().toStdString());
+ }
+ ++index;
+ }
+ return Result<void>::ok();
+}
+
Result<void> Database::exec(const QString& sql) {
QSqlDatabase conn = connection();
if (!conn.isOpen()) {
@@ -176,9 +223,15 @@ Result<void> Database::apply_pragmas(QSqlDatabase& conn, bool include_database_w
static const char* kDatabaseWide[] = {
"PRAGMA journal_mode = WAL",
};
+ // journal_size_limit is per-connection but bounds a file-global artefact: a
+ // bulk import (100k instruments) grows -wal to hundreds of MB and, without a
+ // limit, SQLite never truncates it back after a checkpoint — the file stays
+ // at its high-water mark for the life of the install. 64 MB.
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",
+ "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -20000",
+ "PRAGMA temp_store = MEMORY", "PRAGMA mmap_size = 268435456",
+ "PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000",
+ "PRAGMA journal_size_limit = 67108864",
};
auto run = [&conn](const char* sql) {
diff --git a/fincept-qt/src/storage/sqlite/Database.h b/fincept-qt/src/storage/sqlite/Database.h
index b164e2804..1e1ccaeec 100644
--- a/fincept-qt/src/storage/sqlite/Database.h
+++ b/fincept-qt/src/storage/sqlite/Database.h
@@ -6,6 +6,7 @@
#include <QSqlQuery>
#include <QString>
#include <QVariantList>
+#include <QVector>
#include <atomic>
@@ -39,11 +40,24 @@ class Database {
Result<QSqlQuery> execute(const QString& sql, const QVariantList& params = {});
Result<void> exec(const QString& sql);
+ /// Prepare `sql` ONCE and execute it for every parameter row.
+ /// Use for bulk INSERT/UPDATE loops — `execute()` re-prepares per call, so an
+ /// N-row loop pays N statement compilations of an identical statement.
+ /// Does NOT open a transaction: call inside the caller's
+ /// begin_transaction()/commit() so the whole batch is one commit.
+ /// Stops and returns on the first failing row (the row index is in the error).
+ Result<void> execute_many(const QString& sql, const QVector<QVariantList>& rows);
+
// Transaction support (per-thread — operates on the calling thread's connection).
Result<void> begin_transaction();
Result<void> commit();
Result<void> rollback();
+ /// The owning (main-thread) connection object.
+ /// MAIN THREAD ONLY — this bypasses `connection()`, so using it from any
+ /// other thread is the cross-thread QSqlDatabase misuse the per-thread
+ /// scheme exists to prevent. Prefer `execute()` / `exec()` / `connection()`
+ /// everywhere; this accessor exists for the SQL console and diagnostics.
QSqlDatabase& raw_db() { return db_; }
/// Returns the file path of the open database (empty if not open).
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.cpp b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.cpp
index 5e5a7894a..d389335f6 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.cpp
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.cpp
@@ -2,10 +2,20 @@
#include "core/logging/Logger.h"
+#include <QFile>
+
#include <algorithm>
namespace fincept {
+namespace {
+constexpr const char* kMigrationTag = "DB";
+
+bool has_error_tag(const std::string& message, const char* tag) {
+ return message.rfind(tag, 0) == 0;
+}
+} // namespace
+
// ── Static migration registry ────────────────────────────────────────────────
static QVector<Migration>& migration_registry() {
@@ -24,57 +34,158 @@ const QVector<Migration>& MigrationRunner::all_migrations() {
return migration_registry();
}
+int MigrationRunner::highest_registered_version() {
+ const auto& reg = migration_registry();
+ return reg.isEmpty() ? 0 : reg.last().version; // registry is kept sorted
+}
+
+bool MigrationRunner::is_schema_newer_error(const std::string& error_message) {
+ return has_error_tag(error_message, kErrSchemaNewer);
+}
+
+bool MigrationRunner::is_migration_failure(const std::string& error_message) {
+ return has_error_tag(error_message, kErrMigrationFailed);
+}
+
+bool MigrationRunner::is_fatal_error(const std::string& error_message) {
+ // Only a FAILED migration is fatal. A half-applied schema is genuinely
+ // unsafe to run against, and continuing would let every repository read and
+ // write a shape that is neither the old nor the new one.
+ //
+ // A NEWER-than-build schema is deliberately NOT fatal. It is the normal
+ // state whenever a released build and a dev build share one AppData
+ // directory — the released build migrates the DB forward, then the dev tree
+ // (which has fewer migrations registered) opens the same file. Refusing to
+ // start there bricks the developer's terminal for a condition the app has
+ // always tolerated: every migration is skipped by the `version <= current`
+ // test and the app runs normally.
+ //
+ // The risk is real but bounded and situational, so it is surfaced as a loud
+ // warning at the call site rather than a hard stop. Making it fatal was
+ // tested against a live v57 database on a v51 build and blocked startup
+ // outright.
+ return is_migration_failure(error_message);
+}
+
// ── Instance methods ─────────────────────────────────────────────────────────
MigrationRunner::MigrationRunner(QSqlDatabase& db) : db_(db) {}
Result<void> MigrationRunner::run() {
+ backup_path_.clear();
+
auto r = ensure_schema_version_table();
- if (r.is_err())
- return r;
+ if (r.is_err()) {
+ return Result<void>::err(std::string(kErrMigrationFailed) + " " + r.error());
+ }
- int current = read_current_version();
+ const int current = read_current_version();
const auto& migrations = all_migrations();
+ const int target = highest_registered_version();
+
+ // (a) Downgrade notice. A DB written by a NEWER build is running against an
+ // older one: `run()` only skips `version <= current`, so every future
+ // migration is silently treated as "already applied" and this build queries
+ // a schema it does not fully understand.
+ //
+ // Warn, do NOT refuse. This is the normal state whenever a released build
+ // and a dev build share one AppData directory — the release migrates the DB
+ // forward, then the dev tree (fewer migrations registered) opens the same
+ // file. The app has always tolerated it; making it fatal was tested against
+ // a live v57 database on a v51 build and blocked startup outright, which is
+ // a far worse outcome than the risk it guards against. Tables this build
+ // does not know about are simply unused; the exposure is a table it DOES
+ // know that gained columns it cannot see.
+ //
+ // Returning ok() here is deliberate: an err() would send main() down the
+ // degraded DB-less path (no accounts, no repositories), which is not what
+ // "schema is ahead" warrants.
+ if (current > target) {
+ LOG_WARN(kMigrationTag,
+ QString("database schema v%1 is NEWER than this build (v%2) — all migrations skipped. "
+ "Normal when a released build shares this AppData directory; if data looks wrong, "
+ "run the newer build or restore a pre-upgrade backup of %3.")
+ .arg(current)
+ .arg(target)
+ .arg(db_.databaseName()));
+ return Result<void>::ok();
+ }
+
+ // (b) Back up before touching anything. Migrations are individually
+ // transactional but the SEQUENCE is not: v046 can commit and v047 fail,
+ // leaving a schema that matches no released build. The snapshot is the only
+ // way back from that.
+ if (current < target) {
+ auto br = backup_database(current, target);
+ if (br.is_err()) {
+ const QString detail = QString("cannot migrate v%1 → v%2: pre-migration backup failed (%3). Refusing to "
+ "migrate without a recovery copy — free disk space or check permissions "
+ "on %4 and relaunch.")
+ .arg(current)
+ .arg(target)
+ .arg(QString::fromStdString(br.error()), db_.databaseName());
+ LOG_ERROR(kMigrationTag, detail);
+ return Result<void>::err(std::string(kErrMigrationFailed) + " " + detail.toStdString());
+ }
+ }
+
+ // (c) Unambiguous failure reporting — every early return below carries the
+ // tag plus the backup path, so the caller can tell the user where the
+ // recoverable copy lives.
+ int applied_through = current;
+ auto fail = [this, &applied_through](const QString& what) {
+ QString detail = what + QString(" Schema left at v%1.").arg(applied_through);
+ if (!backup_path_.isEmpty())
+ detail += QString(" Pre-migration backup: %1").arg(backup_path_);
+ LOG_ERROR(kMigrationTag, detail);
+ return Result<void>::err(std::string(kErrMigrationFailed) + " " + detail.toStdString());
+ };
for (const auto& m : migrations) {
if (m.version <= current)
continue;
- LOG_INFO("DB", QString("Applying migration v%1: %2").arg(m.version).arg(m.name));
+ LOG_INFO(kMigrationTag, QString("Applying migration v%1: %2").arg(m.version).arg(m.name));
// Begin transaction for this migration
QSqlQuery q(db_);
if (!q.exec("BEGIN IMMEDIATE")) {
- return Result<void>::err("Failed to begin transaction for migration v" + std::to_string(m.version) + ": " +
- q.lastError().text().toStdString());
+ return fail(QString("Failed to begin transaction for migration v%1 (%2): %3.")
+ .arg(m.version)
+ .arg(m.name, q.lastError().text()));
}
// Apply
auto ar = apply_migration(m);
if (ar.is_err()) {
q.exec("ROLLBACK");
- LOG_ERROR("DB", QString("Migration v%1 failed: %2").arg(m.version).arg(QString::fromStdString(ar.error())));
- return ar;
+ return fail(QString("Migration v%1 (%2) failed: %3.")
+ .arg(m.version)
+ .arg(m.name, QString::fromStdString(ar.error())));
}
// Record version
auto vr = record_version(m.version, m.name);
if (vr.is_err()) {
q.exec("ROLLBACK");
- return vr;
+ return fail(QString("Migration v%1 (%2) applied but its version could not be recorded: %3.")
+ .arg(m.version)
+ .arg(m.name, QString::fromStdString(vr.error())));
}
// Commit
if (!q.exec("COMMIT")) {
- return Result<void>::err("Failed to commit migration v" + std::to_string(m.version) + ": " +
- q.lastError().text().toStdString());
+ return fail(QString("Failed to commit migration v%1 (%2): %3.")
+ .arg(m.version)
+ .arg(m.name, q.lastError().text()));
}
- LOG_INFO("DB", QString("Migration v%1 applied successfully").arg(m.version));
+ applied_through = m.version;
+ LOG_INFO(kMigrationTag, QString("Migration v%1 applied successfully").arg(m.version));
}
if (!migrations.isEmpty()) {
- LOG_INFO("DB", QString("Schema at version %1").arg(read_current_version()));
+ LOG_INFO(kMigrationTag, QString("Schema at version %1").arg(read_current_version()));
}
return Result<void>::ok();
}
@@ -98,6 +209,74 @@ Result<void> MigrationRunner::ensure_schema_version_table() {
return Result<void>::ok();
}
+Result<void> MigrationRunner::backup_database(int current_version, int target_version) {
+ const QString db_file = db_.databaseName();
+ // In-memory / unnamed databases have nothing on disk to copy. Not an error.
+ if (db_file.isEmpty() || db_file.startsWith(QLatin1String(":memory:"))) {
+ backup_path_.clear();
+ return Result<void>::ok();
+ }
+
+ const QString dest = QStringLiteral("%1.pre-v%2.bak").arg(db_file).arg(target_version);
+
+ // A backup left by an earlier FAILED attempt at the same target is the same
+ // vintage as what we would write now — keep the known-good copy rather than
+ // overwriting it with a database a partially-applied run may have touched.
+ if (QFile::exists(dest)) {
+ backup_path_ = dest;
+ LOG_INFO(kMigrationTag,
+ QString("Reusing existing pre-migration backup for v%1 → v%2: %3")
+ .arg(current_version)
+ .arg(target_version)
+ .arg(dest));
+ return Result<void>::ok();
+ }
+
+ // Preferred: VACUUM INTO. Produces a consistent, fully-checkpointed snapshot
+ // from an OPEN connection (SQLite >= 3.27; Qt 6.8 ships far newer), so no
+ // close/reopen dance and no torn WAL.
+ QString vacuum_error;
+ {
+ QString literal = dest;
+ literal.replace(QLatin1Char('\''), QStringLiteral("''"));
+ QSqlQuery q(db_);
+ if (q.exec(QStringLiteral("VACUUM INTO '%1'").arg(literal))) {
+ backup_path_ = dest;
+ LOG_INFO(kMigrationTag, QString("Backed up schema v%1 to %2 before migrating to v%3")
+ .arg(current_version)
+ .arg(dest)
+ .arg(target_version));
+ return Result<void>::ok();
+ }
+ vacuum_error = q.lastError().text();
+ LOG_WARN(kMigrationTag, QString("VACUUM INTO backup failed (%1) — falling back to checkpoint + file copy")
+ .arg(vacuum_error));
+ }
+
+ // Fallback: fold the WAL back into the main file so it is self-contained,
+ // then copy it. Migrations run before any other connection exists, so there
+ // is no concurrent writer to tear the copy.
+ {
+ QSqlQuery q(db_);
+ if (!q.exec("PRAGMA wal_checkpoint(TRUNCATE)")) {
+ LOG_WARN(kMigrationTag, QString("wal_checkpoint before backup failed: %1").arg(q.lastError().text()));
+ }
+ }
+ QFile::remove(dest); // a failed VACUUM INTO can leave a partial file behind
+ if (!QFile::copy(db_file, dest)) {
+ return Result<void>::err(QString("VACUUM INTO failed (%1) and the file copy to %2 also failed")
+ .arg(vacuum_error, dest)
+ .toStdString());
+ }
+
+ backup_path_ = dest;
+ LOG_INFO(kMigrationTag, QString("Backed up schema v%1 to %2 (file copy) before migrating to v%3")
+ .arg(current_version)
+ .arg(dest)
+ .arg(target_version));
+ return Result<void>::ok();
+}
+
Result<void> MigrationRunner::apply_migration(const Migration& m) {
return m.apply(db_);
}
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index e174de9d1..cf0a33b70 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -8,6 +8,7 @@
#include <QVector>
#include <functional>
+#include <string>
namespace fincept {
@@ -20,8 +21,36 @@ struct Migration {
/// Runs versioned migrations tracked in a schema_version table.
/// Migration files auto-register via static initialization.
+///
+/// Safety contract (do not weaken — a half-migrated DB is silent data loss):
+/// - A database written by a NEWER build is refused outright. Running an older
+/// binary against a future schema is unrecoverable: v050, for instance, does
+/// `DROP TABLE IF EXISTS aa_competitions`, so an older build would query
+/// tables that no longer exist. `run()` returns an error tagged with
+/// `kErrSchemaNewer` in that case.
+/// - Before the FIRST forward migration of a session, a consistent snapshot of
+/// the database file is written to `<db>.pre-v<target>.bak`. Backup failure
+/// aborts the migration — migrating with no recovery path is the bug this
+/// class exists to prevent.
+/// - Any failure returns an error tagged with `kErrMigrationFailed` and, when
+/// one exists, the backup path embedded in the message.
+///
+/// Callers MUST treat both tagged errors as fatal: show a blocking dialog and
+/// exit rather than booting the UI onto a half-migrated / future schema.
class MigrationRunner {
public:
+ /// Error tag prefixes. `run()` prefixes its error strings with one of these
+ /// so a caller can classify the failure without parsing prose.
+ static constexpr const char* kErrSchemaNewer = "[schema-newer]";
+ static constexpr const char* kErrMigrationFailed = "[migration-failed]";
+
+ /// True when `error_message` came from `run()` refusing a future schema.
+ static bool is_schema_newer_error(const std::string& error_message);
+ /// True when `error_message` came from a migration that failed to apply.
+ static bool is_migration_failure(const std::string& error_message);
+ /// True for either — i.e. "the database is not safe to use, do not boot".
+ static bool is_fatal_error(const std::string& error_message);
+
explicit MigrationRunner(QSqlDatabase& db);
/// Apply all pending migrations in order.
@@ -30,6 +59,12 @@ class MigrationRunner {
/// Current applied schema version (0 if none).
int current_version() const;
+ /// Highest version this build knows how to apply (0 if none registered).
+ static int highest_registered_version();
+
+ /// Path of the pre-migration backup taken by the last `run()`, or empty.
+ QString backup_path() const { return backup_path_; }
+
/// Register a migration (called at static-init time by each v00N file).
static void register_migration(Migration m);
@@ -42,7 +77,13 @@ class MigrationRunner {
Result<void> record_version(int version, const QString& name);
int read_current_version();
+ /// Snapshot the database file to `<db>.pre-v<target_version>.bak`.
+ /// Prefers `VACUUM INTO` (consistent, safe on an open connection, no
+ /// close/reopen); falls back to `wal_checkpoint(TRUNCATE)` + file copy.
+ Result<void> backup_database(int current_version, int target_version);
+
QSqlDatabase& db_;
+ QString backup_path_;
};
// Explicit registration functions — call these before Database::open()
@@ -97,5 +138,6 @@ void register_migration_v047();
void register_migration_v048();
void register_migration_v049();
void register_migration_v050();
+void register_migration_v051();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v051_drop_duplicate_indexes.cpp b/fincept-qt/src/storage/sqlite/migrations/v051_drop_duplicate_indexes.cpp
new file mode 100644
index 000000000..e4865f239
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v051_drop_duplicate_indexes.cpp
@@ -0,0 +1,65 @@
+// v051_drop_duplicate_indexes — Remove two indices that duplicate an existing
+// one. Every INSERT into the affected tables was maintaining two identical
+// b-trees, doubling write cost and disk for zero query benefit.
+//
+// 1. news_articles(sort_ts)
+// v013 created `idx_news_articles_sort_ts ON news_articles(sort_ts DESC)`.
+// v017 then created `idx_news_sort_ts ON news_articles(sort_ts)` — its own
+// comment admits the index "already [exists] on sort_ts". SQLite can scan
+// an index in either direction, so the DESC one serves both orders.
+// Dropped: idx_news_sort_ts (the v017 duplicate).
+//
+// 2. market_data(symbol, exchange, interval, timestamp_ms)
+// v033 declared that exact tuple as the table's PRIMARY KEY and then
+// created `idx_market_data_series_time` on the SAME four columns in the
+// SAME order. On a non-WITHOUT-ROWID table the PK is itself a unique
+// index, so the secondary index is pure overhead on every candle insert.
+// Dropped: idx_market_data_series_time.
+//
+// Historical migrations are never edited — this is a new forward migration, so
+// databases already at v050 converge with fresh installs.
+//
+// SAFE ON A POPULATED DATABASE: DROP INDEX touches no table rows and cannot
+// lose data. Queries that used the dropped indices are served by the survivor
+// (the DESC index / the primary key) with the same plan.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+// Uniquely named (not a bare `sql`) — unity builds concatenate ~20 TUs, and two
+// anonymous-namespace helpers sharing a name in one batch is a redefinition.
+Result<void> sql_v051(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+Result<void> apply_v051(QSqlDatabase& db) {
+ auto r = sql_v051(db, "DROP INDEX IF EXISTS idx_news_sort_ts");
+ if (r.is_err())
+ return r;
+
+ r = sql_v051(db, "DROP INDEX IF EXISTS idx_market_data_series_time");
+ if (r.is_err())
+ return r;
+
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v051() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({51, "drop_duplicate_indexes", apply_v051});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/storage/workspace/WorkspaceDb.cpp b/fincept-qt/src/storage/workspace/WorkspaceDb.cpp
index faf16be17..cb6033621 100644
--- a/fincept-qt/src/storage/workspace/WorkspaceDb.cpp
+++ b/fincept-qt/src/storage/workspace/WorkspaceDb.cpp
@@ -5,6 +5,8 @@
#include <QMutexLocker>
#include <QSqlError>
+#include <QSqlRecord>
+#include <QThread>
#include <QVariant>
namespace fincept {
@@ -19,6 +21,13 @@ QString connection_name_for_profile() {
const QString prof = ProfileManager::instance().active_profile_id().to_string();
return "fincept_workspace_" + prof;
}
+
+QString workspace_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
WorkspaceDb& WorkspaceDb::instance() {
@@ -40,6 +49,8 @@ Result<void> WorkspaceDb::open(const QString& path) {
QSqlDatabase::removeDatabase(connection_name_);
}
+ main_thread_ = QThread::currentThread();
+ db_path_ = path;
connection_name_ = connection_name_for_profile();
db_ = QSqlDatabase::addDatabase("QSQLITE", connection_name_);
db_.setDatabaseName(path);
@@ -48,10 +59,14 @@ Result<void> WorkspaceDb::open(const QString& path) {
LOG_ERROR(kWorkspaceDbTag, QString("Failed to open %1: %2").arg(path, err));
return Result<void>::err(err.toStdString());
}
+ // Retire any per-thread clone made against a previous profile/path before
+ // declaring the database open.
+ ++generation_;
+ open_ = true;
LOG_INFO(kWorkspaceDbTag, "Opened workspace database: " + path);
// Pragmas first so subsequent CREATE statements run under WAL.
- auto pr = apply_pragmas();
+ auto pr = apply_pragmas(db_, /*include_database_wide=*/true);
if (pr.is_err())
return pr;
@@ -64,22 +79,101 @@ Result<void> WorkspaceDb::open(const QString& path) {
void WorkspaceDb::close() {
QMutexLocker<QRecursiveMutex> lock(&mutex_);
+ open_ = false;
+ ++generation_; // invalidate per-thread clones
if (db_.isOpen())
db_.close();
if (!connection_name_.isEmpty()) {
QSqlDatabase::removeDatabase(connection_name_);
connection_name_.clear();
}
+ db_path_.clear();
}
bool WorkspaceDb::is_open() const {
- QMutexLocker<QRecursiveMutex> lock(&mutex_);
- return db_.isOpen();
+ // Deliberately does NOT touch db_: this is called from worker threads and
+ // QSqlDatabase::isOpen() would dereference the main thread's driver.
+ return open_.load();
+}
+
+QSqlDatabase WorkspaceDb::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 pool workers, which keep their
+ // connection across tasks and clean up at pool shutdown.
+ struct Guard {
+ QString name;
+ quint64 generation = 0;
+ ~Guard() {
+ if (!name.isEmpty())
+ QSqlDatabase::removeDatabase(name);
+ }
+ };
+ thread_local Guard guard;
+
+ // Snapshot the owning connection's identity under the lock — open()/close()
+ // can swap it underneath us on a profile switch.
+ QString source_name;
+ quint64 gen = 0;
+ {
+ QMutexLocker<QRecursiveMutex> lock(&mutex_);
+ if (!open_.load() || connection_name_.isEmpty() || db_path_.isEmpty()) {
+ LOG_ERROR(kWorkspaceDbTag, "connection() called while closed — refusing to clone");
+ return {};
+ }
+ source_name = connection_name_;
+ gen = generation_.load();
+ }
+
+ // A clone from a previous profile must not be reused against the new file.
+ if (!guard.name.isEmpty() && guard.generation != gen) {
+ QSqlDatabase::removeDatabase(guard.name);
+ guard.name.clear();
+ }
+
+ if (guard.name.isEmpty()) {
+ // Generation is part of the name so a retired clone's registry entry can
+ // never collide with its replacement.
+ guard.name = QStringLiteral("fincept_workspace_thread_%1_%2_%3")
+ .arg(workspace_thread_label(t))
+ .arg(reinterpret_cast<quintptr>(t), 0, 16)
+ .arg(gen);
+
+ // Clone by connection NAME: the QSqlDatabase-object overload would read
+ // the main thread's handle and its live driver from this thread, which
+ // is exactly the cross-thread access this scheme exists to avoid.
+ QSqlDatabase clone = QSqlDatabase::cloneDatabase(source_name, guard.name);
+ if (!clone.open()) {
+ const QString err = clone.lastError().text();
+ LOG_ERROR(kWorkspaceDbTag, QString("Failed to open per-thread workspace connection on [%1]: %2")
+ .arg(workspace_thread_label(t), err));
+ QSqlDatabase::removeDatabase(guard.name);
+ guard.name.clear();
+ return {};
+ }
+ // journal_mode is file-global and already set by the owning connection —
+ // only re-apply the per-connection PRAGMAs.
+ apply_pragmas(clone, /*include_database_wide=*/false);
+ guard.generation = gen;
+ const int n = ++per_thread_connections_;
+ LOG_INFO(kWorkspaceDbTag, QString("Opened per-thread workspace connection on [%1] (total=%2)")
+ .arg(workspace_thread_label(t))
+ .arg(n));
+ }
+ return QSqlDatabase::database(guard.name, /*open=*/false);
}
Result<QSqlQuery> WorkspaceDb::execute(const QString& sql, const QVariantList& params) {
- QMutexLocker<QRecursiveMutex> lock(&mutex_);
- QSqlQuery query(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen())
+ return Result<QSqlQuery>::err("Workspace 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]);
@@ -89,13 +183,33 @@ Result<QSqlQuery> WorkspaceDb::execute(const QString& sql, const QVariantList& p
}
Result<void> WorkspaceDb::exec(const QString& sql) {
- QMutexLocker<QRecursiveMutex> lock(&mutex_);
- QSqlQuery query(db_);
+ QSqlDatabase conn = connection();
+ if (!conn.isOpen())
+ return Result<void>::err("Workspace DB connection unavailable on this thread");
+ QSqlQuery query(conn);
if (!query.exec(sql))
return Result<void>::err(query.lastError().text().toStdString());
return Result<void>::ok();
}
+Result<QVector<QVariantList>> WorkspaceDb::query_rows(const QString& sql, const QVariantList& params) {
+ auto r = execute(sql, params);
+ if (r.is_err())
+ return Result<QVector<QVariantList>>::err(r.error());
+
+ QVector<QVariantList> rows;
+ auto& q = r.value();
+ const int cols = q.record().count();
+ while (q.next()) {
+ QVariantList row;
+ row.reserve(cols);
+ for (int c = 0; c < cols; ++c)
+ row.append(q.value(c));
+ rows.append(std::move(row));
+ }
+ return Result<QVector<QVariantList>>::ok(std::move(rows));
+}
+
Result<void> WorkspaceDb::begin_transaction() {
return exec("BEGIN");
}
@@ -109,17 +223,16 @@ Result<void> WorkspaceDb::rollback() {
}
QString WorkspaceDb::meta(const QString& key) const {
- // Re-acquire the lock here; execute() locks too, so we go through it.
- // This is one of the rare const methods that mutates internal state via
- // the mutex; mutable QMutex makes that explicit.
- QMutexLocker<QRecursiveMutex> lock(&mutex_);
- QSqlQuery query(db_);
- query.prepare("SELECT value FROM _meta WHERE key = ?");
- query.bindValue(0, key);
- if (!query.exec()) {
- LOG_WARN(kWorkspaceDbTag, QString("meta(%1) read failed: %2").arg(key, query.lastError().text()));
+ // Logically const, but it must go through execute() so the read lands on the
+ // CALLING thread's connection — building a QSqlQuery from db_ here was the
+ // cross-thread misuse this class no longer does. connection() lazily creates
+ // that per-thread clone, hence the const_cast.
+ auto r = const_cast<WorkspaceDb*>(this)->execute("SELECT value FROM _meta WHERE key = ?", {key});
+ if (r.is_err()) {
+ LOG_WARN(kWorkspaceDbTag, QString("meta(%1) read failed: %2").arg(key, QString::fromStdString(r.error())));
return {};
}
+ auto& query = r.value();
if (query.next())
return query.value(0).toString();
return {};
@@ -135,25 +248,43 @@ Result<void> WorkspaceDb::set_meta(const QString& key, const QString& value) {
}
QString WorkspaceDb::path() const {
+ // Cached string, not db_.databaseName() — the latter reads the owning
+ // connection's driver, which callers on other threads must not touch.
QMutexLocker<QRecursiveMutex> lock(&mutex_);
- return db_.databaseName();
+ return db_path_;
}
-Result<void> WorkspaceDb::apply_pragmas() {
+Result<void> WorkspaceDb::apply_pragmas(QSqlDatabase& conn, bool include_database_wide) {
// Same combo as CacheDatabase: WAL + NORMAL gives durable-on-power-loss
// writes with one fsync per checkpoint, not per write. busy_timeout
// covers the brief overlap when SessionManager's autosave race-collides
// with a closeEvent flush.
- const char* pragmas[] = {
- "PRAGMA journal_mode = WAL", "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -4000",
- "PRAGMA temp_store = MEMORY", "PRAGMA mmap_size = 67108864", "PRAGMA busy_timeout = 3000",
+ //
+ // journal_mode is a property of the FILE — one connection sets it for all.
+ // Everything else is per-connection and must be re-applied to every clone,
+ // or worker threads silently run with SQLite defaults (synchronous=FULL,
+ // 0 ms busy timeout → spurious SQLITE_BUSY under concurrent writers).
+ static const char* kDatabaseWide[] = {
+ "PRAGMA journal_mode = WAL",
+ };
+ static const char* kPerConnection[] = {
+ "PRAGMA synchronous = NORMAL", "PRAGMA cache_size = -4000", "PRAGMA temp_store = MEMORY",
+ "PRAGMA mmap_size = 67108864", "PRAGMA busy_timeout = 3000",
};
- for (const char* p : pragmas) {
- QSqlQuery q(db_);
- if (!q.exec(p)) {
- LOG_WARN(kWorkspaceDbTag, QString("PRAGMA failed: %1 — %2").arg(p, q.lastError().text()));
+
+ auto run = [&conn](const char* sql) {
+ QSqlQuery q(conn);
+ if (!q.exec(QLatin1String(sql))) {
+ LOG_WARN(kWorkspaceDbTag, QString("PRAGMA failed: %1 — %2").arg(sql, q.lastError().text()));
}
+ };
+
+ if (include_database_wide) {
+ for (const char* p : kDatabaseWide)
+ run(p);
}
+ for (const char* p : kPerConnection)
+ run(p);
return Result<void>::ok();
}
diff --git a/fincept-qt/src/storage/workspace/WorkspaceDb.h b/fincept-qt/src/storage/workspace/WorkspaceDb.h
index 37f473c2f..846ffcd7e 100644
--- a/fincept-qt/src/storage/workspace/WorkspaceDb.h
+++ b/fincept-qt/src/storage/workspace/WorkspaceDb.h
@@ -6,6 +6,11 @@
#include <QSqlQuery>
#include <QString>
#include <QVariantList>
+#include <QVector>
+
+#include <atomic>
+
+class QThread;
namespace fincept {
@@ -15,12 +20,25 @@ namespace fincept {
/// Design choices:
/// - WAL mode + synchronous=NORMAL — same combo CacheDatabase uses; safe
/// under power loss with one fsync per checkpoint, low write amplification.
-/// - QMutex around execute() — Qt's QSqlDatabase connection is not
-/// thread-safe and the workspace writer may be invoked from the UI
-/// thread (frame closeEvent) and from a worker (autosave debounce).
+/// - Per-thread connections, same scheme as `Database` / `CacheDatabase`.
+/// QSqlDatabase has thread AFFINITY, not merely a data race: a connection
+/// may only be used on the thread that created it. The previous design held
+/// one shared connection behind a QMutex and then RETURNED a live QSqlQuery
+/// after releasing the lock, so a caller stepped a statement on a connection
+/// another thread could already be preparing on. `connection()` now hands
+/// out a per-thread cloned connection; under WAL those need no
+/// serialisation. This matters because LocalTelemetrySink::record() writes
+/// here from arbitrary threads. The remaining mutex guards only the owning
+/// connection's identity (open/close/profile swap), never a live statement.
+/// - Consequence for callers: the `QSqlQuery` returned by `execute()` belongs
+/// to the CALLING thread's connection and must be stepped on that same
+/// thread — which is what every call site already does. To hand results to
+/// another thread use `query_rows()`, which materialises them first.
/// - Connection name is profile-scoped (`fincept_workspace_<profile_uuid>`)
/// so a future profile-switch path can have two WorkspaceDbs open
-/// concurrently during the swap.
+/// concurrently during the swap. A reopen bumps a generation counter so
+/// per-thread clones of the previous profile are retired lazily instead of
+/// silently writing to the old file.
/// - Path is taken from ProfilePaths::workspace_db() — TerminalShell::initialise()
/// opens the db immediately after that path resolver runs.
///
@@ -63,9 +81,19 @@ class WorkspaceDb {
void close();
bool is_open() const;
+ /// Returns a `QSqlDatabase` handle valid for the current thread.
+ /// Main thread: the primary connection opened by `open()`. Any other thread:
+ /// a lazily-created thread-local clone, removed from Qt's registry when that
+ /// thread exits (or when a profile switch reopens the database).
+ QSqlDatabase connection();
+
Result<QSqlQuery> execute(const QString& sql, const QVariantList& params = {});
Result<void> exec(const QString& sql);
+ /// Like `execute()`, but copies every row out before the statement dies.
+ /// The result is a plain value type, so it is safe to move across threads.
+ Result<QVector<QVariantList>> query_rows(const QString& sql, const QVariantList& params = {});
+
Result<void> begin_transaction();
Result<void> commit();
Result<void> rollback();
@@ -84,15 +112,29 @@ class WorkspaceDb {
private:
WorkspaceDb() = default;
- Result<void> apply_pragmas();
+ Result<void> apply_pragmas(QSqlDatabase& conn, bool include_database_wide);
Result<void> create_tables();
- QSqlDatabase db_;
- QString connection_name_;
- // Recursive: open() holds the mutex while calling create_tables(),
- // which routes through exec() that re-acquires the same mutex. With a
- // non-recursive QMutex this deadlocks the main thread before any window
- // is shown — see ee4e946e regression.
+ QSqlDatabase db_; // main-thread (owning) connection
+ QString connection_name_; // registry name of the owning connection
+ QString db_path_; // for cloning per-thread connections
+ QThread* main_thread_ = nullptr; // captured at open()
+
+ // Bumped on every open()/close(). A per-thread clone stamps the generation
+ // it was made under and is discarded when it no longer matches, so a
+ // profile switch cannot leave a worker writing into the previous profile.
+ std::atomic<quint64> generation_{0};
+ // is_open() is called from arbitrary threads (LocalTelemetrySink::record).
+ // Reading db_.isOpen() there would touch the main thread's driver, so track
+ // the state in an atomic instead.
+ std::atomic<bool> open_{false};
+ std::atomic<int> per_thread_connections_{0}; // diagnostic counter
+
+ // Recursive: open() holds the mutex while calling create_tables(), which
+ // routes through exec(). exec() no longer takes the mutex, but keep the
+ // recursive type so re-entrancy through this class can never deadlock the
+ // main thread before any window is shown — see ee4e946e regression.
+ // Guards only the owning connection's identity, never a live statement.
mutable QRecursiveMutex mutex_;
};
diff --git a/fincept-qt/src/trading/ActionCenter.cpp b/fincept-qt/src/trading/ActionCenter.cpp
index 58b707b51..1d1be75c9 100644
--- a/fincept-qt/src/trading/ActionCenter.cpp
+++ b/fincept-qt/src/trading/ActionCenter.cpp
@@ -12,6 +12,7 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QSqlQuery>
+#include <QStringList>
#include <QUuid>
#include <cmath>
@@ -65,7 +66,17 @@ void ActionCenter::set_order_mode(const QString& account_id, OrderMode mode) {
OrderMode ActionCenter::get_order_mode(const QString& account_id) const {
const QString key = "action_center.mode." + account_id;
auto r = SettingsRepository::instance().get(key, "auto");
- return parse_order_mode(r.is_ok() ? r.value() : QString("auto"));
+ if (r.is_err()) {
+ // Fail closed. should_queue() derives straight from this, so reporting
+ // the "auto" default on a read error would send a SemiAuto account's
+ // orders to the broker instead of the approval queue — silently
+ // defeating a risk control the user explicitly turned on.
+ LOG_WARN(kLog, QString("settings read failed for '%1' — treating the account as SemiAuto (approval "
+ "required) until the read succeeds: %2")
+ .arg(key, QString::fromStdString(r.error())));
+ return OrderMode::SemiAuto;
+ }
+ return parse_order_mode(r.value());
}
// ── Serialization ──────────────────────────────────────────────────────────
@@ -335,8 +346,9 @@ ActionCenter::Stats ActionCenter::get_stats(const QString& account_id) const {
// ── Execution on approval ──────────────────────────────────────────────────
-QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString& err) {
+QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString& err, bool& async) {
ok = false;
+ async = false;
if (po.order_type == "placeorder" || po.order_type == "smartorder") {
// Smart collapses to a standard place via UnifiedTrading for now —
// the serialized order carries the same fields. (place_smart_order
@@ -406,13 +418,30 @@ QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString&
const QJsonArray arr = po.order_data.value("orders").toArray();
for (const auto& v : arr)
basket.orders.append(deserialize_unified_order(v.toObject()));
- // place_basket_orders is async (background thread + callback). For the
- // approval gate we fire it and report acceptance immediately; per-leg
- // results surface via the trading event bus / order book.
- UnifiedTrading::instance().place_basket_orders(po.account_id, basket, [](const BasketOrderResult&) {});
- ok = true;
- err.clear();
- return {}; // no single broker order id for a basket
+ // place_basket_orders is async (background thread + callback). It used to
+ // be fired with an EMPTY callback and the row marked "approved" on the
+ // spot — which discarded "Account not found", "No credentials … Please
+ // authenticate" and every per-leg rejection, so the approval audit trail
+ // claimed success for a basket that never left the building. Capture the
+ // real result and finalize the row from the callback instead.
+ UnifiedTrading::instance().place_basket_orders(
+ po.account_id, basket, [this, po](const BasketOrderResult& res) {
+ const bool all_ok = (res.failed == 0 && res.successful > 0);
+ QStringList errs;
+ for (const auto& r : res.results) {
+ if (!r.success)
+ errs.append(QString("%1: %2").arg(r.symbol, r.error));
+ }
+ const QString detail =
+ all_ok ? QString()
+ : QString("%1/%2 legs failed — %3")
+ .arg(res.failed)
+ .arg(res.total)
+ .arg(errs.isEmpty() ? QStringLiteral("no legs placed") : errs.join("; "));
+ finalize_approval(po, all_ok, detail, {}); // no single broker order id for a basket
+ });
+ async = true;
+ return {};
}
if (po.order_type == "splitorder") {
@@ -420,9 +449,32 @@ QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString&
req.base_order = deserialize_unified_order(po.order_data);
req.split_size = po.order_data.value("splitsize").toInt((int)po.order_data.value("split_size").toDouble());
req.delay_between_ms = po.order_data.value("delay_between_ms").toInt(100);
- UnifiedTrading::instance().place_split_orders(po.account_id, req, [](const SplitOrderResult&) {});
- ok = true;
- err.clear();
+ // Same as basketorder: the outcome only exists in the callback, so the row
+ // is finalized there rather than pre-declared approved.
+ UnifiedTrading::instance().place_split_orders(po.account_id, req, [this, po](const SplitOrderResult& res) {
+ const bool all_ok = (res.chunks_failed == 0 && res.chunks_successful > 0);
+ QStringList errs;
+ for (const auto& r : res.results) {
+ if (!r.success)
+ errs.append(r.error);
+ }
+ const QString detail = all_ok ? QString()
+ : QString("%1/%2 chunks failed — %3")
+ .arg(res.chunks_failed)
+ .arg(res.chunks_failed + res.chunks_successful)
+ .arg(errs.isEmpty() ? QStringLiteral("no chunks placed")
+ : errs.join("; "));
+ // A split has one broker order per chunk; record the first for traceability.
+ QString first_id;
+ for (const auto& r : res.results) {
+ if (r.success && !r.order_id.isEmpty()) {
+ first_id = r.order_id;
+ break;
+ }
+ }
+ finalize_approval(po, all_ok, detail, first_id);
+ });
+ async = true;
return {};
}
@@ -480,24 +532,51 @@ void ActionCenter::approve_order(const QString& pending_id) {
return;
}
+ // Claim the row BEFORE executing it. execute_pending() blocks on a broker
+ // round-trip that spins a nested event loop (up to ~8 s/order), which keeps
+ // delivering UI events — so the "is it still pending?" read above and the
+ // status write below used to straddle a window in which a second click, or
+ // Approve All running while a per-row approve was in flight, could send the
+ // same queued order twice. The conditional UPDATE is atomic: exactly one
+ // caller sees one affected row and proceeds.
+ auto claim = Database::instance().execute(
+ "UPDATE pending_orders SET status = 'approving' WHERE id = ? AND status = 'pending'", {pending_id});
+ if (claim.is_err()) {
+ LOG_ERROR(kLog, QString("approve_order claim failed: %1").arg(QString::fromStdString(claim.error())));
+ return;
+ }
+ if (claim.value().numRowsAffected() != 1) {
+ LOG_WARN(kLog, QString("approve_order: %1 was already claimed by another approval — ignoring").arg(pending_id));
+ return;
+ }
+ po.status = QStringLiteral("approving");
+
bool ok = false;
+ bool async = false;
QString err;
- const QString broker_order_id = execute_pending(po, ok, err);
+ const QString broker_order_id = execute_pending(po, ok, err, async);
+ if (async)
+ return; // basket / split: the result callback finalizes the row.
+
+ finalize_approval(po, ok, err, broker_order_id);
+}
+void ActionCenter::finalize_approval(const PendingOrder& po, bool ok, const QString& err,
+ const QString& broker_order_id) {
const QDateTime now = QDateTime::currentDateTime();
auto r = Database::instance().execute("UPDATE pending_orders SET status = ?, approved_at = ?, broker_order_id = ?, "
"rejection_reason = ? WHERE id = ?",
{ok ? "approved" : "rejected", iso(now), broker_order_id,
- ok ? QString() : ("Execution failed: " + err), pending_id});
+ ok ? QString() : ("Execution failed: " + err), po.id});
if (r.is_err())
LOG_ERROR(kLog, QString("approve_order update failed: %1").arg(QString::fromStdString(r.error())));
if (ok) {
- LOG_INFO(kLog, QString("Approved %1 → broker order %2").arg(pending_id, broker_order_id));
- emit order_approved(pending_id, broker_order_id);
+ LOG_INFO(kLog, QString("Approved %1 → broker order %2").arg(po.id, broker_order_id));
+ emit order_approved(po.id, broker_order_id);
} else {
- LOG_WARN(kLog, QString("Approval of %1 executed but broker rejected: %2").arg(pending_id, err));
- emit order_rejected(pending_id, "Execution failed: " + err);
+ LOG_WARN(kLog, QString("Approval of %1 executed but broker rejected: %2").arg(po.id, err));
+ emit order_rejected(po.id, "Execution failed: " + err);
}
emit stats_updated(po.account_id);
}
diff --git a/fincept-qt/src/trading/ActionCenter.h b/fincept-qt/src/trading/ActionCenter.h
index 2905cb1bf..aa9d6898a 100644
--- a/fincept-qt/src/trading/ActionCenter.h
+++ b/fincept-qt/src/trading/ActionCenter.h
@@ -165,7 +165,17 @@ class ActionCenter : public QObject {
// Execute a queued order against UnifiedTrading (placegttorder routes to the
// broker's native gtt_place — never an immediate order). Returns the broker
// order id / GTT id (empty on failure) and sets `ok`/`err`.
- QString execute_pending(const PendingOrder& po, bool& ok, QString& err);
+ //
+ // Basket and split orders are ASYNCHRONOUS: their outcome is not known when
+ // this returns, so they set `async` and finalize the pending row themselves
+ // from their result callback. When `async` is true the caller must not touch
+ // the row — writing "approved" there is exactly the lie this fixes.
+ QString execute_pending(const PendingOrder& po, bool& ok, QString& err, bool& async);
+
+ // Write the terminal status of an approved row and emit the matching signal.
+ // Shared by the synchronous path and the async (basket/split) callbacks so
+ // the audit trail is produced in one place, from a real result.
+ void finalize_approval(const PendingOrder& po, bool ok, const QString& err, const QString& broker_order_id);
};
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/BrokerInterface.h b/fincept-qt/src/trading/BrokerInterface.h
index 943cdddb3..4afcdd06c 100644
--- a/fincept-qt/src/trading/BrokerInterface.h
+++ b/fincept-qt/src/trading/BrokerInterface.h
@@ -5,6 +5,7 @@
#include <QStringList>
+#include <cmath>
#include <memory>
namespace fincept::trading {
@@ -402,7 +403,15 @@ class IBroker {
UnifiedOrder counter;
counter.symbol = p.symbol;
counter.exchange = p.exchange;
- counter.side = (p.quantity > 0) ? OrderSide::Sell : OrderSide::Buy;
+ // Direction comes from `side` FIRST, sign only as a fallback. MetaAPI and
+ // ICICI Direct report an UNSIGNED quantity plus a separate side, so
+ // sign(quantity) alone reads a short as a long and "close all" places
+ // ANOTHER sell — doubling the short at market. Same fix the paper path
+ // already carries (UnifiedTrading::close_all_positions).
+ const QString dir = p.side.toLower();
+ const bool is_short =
+ dir.startsWith(QLatin1String("short")) || dir.startsWith(QLatin1String("sell")) || p.quantity < 0;
+ counter.side = is_short ? OrderSide::Buy : OrderSide::Sell;
counter.quantity = std::abs(p.quantity);
counter.order_type = OrderType::Market;
// Preserve the position's product (CNC/NRML/MTF) — otherwise the close
@@ -430,7 +439,12 @@ class IBroker {
UnifiedOrder counter;
counter.symbol = p.symbol;
counter.exchange = p.exchange;
- counter.side = (p.quantity > 0) ? OrderSide::Sell : OrderSide::Buy;
+ // Direction from `side` first (unsigned-quantity brokers like MetaAPI /
+ // ICICI Direct), sign only as a fallback — see close_all_positions.
+ const QString dir = p.side.toLower();
+ const bool is_short =
+ dir.startsWith(QLatin1String("short")) || dir.startsWith(QLatin1String("sell")) || p.quantity < 0;
+ counter.side = is_short ? OrderSide::Buy : OrderSide::Sell;
counter.quantity = std::abs(p.quantity);
counter.order_type = OrderType::Market;
// Preserve the position's product (CNC/NRML/MTF) — else the close
diff --git a/fincept-qt/src/trading/ExchangeDaemonPool.cpp b/fincept-qt/src/trading/ExchangeDaemonPool.cpp
index a595bdc00..4f96e97a6 100644
--- a/fincept-qt/src/trading/ExchangeDaemonPool.cpp
+++ b/fincept-qt/src/trading/ExchangeDaemonPool.cpp
@@ -15,6 +15,11 @@ namespace fincept::trading {
namespace {
const QString kPoolTag = "ExchangeDaemonPool";
+/// Marks a `responses_` slot whose caller timed out and went away. Never
+/// produced by the daemon, so it can't collide with a real reply. See the
+/// timeout path in call() and the consume in drain_buffer().
+constexpr auto kPoolAbandonedMarker = "__abandoned__";
+
QString pool_resolve_script_path(const QString& relative) {
const QString dir = fincept::python::PythonRunner::instance().scripts_dir();
if (dir.isEmpty())
@@ -72,6 +77,11 @@ void ExchangeDaemonPool::start() {
// has forgotten them with the interpreter.
QMutexLocker lock(&mutex_);
creds_sent_.clear();
+ // Anything still parked here is unclaimable: the ids belong to
+ // the dead interpreter's request stream and no reply is coming.
+ // Waiters aren't stranded — they're on a bounded wait and fall
+ // through to their own timeout.
+ responses_.clear();
});
QStringList args;
@@ -198,6 +208,16 @@ void ExchangeDaemonPool::drain_buffer() {
{
QMutexLocker lock(&mutex_);
+ // A reply whose caller already timed out must be dropped, not
+ // stored: nothing will ever claim it, and these payloads are order
+ // books and OHLC batches (5–50 KB each). call() leaves a tiny
+ // tombstone under the request id when it gives up — see
+ // kPoolAbandonedMarker there — which we consume here.
+ auto existing = responses_.find(id);
+ if (existing != responses_.end() && existing.value().value(kPoolAbandonedMarker).toBool(false)) {
+ responses_.erase(existing);
+ continue;
+ }
responses_[id] = obj;
}
response_ready_.wakeAll();
@@ -252,6 +272,17 @@ QJsonObject ExchangeDaemonPool::call(const QString& exchange, const QString& met
}
response_ready_.wait(&mutex_, 50);
}
+ // Timed out. Two things can leak here and both are handled:
+ // 1. A reply that landed between the last find() and the loop exit —
+ // overwritten by the tombstone below, so its payload is freed now.
+ // 2. A reply that lands *after* we return — the normal case for a slow
+ // exchange call. drain_buffer() sees the tombstone and drops the
+ // payload instead of storing it.
+ // Before this, either case left a full 5–50 KB response object in
+ // responses_ with no caller left to erase it, for the life of the process.
+ // The tombstone itself is a one-key object and is consumed by the late
+ // reply; only a request whose reply never arrives at all leaves one behind.
+ responses_[req_id] = QJsonObject{{kPoolAbandonedMarker, true}};
lock.unlock();
LOG_WARN(kPoolTag, QString("Daemon call timed out: %1/%2").arg(exchange, method));
return {{"error", QString("Daemon call timed out: %1/%2").arg(exchange, method)}};
diff --git a/fincept-qt/src/trading/ExchangeSession.cpp b/fincept-qt/src/trading/ExchangeSession.cpp
index 2dd3744df..dfe578685 100644
--- a/fincept-qt/src/trading/ExchangeSession.cpp
+++ b/fincept-qt/src/trading/ExchangeSession.cpp
@@ -206,6 +206,13 @@ bool ExchangeSession::start_ws(const QString& primary_symbol, const QStringList&
QString script_path;
QStringList args;
+ // Every Python spawn must inherit the shared base env (PYTHONIOENCODING,
+ // PYTHONDONTWRITEBYTECODE, FINCEPT_DATA_DIR, PYTHONPATH, …). This process
+ // previously called neither setProcessEnvironment nor build_python_env(),
+ // so the WS bridge ran without any of them. Broker credentials ride in
+ // this env too — see the SECURITY note below.
+ QProcessEnvironment ws_env = python::PythonRunner::instance().build_python_env();
+
if (session_is_broker_stream(exchange_id_)) {
script_path = session_resolve_script_path("exchange/broker_ws_bridge.py");
if (python_path.isEmpty() || script_path.isEmpty()) {
@@ -230,8 +237,9 @@ bool ExchangeSession::start_ws(const QString& primary_symbol, const QStringList&
user_id = ad.value("client_code").toString();
feed_token = ad.value("feed_token").toString();
}
- if (user_id.isEmpty())
- user_id = creds.api_key;
+ // NOTE: deliberately no `user_id = creds.api_key` fallback here — that
+ // put the api_key back into argv. broker_ws_bridge.py applies the same
+ // fallback internally, where the key never leaves the process.
QStringList broker_symbols = session_to_broker_symbol_args(all_symbols);
if (broker_symbols.isEmpty())
@@ -240,9 +248,27 @@ bool ExchangeSession::start_ws(const QString& primary_symbol, const QStringList&
LOG_ERROR(kSessionTag, "No symbols provided for broker websocket stream");
return false;
}
- args << "-u" << "-B" << script_path << exchange_id_ << creds.api_key << creds.access_token << user_id;
+
+ // ── SECURITY: broker credentials go in the environment, never argv ───
+ // api_key / access_token / feed_token are live broker credentials that
+ // stay valid for the whole trading session. A process command line is
+ // readable by any process running as the same user (WMI
+ // Win32_Process.CommandLine on Windows with no elevation,
+ // /proc/<pid>/cmdline on Linux) and is captured by crash dumps and EDR
+ // telemetry — passing them there undoes SecureStorage entirely.
+ // build_python_env() already carries 17+ other credential keys this
+ // way. broker_ws_bridge.py reads os.environ first and only falls back
+ // to argv so an older caller still works.
+ ws_env.insert(QStringLiteral("BROKER_API_KEY"), creds.api_key);
+ ws_env.insert(QStringLiteral("BROKER_ACCESS_TOKEN"), creds.access_token);
if (!feed_token.isEmpty())
- args << "--feed-token" << feed_token;
+ ws_env.insert(QStringLiteral("BROKER_FEED_TOKEN"), feed_token);
+
+ // Positional arity is preserved (broker, api_key, access_token,
+ // user_id) so the script's argparse contract is unchanged; the two
+ // credential slots are now empty placeholders. user_id is a client
+ // code, not a secret, and may legitimately be empty.
+ args << "-u" << "-B" << script_path << exchange_id_ << QString() << QString() << user_id;
args << "--symbols";
args.append(broker_symbols);
} else {
@@ -257,6 +283,7 @@ bool ExchangeSession::start_ws(const QString& primary_symbol, const QStringList&
}
ws_process_ = new QProcess(this);
+ ws_process_->setProcessEnvironment(ws_env);
connect(ws_process_, &QProcess::readyReadStandardOutput, this, &ExchangeSession::drain_ws_buffer);
connect(ws_process_, &QProcess::readyReadStandardError, this, [this]() {
if (!ws_process_)
diff --git a/fincept-qt/src/trading/OrderValidator.cpp b/fincept-qt/src/trading/OrderValidator.cpp
index 7c590eeba..a886ed93a 100644
--- a/fincept-qt/src/trading/OrderValidator.cpp
+++ b/fincept-qt/src/trading/OrderValidator.cpp
@@ -58,11 +58,14 @@ OrderValidator::ValidationResult OrderValidator::validate_smart(const SmartOrder
else if (!is_valid_exchange(order.exchange))
r.errors.append("Invalid exchange: " + order.exchange);
- // Smart order: position_size is the target. When target is 0 (flatten) the
- // engine derives action from current position, so quantity is optional. When
- // there is no target and no fallback quantity, nothing can be placed.
- if (order.position_size == 0 && order.quantity <= 0)
- r.errors.append("Either position_size or a positive quantity is required");
+ // position_size is the TARGET net position, and 0 is a legitimate target —
+ // "flatten": the engine reads the live book and derives the quantity itself.
+ // An explicit 0 is indistinguishable from an unset one, so requiring a
+ // fallback quantity here would reject every flatten order. The engine already
+ // reports the genuinely-empty case (no position AND no quantity) as a benign
+ // "no action needed", so only a nonsensical negative fallback is an error.
+ if (order.quantity < 0)
+ r.errors.append("Quantity cannot be negative");
if (requires_price(order.order_type) && order.price <= 0)
r.errors.append("Price is required for LIMIT / SL-Limit orders");
diff --git a/fincept-qt/src/trading/PaperMarkService.cpp b/fincept-qt/src/trading/PaperMarkService.cpp
index 87abe1d13..1c36cb6cf 100644
--- a/fincept-qt/src/trading/PaperMarkService.cpp
+++ b/fincept-qt/src/trading/PaperMarkService.cpp
@@ -1,6 +1,7 @@
#include "trading/PaperMarkService.h"
#include "core/logging/Logger.h"
+#include "storage/sqlite/Database.h"
#include "trading/AccountDataStream.h"
#include "trading/AccountManager.h"
#include "trading/DataStreamManager.h"
@@ -8,6 +9,7 @@
#include "trading/PaperTrading.h"
#include "trading/websocket/FyersTickTypes.h"
+#include <QStringList>
#include <QTimer>
namespace fincept::trading {
@@ -184,12 +186,38 @@ void PaperMarkService::flush_prices() {
return;
const auto snapshot = pending_;
pending_.clear();
+
+ // One transaction for the whole flush. Each pt_update_position_price() is a
+ // bare UPDATE, so without this the 1 s timer issued one implicit commit per
+ // position — 40 commits/second on a 40-position book, every second the
+ // market is open.
+ auto& db = fincept::Database::instance();
+ const bool batched = db.begin_transaction().is_ok();
+ if (!batched)
+ LOG_WARN(TAG, "flush_prices: could not open a transaction — falling back to one commit per position");
+
+ QStringList marked;
+ marked.reserve(snapshot.size());
for (auto pit = snapshot.cbegin(); pit != snapshot.cend(); ++pit) {
const QString& pid = pit.key();
for (auto sit = pit.value().cbegin(); sit != pit.value().cend(); ++sit)
pt_update_position_price(pid, sit.key(), sit.value()); // repo guards price <= 0
- emit prices_marked(pid);
+ marked.append(pid);
}
+
+ if (batched) {
+ auto c = db.commit();
+ if (c.is_err()) {
+ LOG_ERROR(TAG, QString("flush_prices commit failed: %1").arg(QString::fromStdString(c.error())));
+ db.rollback();
+ return; // nothing landed — don't tell listeners marks are fresh
+ }
+ }
+
+ // Emit only after the commit, so a slot that re-reads pt_positions sees the
+ // marks it was just told about.
+ for (const auto& pid : marked)
+ emit prices_marked(pid);
}
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/SmartOrderEngine.cpp b/fincept-qt/src/trading/SmartOrderEngine.cpp
index 89b4fb8f0..59a38c4e8 100644
--- a/fincept-qt/src/trading/SmartOrderEngine.cpp
+++ b/fincept-qt/src/trading/SmartOrderEngine.cpp
@@ -20,23 +20,30 @@ QMutex* SmartOrderEngine::get_symbol_lock(const QString& symbol, const QString&
return it->second.get();
}
-QVector<BrokerPosition> SmartOrderEngine::get_positions_cached(IBroker* broker, const BrokerCredentials& creds) {
+ApiResponse<QVector<BrokerPosition>> SmartOrderEngine::get_positions_cached(IBroker* broker,
+ const BrokerCredentials& creds) {
QMutexLocker locker(&cache_mutex_);
qint64 now = QDateTime::currentMSecsSinceEpoch();
auto it = position_cache_.find(creds.access_token);
if (it != position_cache_.end() && (now - it->fetched_at_ms) < CACHE_TTL_MS) {
- return it->positions;
+ return {true, it->positions, {}};
}
locker.unlock();
+ // Propagate a failed fetch. The old code swallowed the error, kept the empty
+ // vector, and cached it with a FRESH timestamp — so a single transient
+ // /positions failure made every smart order for the rest of the TTL read the
+ // book as flat: "adjust to N" bought N more on top of a real long, and
+ // "flatten to 0" reported "No action needed" while the exposure stayed open.
auto resp = broker->get_positions(creds);
- QVector<BrokerPosition> positions;
- if (resp.success && resp.data.has_value())
- positions = resp.data.value();
+ if (!resp.success || !resp.data.has_value()) {
+ return {false, std::nullopt,
+ resp.error.isEmpty() ? QStringLiteral("Broker returned no position data") : resp.error};
+ }
locker.relock();
- position_cache_[creds.access_token] = {positions, QDateTime::currentMSecsSinceEpoch()};
- return positions;
+ position_cache_[creds.access_token] = {resp.data.value(), QDateTime::currentMSecsSinceEpoch()};
+ return {true, resp.data.value(), {}};
}
void SmartOrderEngine::invalidate_cache(const QString& auth_token) {
@@ -71,7 +78,18 @@ ApiResponse<SmartOrderResult> SmartOrderEngine::execute(IBroker* broker, const B
auto* lock = get_symbol_lock(order.symbol, order.exchange, product_type_str(order.product_type));
QMutexLocker locker(lock);
- auto positions = get_positions_cached(broker, creds);
+ // Never trade off an unverified book: a smart order is a DELTA against the
+ // current position, so an unknown position must abort before any delta is
+ // computed rather than default to zero.
+ auto pos_resp = get_positions_cached(broker, creds);
+ if (!pos_resp.success || !pos_resp.data.has_value()) {
+ const QString err =
+ pos_resp.error.isEmpty() ? QStringLiteral("Could not read current positions") : pos_resp.error;
+ LOG_ERROR("SmartOrder", QString("Refusing smart order for %1:%2 — position fetch failed: %3")
+ .arg(order.symbol, order.exchange, err));
+ return {false, std::nullopt, "Cannot verify current position — order not sent: " + err};
+ }
+ const QVector<BrokerPosition>& positions = pos_resp.data.value();
double current =
find_current_position(positions, order.symbol, order.exchange, product_type_str(order.product_type));
diff --git a/fincept-qt/src/trading/SmartOrderEngine.h b/fincept-qt/src/trading/SmartOrderEngine.h
index 861042e28..df9408168 100644
--- a/fincept-qt/src/trading/SmartOrderEngine.h
+++ b/fincept-qt/src/trading/SmartOrderEngine.h
@@ -33,7 +33,13 @@ class SmartOrderEngine {
qint64 fetched_at_ms = 0;
};
- QVector<BrokerPosition> get_positions_cached(IBroker* broker, const BrokerCredentials& creds);
+ // Returns the position book, carrying the fetch failure instead of hiding it.
+ // A failed read MUST NOT be seen as a flat book: the caller trades a delta
+ // against it, so an empty-on-error result would buy the target size on top of
+ // a real position (and silently no-op a flatten). Only successful reads are
+ // cached — caching an error response would poison every smart order for the
+ // rest of the TTL.
+ ApiResponse<QVector<BrokerPosition>> get_positions_cached(IBroker* broker, const BrokerCredentials& creds);
double find_current_position(const QVector<BrokerPosition>& positions, const QString& symbol,
const QString& exchange, const QString& product);
diff --git a/fincept-qt/src/trading/TradingNotificationBridge.cpp b/fincept-qt/src/trading/TradingNotificationBridge.cpp
index 4287e35dd..63ab4707f 100644
--- a/fincept-qt/src/trading/TradingNotificationBridge.cpp
+++ b/fincept-qt/src/trading/TradingNotificationBridge.cpp
@@ -23,7 +23,7 @@ void TradingNotificationBridge::install() {
auto& bus = EventBus::instance();
- sub_placed_ = bus.subscribe(events::kOrderPlaced, [](const QVariantMap& d) {
+ sub_placed_ = bus.subscribe(this, events::kOrderPlaced, [](const QVariantMap& d) {
NotificationRequest req;
req.title = "Order Placed";
req.message = QString("%1 %2 %3 %4 (%5) — %6")
@@ -35,7 +35,7 @@ void TradingNotificationBridge::install() {
NotificationService::instance().send(req);
});
- sub_failed_ = bus.subscribe(events::kOrderFailed, [](const QVariantMap& d) {
+ sub_failed_ = bus.subscribe(this, events::kOrderFailed, [](const QVariantMap& d) {
NotificationRequest req;
req.title = "Order Failed";
req.message =
@@ -46,7 +46,7 @@ void TradingNotificationBridge::install() {
NotificationService::instance().send(req);
});
- sub_cancelled_ = bus.subscribe(events::kAllOrdersCancelled, [](const QVariantMap& d) {
+ sub_cancelled_ = bus.subscribe(this, events::kAllOrdersCancelled, [](const QVariantMap& d) {
NotificationRequest req;
req.title = "All Orders Cancelled";
req.message = QString("%1 cancelled, %2 failed (%3)")
@@ -58,7 +58,7 @@ void TradingNotificationBridge::install() {
NotificationService::instance().send(req);
});
- sub_closed_ = bus.subscribe(events::kAllPositionsClosed, [](const QVariantMap& d) {
+ sub_closed_ = bus.subscribe(this, events::kAllPositionsClosed, [](const QVariantMap& d) {
NotificationRequest req;
req.title = "All Positions Squared Off";
req.message = QString("%1 closed, %2 failed (%3)")
@@ -70,7 +70,7 @@ void TradingNotificationBridge::install() {
NotificationService::instance().send(req);
});
- sub_basket_ = bus.subscribe(events::kBasketCompleted, [](const QVariantMap& d) {
+ sub_basket_ = bus.subscribe(this, events::kBasketCompleted, [](const QVariantMap& d) {
NotificationRequest req;
req.title = "Basket Order Completed";
req.message = QString("%1: %2/%3 placed (%4 failed)")
diff --git a/fincept-qt/src/trading/TradingTypes.h b/fincept-qt/src/trading/TradingTypes.h
index 943cfe648..5a08c9c3c 100644
--- a/fincept-qt/src/trading/TradingTypes.h
+++ b/fincept-qt/src/trading/TradingTypes.h
@@ -287,6 +287,24 @@ struct UnifiedOrder {
double take_profit = 0;
bool amo = false;
QString instrument_token; // broker-specific numeric token (e.g. Zerodha/AliceBlue/Dhan)
+
+ /// Stable idempotency reference for this order INTENT, carried into whichever
+ /// native field the broker deduplicates on (Zerodha/Upstox `tag`, Alpaca
+ /// `client_order_id`, IBKR `cOID`, IIFL `orderUniqueIdentifier`, Saxo
+ /// `ExternalReference`, Dhan `correlationId`, …).
+ ///
+ /// Minted ONCE by UnifiedTrading when an order first enters the routing layer
+ /// (see UnifiedTrading::place_order) and never re-minted while non-empty, so
+ /// re-submitting the SAME UnifiedOrder after BrokerHttp's 8 s client-side
+ /// timeout carries the same reference — the broker rejects it as a duplicate
+ /// instead of creating a second live order. A per-call reference (what
+ /// make_client_order_ref() produces on its own) cannot do that.
+ ///
+ /// Split chunks and basket legs are distinct orders and each carry their own.
+ /// Generated as compact alphanumeric text at 20 chars; brokers with a narrower
+ /// field clamp it with .left(n), which is deterministic and so preserves the
+ /// dedup property. See trading/brokers/BrokerClientOrderId.h.
+ QString client_order_id;
};
struct BrokerPosition {
diff --git a/fincept-qt/src/trading/UnifiedTrading.cpp b/fincept-qt/src/trading/UnifiedTrading.cpp
index 781bb69ef..4a4d94683 100644
--- a/fincept-qt/src/trading/UnifiedTrading.cpp
+++ b/fincept-qt/src/trading/UnifiedTrading.cpp
@@ -3,16 +3,20 @@
#include "trading/UnifiedTrading.h"
#include "core/logging/Logger.h"
+#include "services/workflow/RiskManager.h"
#include "storage/sqlite/Database.h"
#include "trading/AccountManager.h"
#include "trading/DataStreamManager.h"
#include "trading/OrderMatcher.h"
#include "trading/OrderValidator.h"
#include "trading/PaperTrading.h"
+#include "trading/RateLimiter.h"
#include "trading/SmartOrderEngine.h"
#include "trading/StrategyPortfolio.h"
#include "trading/TradingEvents.h"
+#include "trading/brokers/BrokerClientOrderId.h"
+#include <QCoreApplication>
#include <QJsonObject>
#include <QMutexLocker>
#include <QPointer>
@@ -22,9 +26,162 @@
#include <QtConcurrent/QtConcurrentRun>
#include <algorithm>
+#include <cmath>
namespace fincept::trading {
+namespace {
+constexpr const char* kUtLog = "UnifiedTrading";
+
+/// Risk-limit gate shared by every UnifiedTrading path that can reach a broker.
+/// Returns an empty string when the order is allowed, otherwise the reason it was
+/// blocked.
+///
+/// Every RiskLimits field defaults to "unlimited" (0) with short selling allowed,
+/// so an unconfigured install behaves exactly as it did before this gate existed;
+/// only an operator who has set a limit can be rejected by it.
+///
+/// Fails CLOSED: if the check itself throws, the order is refused. A risk gate
+/// that could not be evaluated must never read as a pass.
+QString risk_block_reason(const QString& symbol, OrderSide side, double quantity, double price, bool paper) {
+ try {
+ QString reason;
+ if (workflow::RiskManager::instance().is_order_allowed(symbol, QString::fromLatin1(order_side_str(side)),
+ quantity, price, paper, &reason))
+ return {};
+ return reason.isEmpty() ? QStringLiteral("Blocked by risk limits") : reason;
+ } catch (const std::exception& e) {
+ return QStringLiteral("Risk check failed: ") + QString::fromUtf8(e.what());
+ } catch (...) {
+ return QStringLiteral("Risk check failed (unknown error)");
+ }
+}
+
+/// Broker order-rate gate, applied immediately before a live broker call.
+/// OrderRateLimiter::acquire() sleeps (QThread::msleep) to space orders out, so it
+/// must NEVER run on the GUI thread (P1). The batch paths that actually need it —
+/// basket, split, broadcast, algo deployment — all run under QtConcurrent::run.
+/// The two known main-thread callers are a single user-initiated approval
+/// (ActionCenter) and the MCP tool handler; there we skip the throttle rather than
+/// freeze the UI, which is safe because those are one order at a time.
+void rate_limit_broker(const QString& broker_id) {
+ const auto id = parse_broker_id(broker_id);
+ if (!id)
+ return; // unknown broker string — nothing registered to throttle
+ auto* app = QCoreApplication::instance();
+ if (app && QThread::currentThread() == app->thread()) {
+ LOG_DEBUG(kUtLog, QString("Order rate-limit skipped for %1 — call is on the GUI thread").arg(broker_id));
+ return;
+ }
+ OrderRateLimiter::instance().acquire(*id);
+}
+
+/// Stamp an order's idempotency reference exactly ONCE, at the point it enters
+/// the routing layer. A non-empty value is never overwritten, so re-submitting
+/// the SAME UnifiedOrder after BrokerHttp's 8 s client-side timeout reaches the
+/// broker with the reference it already used — the broker rejects the retry as a
+/// duplicate instead of opening a second live position. Minting inside each
+/// broker (what make_client_order_ref() does on its own) cannot achieve that,
+/// because it produces a fresh value on every attempt.
+void stamp_client_order_id(UnifiedOrder& order) {
+ if (order.client_order_id.isEmpty())
+ order.client_order_id = make_client_order_ref(20);
+}
+
+/// Fill the caller-owned identity fields of a modify request from the RESTING
+/// order, then return an empty string. On failure, returns the reason the modify
+/// must be refused.
+///
+/// Why this exists: Kotak and Tradejini implement modify as a FULL REPLACE —
+/// every field they transmit overwrites the resting order. They used to default
+/// the missing ones, and the worst of those defaults was `side` ("B" / "buy"):
+/// re-pricing a resting SELL or stop-loss rewrote it as a BUY, turning an exit
+/// into a new long. Both now hard-fail instead of guessing. Every caller in the
+/// terminal (order blotter, workflow node) sends only {quantity, price}, so
+/// without this hydration those two brokers can no longer modify anything.
+///
+/// Caller-supplied values ALWAYS win — this only fills gaps.
+///
+/// The same concept is read under different key names across the 22 brokers, so
+/// each value is written under every spelling some broker reads. Brokers ignore
+/// keys they don't read, so the duplicate spellings are inert:
+/// side -> "side" (kotak, tradejini)
+/// symbol -> "symbol" (flattrade, kotak, shoonya, tradejini)
+/// exchange -> "exchange", "exchange_code" (flattrade/groww/kotak/shoonya, icicidirect)
+/// product -> "product", "productType" (kotak, iifl)
+/// order type -> "order_type", "orderType", "type" (see the three families below)
+///
+/// Deliberately NOT written:
+/// "variety" — it looks like a product slot but is the Kite / AngelOne order
+/// VARIETY (regular|amo|co, NORMAL|STOPLOSS|AMO). Zerodha puts it in the
+/// request path, so writing a product there would issue
+/// PUT /orders/MIS/<id>; AngelOne already recovers the real variety from its
+/// own order book.
+/// "segment" — Groww's CASH/FNO segment, not an exchange. Groww already
+/// derives it from "exchange" when absent, which this does supply.
+QString hydrate_modify_fields(IBroker& broker, const BrokerCredentials& creds, const QString& order_id,
+ QJsonObject& mods) {
+ // Every key some broker reads for one of the five hydratable concepts.
+ static const char* const kHydratedKeys[] = {"side", "symbol", "exchange", "exchange_code",
+ "product", "productType", "order_type", "orderType",
+ "type"};
+ auto blank = [&mods](const char* key) {
+ return mods.value(QString::fromLatin1(key)).toString().trimmed().isEmpty();
+ };
+
+ // If the caller already supplied everything, skip the round trip entirely.
+ bool needs_fill = false;
+ for (const char* k : kHydratedKeys) {
+ if (blank(k)) {
+ needs_fill = true;
+ break;
+ }
+ }
+ if (!needs_fill)
+ return {};
+
+ const QString broker_name = QString::fromLatin1(broker.name());
+ auto resp = broker.get_orders(creds);
+ if (!resp.success || !resp.data.has_value()) {
+ // Refuse rather than dispatch a half-populated map — a partially
+ // populated full-replace modify is the exact failure mode this guards.
+ return QString("Cannot modify order %1: %2's order book could not be read (%3)")
+ .arg(order_id, broker_name, resp.error.isEmpty() ? QStringLiteral("no detail") : resp.error);
+ }
+
+ const BrokerOrderInfo* resting = nullptr;
+ for (const auto& o : *resp.data) {
+ if (o.order_id == order_id || (!o.exchange_order_id.isEmpty() && o.exchange_order_id == order_id)) {
+ resting = &o;
+ break;
+ }
+ }
+ if (!resting) {
+ return QString("Cannot modify order %1: it is not in %2's order book (already filled or cancelled?)")
+ .arg(order_id, broker_name);
+ }
+
+ auto fill = [&mods, &blank](const char* key, const QString& value) {
+ if (!value.trimmed().isEmpty() && blank(key))
+ mods[QString::fromLatin1(key)] = value;
+ };
+ fill("side", resting->side);
+ fill("symbol", resting->symbol);
+ fill("exchange", resting->exchange);
+ fill("exchange_code", resting->exchange);
+ fill("product", resting->product_type);
+ fill("productType", resting->product_type);
+ fill("order_type", resting->order_type);
+ fill("orderType", resting->order_type);
+ fill("type", resting->order_type);
+
+ LOG_DEBUG(kUtLog, QString("Modify %1 on %2 hydrated from the resting order: %3 %4 %5 %6/%7")
+ .arg(order_id, broker_name, resting->side, resting->symbol, resting->exchange,
+ resting->product_type, resting->order_type));
+ return {};
+}
+} // namespace
+
UnifiedTrading& UnifiedTrading::instance() {
static UnifiedTrading ut;
return ut;
@@ -91,10 +248,13 @@ UnifiedOrderResponse UnifiedTrading::place_order(const UnifiedOrder& order) {
return {false, "", "No active trading session. Call init_session first.", ""};
}
+ UnifiedOrder routed = order;
+ stamp_client_order_id(routed);
+
if (session_->mode == "paper") {
- return place_paper_order(*session_, order);
+ return place_paper_order(*session_, routed);
}
- return place_live_order(*session_, order);
+ return place_live_order(*session_, routed);
}
UnifiedOrderResponse UnifiedTrading::place_paper_order(const TradingSession& session, const UnifiedOrder& order) {
@@ -145,6 +305,18 @@ UnifiedOrderResponse UnifiedTrading::place_live_order(const TradingSession& sess
return {false, "", "No credentials for " + session.broker + ". Please authenticate.", "live"};
}
+ // Legacy session path bypasses the account-aware place_order, so it carries
+ // its own risk gate — this reaches a real broker.
+ const QString blocked = risk_block_reason(order.symbol, order.side, order.quantity, order.price, /*paper=*/false);
+ if (!blocked.isEmpty()) {
+ LOG_INFO(kUtLog, QString("Risk limit rejected %1 %2 x%3 on %4: %5")
+ .arg(QString::fromLatin1(order_side_str(order.side)), order.symbol)
+ .arg(order.quantity)
+ .arg(session.broker, blocked));
+ return {false, "", "Risk check failed: " + blocked, "live"};
+ }
+
+ rate_limit_broker(session.broker);
auto result = broker->place_order(creds, order);
return {result.success, result.order_id, result.error, "live"};
}
@@ -170,6 +342,7 @@ UnifiedOrderResponse UnifiedTrading::cancel_order(const QString& order_id) {
return {false, "", "Broker not found", "live"};
auto creds = broker->load_credentials();
+ rate_limit_broker(session_->broker);
auto result = broker->cancel_order(creds, order_id);
return {result.success, order_id, result.error, "live"};
}
@@ -191,6 +364,23 @@ UnifiedOrderResponse UnifiedTrading::place_order(const QString& account_id, cons
return {false, "", "Validation failed: " + err, account.trading_mode};
}
+ // Risk limits. This is the terminal's single order choke point — every
+ // broadcast, approval and workflow order funnels through here — so the gate
+ // lives here rather than in each caller. Defaults are wide open (see
+ // RiskLimits), so nothing that works today starts failing; a rejection only
+ // happens when an operator has actually configured a limit, and is logged so
+ // they can see which one bit.
+ const QString risk_err =
+ risk_block_reason(order.symbol, order.side, order.quantity, order.price, account.trading_mode == "paper");
+ if (!risk_err.isEmpty()) {
+ LOG_INFO(kUtLog, QString("Risk limit rejected %1 %2 x%3 on account %4: %5")
+ .arg(QString::fromLatin1(order_side_str(order.side)), order.symbol)
+ .arg(order.quantity)
+ .arg(account_id, risk_err));
+ publish(OrderFailedEvent{account_id, "PLACE", order.symbol, risk_err, account.trading_mode});
+ return {false, "", "Risk check failed: " + risk_err, account.trading_mode};
+ }
+
// Quantity freeze check (Phase 3 §17). Exchanges cap the max quantity per
// single order (e.g. NSE NIFTY futures = 1800). place_order is synchronous;
// an auto-split is inherently async (place_split_orders runs on a worker
@@ -209,8 +399,15 @@ UnifiedOrderResponse UnifiedTrading::place_order(const QString& account_id, cons
return {false, "", err, account.trading_mode};
}
- UnifiedOrderResponse resp = (account.trading_mode == "paper") ? place_paper_order_for_account(account_id, order)
- : place_live_order_for_account(account_id, order);
+ // Stamp the idempotency reference here — this is the terminal's single order
+ // choke point, so every routed order carries one exactly once. Re-submitting
+ // the same UnifiedOrder (a retry after an 8 s BrokerHttp timeout) keeps the
+ // original reference; a freshly built order gets a new one.
+ UnifiedOrder routed = order;
+ stamp_client_order_id(routed);
+
+ UnifiedOrderResponse resp = (account.trading_mode == "paper") ? place_paper_order_for_account(account_id, routed)
+ : place_live_order_for_account(account_id, routed);
if (resp.success) {
publish(OrderPlacedEvent{account_id, resp.order_id, order.symbol, order.exchange, order.side, order.quantity,
@@ -240,6 +437,7 @@ UnifiedOrderResponse UnifiedTrading::cancel_order(const QString& account_id, con
return {false, "", "Broker not found: " + account.broker_id, "live"};
auto creds = AccountManager::instance().load_credentials(account_id);
+ rate_limit_broker(account.broker_id);
auto result = broker->cancel_order(creds, order_id);
return {result.success, order_id, result.error, "live"};
}
@@ -258,7 +456,25 @@ UnifiedOrderResponse UnifiedTrading::modify_order(const QString& account_id, con
return {false, "", "Broker not found: " + account.broker_id, "live"};
auto creds = AccountManager::instance().load_credentials(account_id);
- auto result = broker->modify_order(creds, order_id, modifications);
+
+ // Hydrate side/symbol/exchange/product/order_type from the resting order
+ // before dispatching. Several brokers replace the whole order on modify, so
+ // a map carrying only {quantity, price} either gets rejected (Kotak,
+ // Tradejini) or silently rewrites the fields the caller never touched
+ // (IIFL's MIS/MARKET defaults, AliceBlue's LIMIT default).
+ //
+ // This costs one extra broker round trip per modify. Both call sites
+ // (EquityTradingScreen::async_modify_order, the workflow modify-order node)
+ // already run under QtConcurrent::run, so it never blocks the GUI thread.
+ QJsonObject mods = modifications;
+ const QString hydrate_err = hydrate_modify_fields(*broker, creds, order_id, mods);
+ if (!hydrate_err.isEmpty()) {
+ LOG_ERROR(kUtLog, QString("Modify refused on account %1: %2").arg(account_id, hydrate_err));
+ return {false, order_id, hydrate_err, "live"};
+ }
+
+ rate_limit_broker(account.broker_id);
+ auto result = broker->modify_order(creds, order_id, mods);
return {result.success, order_id, result.error, "live"};
}
@@ -330,6 +546,10 @@ UnifiedOrderResponse UnifiedTrading::place_live_order_for_account(const QString&
if (creds.access_token.isEmpty())
return {false, "", "No credentials for account " + account.display_name + ". Please authenticate.", "live"};
+ // Space orders out to the broker's published per-second cap. Without this a
+ // broadcast / basket / algo loop fires as fast as the network allows and the
+ // API key gets throttled or banned mid-batch.
+ rate_limit_broker(account.broker_id);
auto result = broker->place_order(creds, order);
return {result.success, result.order_id, result.error, "live"};
}
@@ -493,6 +713,27 @@ ApiResponse<SmartOrderResult> UnifiedTrading::place_smart_order(const QString& a
if (account.account_id.isEmpty())
return {false, std::nullopt, "Account not found: " + account_id};
+ // Pre-flight validation. Smart orders previously reached the broker with no
+ // checks at all — only the plain UnifiedOrder overload was wired.
+ auto vr = OrderValidator::validate_smart(order);
+ if (!vr.valid)
+ return {false, std::nullopt, "Validation failed: " + vr.errors.join("; ")};
+
+ // Risk gate on the TARGET exposure: the engine computes the delta from the
+ // live book, so the size the account will be carrying is the meaningful
+ // quantity to check (falling back to the explicit quantity when the target is
+ // a flatten). Defaults are unlimited — see risk_block_reason.
+ const double risk_qty = (order.position_size != 0.0) ? std::abs(order.position_size) : order.quantity;
+ const QString risk_err = risk_block_reason(order.symbol, order.action, risk_qty, order.price,
+ account.trading_mode == "paper");
+ if (!risk_err.isEmpty()) {
+ LOG_INFO(kUtLog, QString("Risk limit rejected smart order %1 (target %2) on account %3: %4")
+ .arg(order.symbol)
+ .arg(order.position_size)
+ .arg(account_id, risk_err));
+ return {false, std::nullopt, "Risk check failed: " + risk_err};
+ }
+
if (account.trading_mode == "paper") {
// Paper mode: get paper positions, calculate delta, place paper order
auto positions = pt_get_positions(account.paper_portfolio_id);
@@ -561,6 +802,7 @@ ApiResponse<SmartOrderResult> UnifiedTrading::place_smart_order(const QString& a
return {false, std::nullopt, "Broker not found: " + account.broker_id};
auto creds = AccountManager::instance().load_credentials(account_id);
+ rate_limit_broker(account.broker_id);
return SmartOrderEngine::instance().execute(broker, creds, order);
}
@@ -611,6 +853,25 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
return;
}
+ // Pre-flight validation. validate_basket had zero call sites, so a basket
+ // reached the broker with no checks whatsoever — a leg with a bad exchange or
+ // a zero quantity was only ever rejected by the broker itself, one leg at a
+ // time, after the earlier legs had already filled.
+ auto bvr = OrderValidator::validate_basket(basket);
+ if (!bvr.valid) {
+ const QString err = bvr.errors.join("; ");
+ BasketOrderResult result;
+ result.total = basket.orders.size();
+ for (const auto& order : basket.orders) {
+ result.results.append({order.symbol, order.exchange, false, {}, "Validation failed: " + err});
+ result.failed++;
+ }
+ LOG_WARN(kUtLog, QString("Basket rejected by validation for %1: %2").arg(account_id, err));
+ if (callback)
+ callback(result);
+ return;
+ }
+
const bool is_paper = (account.trading_mode == "paper");
// Resolve broker + credentials up front on the calling thread (consistent
@@ -656,6 +917,12 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
QVector<UnifiedOrder> orders = basket.orders;
std::stable_partition(orders.begin(), orders.end(), [](const UnifiedOrder& o) { return o.side == OrderSide::Buy; });
+ // Basket legs bypass place_order, so stamp each leg's idempotency reference
+ // here. Every leg is a distinct order and therefore gets its own reference —
+ // sharing one would make the broker dedupe legs 2..N away.
+ for (auto& o : orders)
+ stamp_client_order_id(o);
+
// Paper MARKET legs need a fill price, but basket builders (BasketOrdersDialog,
// options strategies) leave price = 0 on market legs. Backfill from the account
// stream's quote cache HERE on the calling (GUI) thread — cached_quote() is
@@ -676,8 +943,9 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
QPointer<UnifiedTrading> self = this;
const QString basket_strategy = basket.strategy_name;
- (void)QtConcurrent::run(
- [self, account_id, basket_strategy, orders, is_paper, broker, creds, paper_portfolio_id, callback]() {
+ const QString broker_id = account.broker_id;
+ (void)QtConcurrent::run([self, account_id, basket_strategy, orders, is_paper, broker, broker_id, creds,
+ paper_portfolio_id, callback]() {
BasketOrderResult result;
result.total = orders.size();
@@ -692,6 +960,20 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
r.symbol = order.symbol;
r.exchange = order.exchange;
+ // Basket legs bypass place_order, so the risk gate is applied per leg
+ // here. A blocked leg fails on its own; the rest of the basket still
+ // goes out, matching how a broker-rejected leg already behaves.
+ const QString leg_risk = risk_block_reason(order.symbol, order.side, order.quantity, order.price, is_paper);
+ if (!leg_risk.isEmpty()) {
+ LOG_INFO(kUtLog, QString("Risk limit rejected basket leg %1 on account %2: %3")
+ .arg(order.symbol, account_id, leg_risk));
+ r.success = false;
+ r.error = "Risk check failed: " + leg_risk;
+ result.failed++;
+ result.results.append(r);
+ continue;
+ }
+
if (is_paper) {
// Store the BARE symbol + forward exchange/product (same contract as
// place_paper_order_for_account) so each leg marks to market and
@@ -728,6 +1010,8 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
}
}
} else {
+ // Worker thread — safe to block on the broker's per-second cap.
+ rate_limit_broker(broker_id);
OrderPlaceResponse resp = broker->place_order(creds, order);
r.success = resp.success;
r.order_id = resp.order_id;
@@ -779,7 +1063,45 @@ void UnifiedTrading::place_split_orders(const QString& account_id, const SplitOr
return;
}
- const int total = static_cast<int>(request.base_order.quantity);
+ // UnifiedOrder::quantity is a double. Truncating it to int made any fractional
+ // quantity below 1 collapse to total = 0: the chunk loop never ran, and the
+ // callback fired with chunks_successful == 0 AND chunks_failed == 0 — reported
+ // as neither success nor failure, so the user believed the order had gone out.
+ // Reject anything that is not a whole quantity of at least 1, and ROUND (not
+ // truncate) the conversion so a 9.9999 carried in from a float calculation is
+ // 10 chunks' worth, not 9.
+ const double raw_qty = request.base_order.quantity;
+ const long long rounded_qty = std::llround(raw_qty);
+ if (raw_qty < 1.0 || std::fabs(raw_qty - static_cast<double>(rounded_qty)) > 1e-6) {
+ SplitOrderResult result;
+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},
+ QString("Invalid quantity %1 for a split order — it must be a whole number of at "
+ "least 1.")
+ .arg(raw_qty)});
+ result.chunks_failed++;
+ if (callback)
+ callback(result);
+ return;
+ }
+
+ // Risk gate on the FULL quantity (a split is one intent, not N independent
+ // orders) — split chunks bypass place_order entirely. Defaults are unlimited.
+ const QString split_risk =
+ risk_block_reason(request.base_order.symbol, request.base_order.side, raw_qty, request.base_order.price,
+ account.trading_mode == "paper");
+ if (!split_risk.isEmpty()) {
+ LOG_INFO(kUtLog, QString("Risk limit rejected split order %1 on account %2: %3")
+ .arg(request.base_order.symbol, account_id, split_risk));
+ SplitOrderResult result;
+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},
+ "Risk check failed: " + split_risk});
+ result.chunks_failed++;
+ if (callback)
+ callback(result);
+ return;
+ }
+
+ const int total = static_cast<int>(rounded_qty);
const int split_size = request.split_size;
const int num_full = total / split_size;
const int remainder = total % split_size;
@@ -852,10 +1174,11 @@ void UnifiedTrading::place_split_orders(const QString& account_id, const SplitOr
}
}
const int delay_ms = request.delay_between_ms;
+ const QString broker_id = account.broker_id;
QPointer<UnifiedTrading> self = this;
(void)QtConcurrent::run(
- [self, base, chunk_qtys, delay_ms, is_paper, broker, creds, paper_portfolio_id, callback]() {
+ [self, base, chunk_qtys, delay_ms, is_paper, broker, broker_id, creds, paper_portfolio_id, callback]() {
SplitOrderResult result;
for (int i = 0; i < chunk_qtys.size(); ++i) {
@@ -864,6 +1187,10 @@ void UnifiedTrading::place_split_orders(const QString& account_id, const SplitOr
UnifiedOrder chunk = base;
chunk.quantity = chunk_qtys.at(i);
+ // Each chunk is a SEPARATE live order, so it needs its own
+ // idempotency reference. Inheriting the base order's would make
+ // the broker dedupe chunks 2..N and only the first would fill.
+ chunk.client_order_id = make_client_order_ref(20);
BasketOrderResult::OrderResult r;
r.symbol = chunk.symbol;
@@ -902,6 +1229,8 @@ void UnifiedTrading::place_split_orders(const QString& account_id, const SplitOr
}
}
} else {
+ // Worker thread — safe to block on the broker's per-second cap.
+ rate_limit_broker(broker_id);
OrderPlaceResponse resp = broker->place_order(creds, chunk);
r.success = resp.success;
r.order_id = resp.order_id;
diff --git a/fincept-qt/src/trading/auth/RedirectServer.cpp b/fincept-qt/src/trading/auth/RedirectServer.cpp
index 45bd05181..6cdaa245d 100644
--- a/fincept-qt/src/trading/auth/RedirectServer.cpp
+++ b/fincept-qt/src/trading/auth/RedirectServer.cpp
@@ -1,12 +1,17 @@
#include "trading/auth/RedirectServer.h"
+#include "auth/ConstantTime.h"
+#include "auth/LoopbackGuard.h"
#include "core/logging/Logger.h"
#include <QHostAddress>
+#include <QRandomGenerator>
#include <QTcpSocket>
#include <QUrl>
#include <QUrlQuery>
+#include <memory>
+
namespace fincept::trading::auth {
namespace {
@@ -18,8 +23,31 @@ constexpr const char* kResponseHtml =
"div{text-align:center}h1{color:#d97706;font-size:20px}p{color:#94a3b8}</style>"
"</head><body><div><h1>Login captured</h1>"
"<p>You can close this tab and return to Fincept Terminal.</p></div></body></html>";
+
+// 128 bits of CSPRNG output, hex-encoded. QRandomGenerator::system() is the
+// OS entropy source — the non-system generator is seeded deterministically and
+// must never be used for a security nonce.
+QString make_state_nonce() {
+ quint32 words[4];
+ QRandomGenerator::system()->fillRange(words);
+ QByteArray raw(reinterpret_cast<const char*>(words), static_cast<qsizetype>(sizeof(words)));
+ return QString::fromLatin1(raw.toHex());
}
+void write_page(QTcpSocket* sock, int status, const char* status_text, const QByteArray& body) {
+ QByteArray response = "HTTP/1.1 " + QByteArray::number(status) + ' ' + status_text + "\r\n";
+ response += "Content-Type: text/html; charset=utf-8\r\n";
+ response += "Content-Length: " + QByteArray::number(body.size()) + "\r\n";
+ response += "Cache-Control: no-store\r\n";
+ response += "X-Content-Type-Options: nosniff\r\n";
+ response += "Referrer-Policy: no-referrer\r\n";
+ response += "Connection: close\r\n\r\n";
+ response += body;
+ sock->write(response);
+ sock->flush();
+}
+} // namespace
+
RedirectServer::RedirectServer(QObject* parent)
: QObject(parent), server_(new QTcpServer(this)), timeout_timer_(new QTimer(this)) {
timeout_timer_->setSingleShot(true);
@@ -35,6 +63,7 @@ bool RedirectServer::start(quint16 preferred_port, int timeout_seconds) {
if (server_->isListening())
server_->close();
+ // Loopback only — never QHostAddress::Any. Do not change this.
if (!server_->listen(QHostAddress::LocalHost, preferred_port)) {
LOG_WARN("RedirectServer", QString("Port %1 busy - falling back to ephemeral").arg(preferred_port));
if (!server_->listen(QHostAddress::LocalHost, 0)) {
@@ -43,6 +72,7 @@ bool RedirectServer::start(quint16 preferred_port, int timeout_seconds) {
}
}
port_ = server_->serverPort();
+ state_ = make_state_nonce(); // fresh per attempt — never reuse across logins
timeout_timer_->start(timeout_seconds * 1000);
LOG_INFO("RedirectServer", QString("Listening on 127.0.0.1:%1").arg(port_));
return true;
@@ -58,46 +88,99 @@ void RedirectServer::handle_new_connection() {
QTcpSocket* sock = server_->nextPendingConnection();
if (!sock)
return;
+ connect(sock, &QTcpSocket::disconnected, sock, &QTcpSocket::deleteLater);
+
+ // The request can arrive in several TCP segments; accumulate until the
+ // header block is complete, because the guards below read headers, not just
+ // the request line.
+ auto buffer = std::make_shared<QByteArray>();
+ connect(sock, &QTcpSocket::readyRead, this, [this, sock, buffer]() {
+ buffer->append(sock->readAll());
+ if (buffer->indexOf("\r\n\r\n") < 0 && buffer->indexOf("\n\n") < 0) {
+ if (buffer->size() < 16384)
+ return; // wait for the rest of the head
+ write_page(sock, 431, "Request Header Fields Too Large", QByteArrayLiteral("too large"));
+ sock->disconnectFromHost();
+ return;
+ }
- connect(sock, &QTcpSocket::readyRead, this, [this, sock]() {
- const QByteArray request = sock->readAll();
- const int line_end = request.indexOf("\r\n");
- const QByteArray first_line = (line_end >= 0) ? request.left(line_end) : request;
+ const QByteArray request = *buffer;
+ const qsizetype line_end = request.indexOf('\n');
+ QByteArray first_line = (line_end >= 0) ? request.left(line_end) : request;
+ if (first_line.endsWith('\r'))
+ first_line.chop(1);
const QList<QByteArray> parts = first_line.split(' ');
- QString token;
- QString error_msg;
- if (parts.size() >= 2) {
- const QUrl url(QStringLiteral("http://localhost") + QString::fromLatin1(parts.at(1)));
- const QUrlQuery q(url);
- token = q.queryItemValue("request_token");
- if (token.isEmpty())
- token = q.queryItemValue("auth_code");
- if (token.isEmpty()) {
- const QString err = q.queryItemValue("error");
- error_msg = err.isEmpty() ? QStringLiteral("Token missing in redirect") : err;
+ // ── Gate 1: only a browser redirect, i.e. a GET ──────────────────────
+ if (parts.size() < 2 || parts.at(0) != "GET") {
+ LOG_WARN("RedirectServer", "Rejected non-GET request on the OAuth callback port");
+ write_page(sock, 405, "Method Not Allowed", QByteArrayLiteral("method not allowed"));
+ sock->disconnectFromHost();
+ return;
+ }
+
+ // ── Gate 2: Host + fetch-metadata (see auth/LoopbackGuard.h) ─────────
+ // Fully qualified: this file lives in fincept::trading::auth, and the
+ // helper lives in fincept::auth — two different `auth` namespaces.
+ const auto check = ::fincept::auth::check_loopback_request(request, port_);
+ if (!check.allowed) {
+ LOG_WARN("RedirectServer", "Rejected OAuth callback: " + check.reason);
+ write_page(sock, 403, "Forbidden", QByteArrayLiteral("forbidden"));
+ sock->disconnectFromHost();
+ return;
+ }
+
+ const QUrl url(QStringLiteral("http://127.0.0.1") + QString::fromLatin1(parts.at(1)));
+ const QUrlQuery q(url);
+
+ QString token = q.queryItemValue("request_token");
+ if (token.isEmpty())
+ token = q.queryItemValue("auth_code");
+
+ // ── Gate 3: the state nonce ──────────────────────────────────────────
+ // The only gate that also stops a cross-site *top-level* navigation
+ // (window.open to the fixed port), which looks identical to the real
+ // redirect at the header level.
+ if (!token.isEmpty()) {
+ const QString echoed_state = q.queryItemValue("state");
+ if (echoed_state.isEmpty()) {
+ if (require_state_) {
+ LOG_WARN("RedirectServer", "Rejected OAuth callback: no state nonce echoed back");
+ write_page(sock, 403, "Forbidden", QByteArrayLiteral("forbidden"));
+ sock->disconnectFromHost();
+ emit error(QStringLiteral("Login rejected: missing CSRF state"));
+ return;
+ }
+ LOG_WARN("RedirectServer",
+ "OAuth callback carried no state nonce — the authorize URL is not sending state(). "
+ "Any page the user has open can forge this callback until it does.");
+ } else if (!::fincept::auth::constant_time_equals(echoed_state, state_)) {
+ LOG_WARN("RedirectServer", "Rejected OAuth callback: state nonce mismatch");
+ write_page(sock, 403, "Forbidden", QByteArrayLiteral("forbidden"));
+ sock->disconnectFromHost();
+ emit error(QStringLiteral("Login rejected: CSRF state mismatch"));
+ return;
}
- } else {
- error_msg = QStringLiteral("Malformed request");
}
- const QByteArray body(kResponseHtml);
- QByteArray response = "HTTP/1.1 200 OK\r\n";
- response += "Content-Type: text/html; charset=utf-8\r\n";
- response += "Content-Length: " + QByteArray::number(body.size()) + "\r\n";
- response += "Connection: close\r\n\r\n";
- response += body;
- sock->write(response);
- sock->flush();
+ QString error_msg;
+ if (token.isEmpty()) {
+ const QString err = q.queryItemValue("error");
+ error_msg = err.isEmpty() ? QStringLiteral("Token missing in redirect") : err;
+ }
+
+ write_page(sock, 200, "OK", QByteArray(kResponseHtml));
sock->disconnectFromHost();
- connect(sock, &QTcpSocket::disconnected, sock, &QTcpSocket::deleteLater);
- timeout_timer_->stop();
if (!token.isEmpty()) {
LOG_INFO("RedirectServer", "Captured auth token");
+ timeout_timer_->stop();
server_->close();
emit request_token_received(token);
} else {
+ // Keep listening: this was a stray request (favicon, a probe, a
+ // provider error page) and the real redirect may still be coming.
+ // Stopping the timeout here would leave the dialog waiting forever.
LOG_WARN("RedirectServer", "No token in redirect: " + error_msg);
emit error(error_msg);
}
diff --git a/fincept-qt/src/trading/auth/RedirectServer.h b/fincept-qt/src/trading/auth/RedirectServer.h
index 2a461f56f..b93482548 100644
--- a/fincept-qt/src/trading/auth/RedirectServer.h
+++ b/fincept-qt/src/trading/auth/RedirectServer.h
@@ -6,6 +6,19 @@
// port and exposes it via port().
//
// Owned by the dialog for the duration of one browser-login attempt.
+//
+// SECURITY — this listener accepts a credential from the browser on a fixed,
+// guessable port. Three gates protect it (see auth/LoopbackGuard.h for the
+// threat model):
+// 1. Loopback bind — no other host can reach it.
+// 2. Host + Sec-Fetch-* validation — rejects DNS-rebinding and any
+// cross-origin subresource injection (`<img src="http://127.0.0.1:5010/
+// ?request_token=...">` from any page the user has open).
+// 3. A `state` nonce — the only gate that also stops a cross-site *top-level*
+// navigation, which is indistinguishable from the real redirect at the
+// header level. The caller must put state() into the provider's authorize
+// URL and then call set_require_state(true); until it does, a state-less
+// callback is accepted with a loud warning.
#include <QObject>
#include <QTcpServer>
@@ -21,11 +34,21 @@ class RedirectServer : public QObject {
// Starts listening. Returns true on success. Updates port() on ephemeral fallback.
// timeout_seconds triggers timeout() if no request arrives in that window.
+ // Also mints a fresh state() nonce for this attempt.
bool start(quint16 preferred_port = 5010, int timeout_seconds = 120);
void stop();
quint16 port() const { return port_; }
+ /// Per-attempt CSRF nonce. Append it to the provider's authorize URL as
+ /// `state=<value>`; OAuth providers echo it back on the redirect.
+ /// Valid only after start().
+ QString state() const { return state_; }
+
+ /// When true, a callback without a matching `state` is rejected outright.
+ /// Turn this on once the authorize URL actually carries state().
+ void set_require_state(bool require) { require_state_ = require; }
+
signals:
void request_token_received(const QString& token);
void error(const QString& message);
@@ -39,6 +62,8 @@ class RedirectServer : public QObject {
QTcpServer* server_ = nullptr;
QTimer* timeout_timer_ = nullptr;
quint16 port_ = 0;
+ QString state_;
+ bool require_state_ = false;
};
} // namespace fincept::trading::auth
diff --git a/fincept-qt/src/trading/brokers/BrokerClientOrderId.h b/fincept-qt/src/trading/brokers/BrokerClientOrderId.h
new file mode 100644
index 000000000..b295c1abd
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/BrokerClientOrderId.h
@@ -0,0 +1,42 @@
+#pragma once
+// BrokerClientOrderId — per-attempt idempotency reference for order placement.
+//
+// BrokerHttp aborts a request client-side after 8 s and reports "Request timed
+// out", but a timeout is not proof the order was rejected: the broker may have
+// accepted it and only the response was lost. The trader (or the algo engine)
+// then retries and a *second* live order is created.
+//
+// Nearly every broker API deduplicates on a caller-supplied reference —
+// Alpaca client_order_id, IBKR cOID, Zerodha/Upstox/Tradier/Motilal tag,
+// IIFL orderUniqueIdentifier, Shoonya/Flattrade remarks, AliceBlue orderTag,
+// ICICI user_remark, Saxo ExternalReference, Groww order_reference_id,
+// Dhan correlationId, FivePaisa RemoteOrderID. Sending a constant ("fincept")
+// buys nothing; sending a genuinely unique value per order turns the duplicate
+// into a broker-side rejection instead of a second position.
+//
+// TODO(cross-file): UnifiedOrder (src/trading/TradingTypes.h) has no field to
+// carry this, so the reference is minted here and therefore differs on every
+// attempt. That deduplicates nothing across a *retry* — it only makes each
+// submission individually identifiable in the broker's order book, which is
+// what the reconciliation path needs today. Add `QString client_order_id` to
+// UnifiedOrder, populate it once at the call site that builds the order, and
+// change these helpers to prefer it when non-empty; only then does a retry of
+// the same intent collapse to one order broker-side.
+
+#include <QString>
+#include <QUuid>
+
+namespace fincept::trading {
+
+// Compact, purely alphanumeric reference (several Indian broker APIs reject
+// punctuation in their tag/remark fields), e.g. "fin7f3a9c1e4b2d9081".
+//
+// `max_len` clamps to the narrowest field a given broker accepts — Motilal's
+// tag is 10 chars, Zerodha's/ICICI's 20, Dhan's 25, Saxo's 50, Alpaca's 128.
+// Keep at least 12 so the random tail stays wide enough to not collide.
+inline QString make_client_order_ref(int max_len = 20) {
+ const QString id = QStringLiteral("fin") + QUuid::createUuid().toString(QUuid::Id128);
+ return (max_len > 0 && id.size() > max_len) ? id.left(max_len) : id;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/BrokerHttp.cpp b/fincept-qt/src/trading/brokers/BrokerHttp.cpp
index 5ab7298a2..faccfc9b9 100644
--- a/fincept-qt/src/trading/brokers/BrokerHttp.cpp
+++ b/fincept-qt/src/trading/brokers/BrokerHttp.cpp
@@ -181,16 +181,24 @@ BrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& url
if (timer.isActive()) {
timer.stop();
} else {
- // Timeout
+ // Timeout. The abort is client-side only: the broker may already have
+ // accepted the request, so this is "outcome unknown", not "did not
+ // happen". A blind retry of an order placement here creates a second
+ // live order — order payloads therefore carry a unique client order
+ // reference (BrokerClientOrderId.h) so the broker can reject the
+ // duplicate. Say so in the message rather than implying nothing ran.
reply->abort();
reply->deleteLater();
BrokerHttpResponse timeout_result;
- timeout_result.error = "Request timed out";
+ timeout_result.error = QString("Request timed out after %1 ms — outcome unknown, the request may have "
+ "been accepted; verify before retrying")
+ .arg(timeout_ms_);
timeout_result.rtt_ms = elapsed_ms;
return timeout_result;
}
result.status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ const QString response_content_type = reply->header(QNetworkRequest::ContentTypeHeader).toString();
result.raw_body = QString::fromUtf8(reply->readAll());
if (reply->error() != QNetworkReply::NoError && result.status_code == 0) {
@@ -200,13 +208,37 @@ BrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& url
}
// Parse JSON
+ const QByteArray body_bytes = result.raw_body.toUtf8();
QJsonParseError parseErr;
- auto doc = QJsonDocument::fromJson(result.raw_body.toUtf8(), &parseErr);
+ auto doc = QJsonDocument::fromJson(body_bytes, &parseErr);
if (parseErr.error == QJsonParseError::NoError && doc.isObject()) {
result.json = doc.object();
}
result.success = (result.status_code >= 200 && result.status_code < 300);
+
+ // A 2xx whose body we could not parse is NOT a success. The parse failure
+ // used to be dropped on the floor, leaving `json` default-constructed while
+ // `success` stayed true — Alpaca then read an empty `id` off it and reported
+ // "Order placed: " with no order id when nothing had been placed.
+ //
+ // Only a body the server itself labelled as JSON is held to this: an empty
+ // body is legitimate (204 on DELETE/cancel), a top-level JSON array is
+ // legitimate (Alpaca, IBKR and Shoonya return arrays and parse raw_body
+ // themselves — those leave `json` empty by design and parse cleanly), and
+ // genuinely non-JSON endpoints must keep working (Motilal's
+ // /getscripmastercsv and Kite's /instruments both return CSV through this
+ // same client). A missing or non-JSON content type therefore falls through
+ // to the previous behaviour rather than inventing a failure.
+ if (result.success && parseErr.error != QJsonParseError::NoError && !body_bytes.trimmed().isEmpty() &&
+ response_content_type.contains(QLatin1String("json"), Qt::CaseInsensitive)) {
+ result.success = false;
+ result.error = QString("Malformed JSON response (HTTP %1): %2 at offset %3")
+ .arg(result.status_code)
+ .arg(parseErr.errorString())
+ .arg(parseErr.offset);
+ }
+
if (!result.success && result.error.isEmpty()) {
result.error = result.json.value("message").toString(
result.json.value("error").toString(QString("HTTP %1").arg(result.status_code)));
diff --git a/fincept-qt/src/trading/brokers/BrokerModifyFields.h b/fincept-qt/src/trading/brokers/BrokerModifyFields.h
new file mode 100644
index 000000000..c8e0d4a56
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/BrokerModifyFields.h
@@ -0,0 +1,77 @@
+#pragma once
+
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QString>
+
+#include <span>
+
+/// Canonical readers for the untyped `modify_order(mods)` map.
+///
+/// The map is read under **32 distinct key names** across the 22 broker
+/// adapters (`trigger_price` ×7 vs `triggerPrice` ×6 vs `auxPrice` vs
+/// `stopPrice` vs `stop` vs `stoploss`; `orderType` ×9 vs `order_type` ×7 vs
+/// `type`), while callers populate only a couple of spellings. Every mismatch
+/// silently reads as absent and transmits the type's default — which for a
+/// price field means the broker receives **0**.
+///
+/// Live consequences this header exists to stop:
+/// * IIFL read `limitPrice` while callers send `price`, so a price modify
+/// transmitted `modifiedLimitPrice = 0`.
+/// * Shoonya, Flattrade and Tradejini read `triggerPrice` while callers send
+/// `trigger_price` (or nothing), so an SL modify transmitted `trgprc = 0`.
+///
+/// The real fix is a typed `OrderModification` struct; until that lands, read
+/// through these helpers so a broker accepts every spelling of a concept and a
+/// missing value is distinguishable from a zero one.
+namespace fincept::trading::modify_fields {
+
+using KeySet = std::span<const char* const>;
+
+/// First key that is actually present, else an undefined value.
+/// Presence — not truthiness — decides: a legitimate 0 must win over a fallback.
+inline QJsonValue first_present(const QJsonObject& mods, KeySet keys) {
+ for (const char* k : keys) {
+ const auto it = mods.constFind(QLatin1String(k));
+ if (it != mods.constEnd() && !it->isUndefined() && !it->isNull())
+ return *it;
+ }
+ return QJsonValue(QJsonValue::Undefined);
+}
+
+inline bool has_any(const QJsonObject& mods, KeySet keys) {
+ return !first_present(mods, keys).isUndefined();
+}
+
+/// Numeric read tolerant of JSON numbers *and* numeric strings. Zerodha's
+/// adapter used QJsonValue::toString() on numeric values, which returns an
+/// empty string — hence `toVariant()` rather than a typed accessor.
+inline double number(const QJsonObject& mods, KeySet keys, double fallback = 0.0) {
+ const QJsonValue v = first_present(mods, keys);
+ if (v.isUndefined())
+ return fallback;
+ bool ok = false;
+ const double d = v.toVariant().toDouble(&ok);
+ return ok ? d : fallback;
+}
+
+inline QString text(const QJsonObject& mods, KeySet keys, const QString& fallback = {}) {
+ const QJsonValue v = first_present(mods, keys);
+ if (v.isUndefined())
+ return fallback;
+ const QString s = v.toVariant().toString();
+ return s.isEmpty() ? fallback : s;
+}
+
+// Concept key sets. Canonical caller spelling first, adapter spellings after.
+// Plain arrays, not std::initializer_list: a namespace-scope constexpr
+// initializer_list has a backing array whose lifetime rules are subtle, and
+// span-over-array is unambiguously safe with static storage duration.
+inline constexpr const char* kPrice[] = {"price", "limitPrice", "limit_price"};
+inline constexpr const char* kTrigger[] = {"trigger_price", "triggerPrice", "trigPrice", "stopPrice",
+ "stop", "stoploss", "auxPrice"};
+inline constexpr const char* kQuantity[] = {"quantity", "qty"};
+inline constexpr const char* kOrderType[] = {"order_type", "orderType", "type"};
+inline constexpr const char* kProduct[] = {"product", "productType", "product_type"};
+
+} // namespace fincept::trading::modify_fields
diff --git a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
index 3e3bc2e7d..e4421bf1d 100644
--- a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
+++ b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
@@ -1,6 +1,7 @@
#include "trading/brokers/aliceblue/AliceBlueBroker.h"
#include "trading/adapter/BrokerEnumMap.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include "trading/instruments/InstrumentService.h"
@@ -130,23 +131,26 @@ TokenExchangeResponse AliceBlueBroker::exchange_token(const QString& api_key, co
auto resp = BrokerHttp::instance().post_json(AUTH_URL, body, headers);
if (!resp.success)
- return {false, "", "", "", checked_error(resp, "Network error"), ""};
+ return {.success = false, .error = checked_error(resp, "Network error")};
QString stat = resp.json["stat"].toString();
if (stat != "Ok")
- return {false, "", "", "", checked_error(resp, "Authentication failed"), ""};
+ return {.success = false, .error = checked_error(resp, "Authentication failed")};
QString session = resp.json["userSession"].toString();
QString client_id = resp.json["clientId"].toString();
if (session.isEmpty())
- return {false, "", "", "", "No userSession in response", ""};
+ return {.success = false, .error = "No userSession in response"};
// AliceBlue session tokens are flushed at the daily reset; the live sweep is
// authoritative — this is only a startup hint. No silent refresh (re-auth
// needs a fresh web-login auth code).
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, session, client_id, "", extra, ""};
+ // clientId is the account identifier, not a refresh token — it used to be
+ // passed positionally into the refresh_token slot, which left user_id empty
+ // everywhere the account is displayed or reconciled.
+ return {.success = true, .access_token = session, .user_id = client_id, .additional_data = extra};
}
// ============================================================================
@@ -181,7 +185,10 @@ OrderPlaceResponse AliceBlueBroker::place_order(const BrokerCredentials& creds,
item["trailingSlAmount"] = "";
item["apiOrderSource"] = "";
item["algoId"] = "";
- item["orderTag"] = "fincept";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ item["orderTag"] = make_client_order_ref(20);
// API expects an array of one item
QJsonArray payload;
@@ -383,6 +390,10 @@ ApiResponse<QVector<BrokerPosition>> AliceBlueBroker::get_positions(const Broker
pos.pnl = p["unrealisedPnl"].toDouble();
pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.product_type = p["product"].toString();
+ // netQuantity carries the sign, but PortfolioReplicationService takes
+ // fabs() of quantity and reads direction from `side` alone — leaving it
+ // empty replicated every short as a long and inverted its P&L.
+ pos.side = net_qty > 0 ? "LONG" : "SHORT";
positions.append(pos);
}
diff --git a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp
index feb28ea23..aab211cf1 100644
--- a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp
@@ -2,7 +2,9 @@
#include "core/logging/Logger.h"
#include "trading/adapter/BrokerEnumMap.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
+#include "trading/brokers/BrokerLogRedact.h"
#include <QDateTime>
#include <QJsonArray>
@@ -14,6 +16,54 @@ namespace fincept::trading {
static int64_t now_ts() {
return QDateTime::currentSecsSinceEpoch();
}
+
+namespace {
+
+// Alpaca reports auth failures as HTTP 401/403 with a JSON {code, message}
+// body. BrokerInterface's default validate_session only classifies a session as
+// Expired when the error string carries the [TOKEN_EXPIRED] marker (see the
+// contract comment on BrokerInterface::validate_session), so without it an
+// Alpaca account reads "Connected" forever while every request fails and the
+// user is never prompted to reconnect. Every error path here goes through this
+// helper so the marker is attached exactly once, in one place.
+QString alpaca_checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
+ QString msg;
+ const QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
+ if (doc.isObject()) {
+ const QJsonObject o = doc.object();
+ msg = o.value("message").toString();
+ if (msg.isEmpty())
+ msg = o.value("error").toString();
+ }
+ if (msg.isEmpty())
+ msg = resp.error;
+ if (msg.isEmpty())
+ msg = fallback;
+
+ const QString lower = msg.toLower();
+ if (resp.status_code == 401 || resp.status_code == 403 || lower.contains("access key verification failed") ||
+ lower.contains("unauthorized") || lower.contains("forbidden"))
+ return QStringLiteral("[TOKEN_EXPIRED] ") + msg;
+ return msg;
+}
+
+// Alpaca accepts fractional shares, so quantity is a decimal string. The
+// default QString::number() 'g' format caps at 6 significant digits, which
+// serialises 1,000,000 shares as "1e+06" — Alpaca rejects that. Emit a plain
+// fixed-point value and trim the padding.
+QString alpaca_qty(double quantity) {
+ QString s = QString::number(quantity, 'f', 9);
+ if (s.contains(QLatin1Char('.'))) {
+ while (s.endsWith(QLatin1Char('0')))
+ s.chop(1);
+ if (s.endsWith(QLatin1Char('.')))
+ s.chop(1);
+ }
+ return s;
+}
+
+} // namespace
+
// ═══════════════════════════════════════════════════════════════════════════════
// ALPACA — US broker, API key/secret in headers (no OAuth)
// additional_data == "live" → https://api.alpaca.markets
@@ -102,13 +152,21 @@ OrderPlaceResponse AlpacaBroker::place_order(const BrokerCredentials& creds, con
const QString tif = is_market ? "day" : "gtc";
QJsonObject payload{{"symbol", order.symbol},
- {"qty", QString::number(order.quantity)},
+ {"qty", alpaca_qty(order.quantity)},
{"side", alpaca_enum_map().side_or(order.side, "buy")},
{"type", alpaca_enum_map().order_type_or(order.order_type, "market")},
- {"time_in_force", tif}};
+ {"time_in_force", tif},
+ // Idempotency key: BrokerHttp aborts client-side on an 8s
+ // timeout, but the order may already be live at Alpaca. A
+ // unique client_order_id makes the retry a duplicate that
+ // Alpaca rejects instead of a second live order.
+ {"client_order_id", make_client_order_ref(48)}};
if (is_market)
payload["extended_hours"] = true; // allow pre/post market execution
- if (order.price > 0)
+ // limit_price must be gated on the order type, not merely on price > 0:
+ // callers routinely fill order.price with the LTP for a market order, which
+ // silently converted a market order into a limit order at the last tick.
+ if (!is_market && order.price > 0)
payload["limit_price"] = QString::number(order.price, 'f', 2);
if (order.stop_price > 0)
payload["stop_price"] = QString::number(order.stop_price, 'f', 2);
@@ -116,11 +174,27 @@ OrderPlaceResponse AlpacaBroker::place_order(const BrokerCredentials& creds, con
auto resp = BrokerHttp::instance().post_json(trading_url(creds) + "/v2/orders", payload, auth_headers(creds));
OrderPlaceResponse result;
if (!resp.success) {
- result.error = resp.error;
+ result.error = alpaca_checked_error(resp, "place_order failed");
+ LOG_ERROR("AlpacaBroker",
+ QString("place_order failed: %1 | body: %2").arg(result.error, redact_body(resp.raw_body)));
+ return result;
+ }
+ // A 2xx alone is not proof the order exists. Alpaca can answer with a
+ // business error in the body, and an unparseable body leaves resp.json
+ // default-constructed — which used to yield success with an empty order id
+ // ("Order placed: ") that the algo engine then tracked as a real position.
+ const QString body_err = resp.json.value("message").toString();
+ if (!body_err.isEmpty()) {
+ result.error = alpaca_checked_error(resp, body_err);
return result;
}
- result.success = true;
result.order_id = resp.json.value("id").toString();
+ if (result.order_id.isEmpty()) {
+ result.error = "place_order: broker returned no order id — order not confirmed placed";
+ LOG_ERROR("AlpacaBroker", QString("place_order: %1 | body: %2").arg(result.error, redact_body(resp.raw_body)));
+ return result;
+ }
+ result.success = true;
return result;
}
@@ -130,21 +204,23 @@ ApiResponse<QJsonObject> AlpacaBroker::modify_order(const BrokerCredentials& cre
BrokerHttp::instance().put_json(trading_url(creds) + "/v2/orders/" + order_id, mods, auth_headers(creds));
int64_t ts = now_ts();
return resp.success ? ApiResponse<QJsonObject>{true, resp.json, "", ts}
- : ApiResponse<QJsonObject>{false, std::nullopt, resp.error, ts};
+ : ApiResponse<QJsonObject>{false, std::nullopt, alpaca_checked_error(resp, "request failed"),
+ ts};
}
ApiResponse<QJsonObject> AlpacaBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {
auto resp = BrokerHttp::instance().del(trading_url(creds) + "/v2/orders/" + order_id, auth_headers(creds));
int64_t ts = now_ts();
return resp.success ? ApiResponse<QJsonObject>{true, resp.json, "", ts}
- : ApiResponse<QJsonObject>{false, std::nullopt, resp.error, ts};
+ : ApiResponse<QJsonObject>{false, std::nullopt, alpaca_checked_error(resp, "request failed"),
+ ts};
}
ApiResponse<QVector<BrokerOrderInfo>> AlpacaBroker::get_orders(const BrokerCredentials& creds) {
auto resp = BrokerHttp::instance().get(trading_url(creds) + "/v2/orders?status=all&limit=100", auth_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QVector<BrokerOrderInfo> orders;
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -173,15 +249,17 @@ ApiResponse<QJsonObject> AlpacaBroker::get_trade_book(const BrokerCredentials& c
auto resp = BrokerHttp::instance().get(trading_url(creds) + "/v2/account/activities/FILL", auth_headers(creds));
int64_t ts = now_ts();
return resp.success ? ApiResponse<QJsonObject>{true, resp.json, "", ts}
- : ApiResponse<QJsonObject>{false, std::nullopt, resp.error, ts};
+ : ApiResponse<QJsonObject>{false, std::nullopt, alpaca_checked_error(resp, "request failed"),
+ ts};
}
ApiResponse<QVector<BrokerPosition>> AlpacaBroker::get_positions(const BrokerCredentials& creds) {
auto resp = BrokerHttp::instance().get(trading_url(creds) + "/v2/positions", auth_headers(creds));
int64_t ts = now_ts();
if (!resp.success) {
- LOG_ERROR("AlpacaBroker", QString("get_positions failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("get_positions failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
QVector<BrokerPosition> positions;
QJsonParseError err;
@@ -210,8 +288,9 @@ ApiResponse<QVector<BrokerHolding>> AlpacaBroker::get_holdings(const BrokerCrede
auto resp = BrokerHttp::instance().get(trading_url(creds) + "/v2/positions", auth_headers(creds));
int64_t ts = now_ts();
if (!resp.success) {
- LOG_ERROR("AlpacaBroker", QString("get_holdings failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("get_holdings failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
QVector<BrokerHolding> holdings;
QJsonParseError err;
@@ -240,8 +319,9 @@ ApiResponse<BrokerFunds> AlpacaBroker::get_funds(const BrokerCredentials& creds)
auto resp = BrokerHttp::instance().get(trading_url(creds) + "/v2/account", auth_headers(creds));
int64_t ts = now_ts();
if (!resp.success) {
- LOG_ERROR("AlpacaBroker", QString("get_funds failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("get_funds failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
// Alpaca returns numeric fields as JSON strings in paper env, numbers in live env — handle both
auto jval = [](const QJsonValue& v) -> double {
@@ -278,8 +358,9 @@ ApiResponse<QVector<BrokerQuote>> AlpacaBroker::get_quotes(const BrokerCredentia
auto resp = BrokerHttp::instance().get(url, data_headers);
int64_t ts = now_ts();
if (!resp.success) {
- LOG_ERROR("AlpacaBroker", QString("get_quotes failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("get_quotes failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
QJsonParseError err;
@@ -364,8 +445,9 @@ ApiResponse<QVector<BrokerCandle>> AlpacaBroker::get_history(const BrokerCredent
auto resp = BrokerHttp::instance().get(url, data_headers);
int64_t ts = now_ts();
if (!resp.success) {
- LOG_ERROR("AlpacaBroker", QString("get_history failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("get_history failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
QVector<BrokerCandle> candles;
@@ -404,7 +486,7 @@ ApiResponse<QVector<MarketCalendarDay>> AlpacaBroker::get_calendar(const BrokerC
int64_t ts = now_ts();
if (!resp.success) {
LOG_ERROR("AlpacaBroker", QString("get_calendar failed: %1").arg(resp.error));
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
QJsonParseError err;
@@ -434,7 +516,7 @@ ApiResponse<MarketClock> AlpacaBroker::get_clock(const BrokerCredentials& creds)
int64_t ts = now_ts();
if (!resp.success) {
LOG_ERROR("AlpacaBroker", QString("get_clock failed: %1").arg(resp.error));
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
}
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -512,7 +594,7 @@ ApiResponse<QVector<BrokerCandle>> AlpacaBroker::get_latest_bars(const BrokerCre
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -547,7 +629,7 @@ ApiResponse<QVector<BrokerCandle>> AlpacaBroker::get_historical_bars(const Broke
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -573,7 +655,7 @@ ApiResponse<QVector<BrokerQuote>> AlpacaBroker::get_latest_quotes(const BrokerCr
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -600,7 +682,7 @@ ApiResponse<QVector<BrokerTrade>> AlpacaBroker::get_latest_trades(const BrokerCr
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -635,7 +717,7 @@ ApiResponse<QVector<BrokerTrade>> AlpacaBroker::get_historical_trades(const Brok
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -667,7 +749,7 @@ ApiResponse<QVector<BrokerAuction>> AlpacaBroker::get_historical_auctions(const
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -718,7 +800,7 @@ ApiResponse<BrokerCandle> AlpacaBroker::get_latest_bar(const BrokerCredentials&
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -737,7 +819,7 @@ ApiResponse<BrokerQuote> AlpacaBroker::get_latest_quote(const BrokerCredentials&
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -756,7 +838,7 @@ ApiResponse<BrokerTrade> AlpacaBroker::get_latest_trade(const BrokerCredentials&
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -775,7 +857,7 @@ ApiResponse<BrokerQuote> AlpacaBroker::get_snapshot(const BrokerCredentials& cre
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -823,7 +905,7 @@ ApiResponse<QVector<BrokerTrade>> AlpacaBroker::get_historical_trades_single(con
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -851,7 +933,7 @@ ApiResponse<QVector<BrokerQuote>> AlpacaBroker::get_historical_quotes_single(con
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -878,7 +960,7 @@ ApiResponse<QVector<BrokerAuction>> AlpacaBroker::get_historical_auctions_single
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
@@ -922,7 +1004,7 @@ ApiResponse<QVector<BrokerMetaEntry>> AlpacaBroker::get_condition_codes(const Br
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
if (err.error != QJsonParseError::NoError)
@@ -947,7 +1029,7 @@ ApiResponse<QVector<BrokerMetaEntry>> AlpacaBroker::get_exchange_codes(const Bro
auto resp = BrokerHttp::instance().get(url, alpaca_data_headers(creds));
int64_t ts = now_ts();
if (!resp.success)
- return {false, std::nullopt, resp.error, ts};
+ return {false, std::nullopt, alpaca_checked_error(resp, "request failed"), ts};
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
if (err.error != QJsonParseError::NoError)
@@ -976,8 +1058,9 @@ ApiResponse<CancelAllResult> AlpacaBroker::cancel_all_orders(const BrokerCredent
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
if (err.error != QJsonParseError::NoError && !resp.success) {
- LOG_ERROR("AlpacaBroker", QString("cancel_all_orders failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error.isEmpty() ? resp.raw_body : resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("cancel_all_orders failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "cancel_all_orders failed"), ts};
}
CancelAllResult result;
@@ -1015,8 +1098,9 @@ ApiResponse<CloseAllResult> AlpacaBroker::close_all_positions(const BrokerCreden
QJsonParseError err;
auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);
if (err.error != QJsonParseError::NoError && !resp.success) {
- LOG_ERROR("AlpacaBroker", QString("close_all_positions failed: %1 | body: %2").arg(resp.error, resp.raw_body));
- return {false, std::nullopt, resp.error.isEmpty() ? resp.raw_body : resp.error, ts};
+ LOG_ERROR("AlpacaBroker",
+ QString("close_all_positions failed: %1 | body: %2").arg(resp.error, redact_body(resp.raw_body)));
+ return {false, std::nullopt, alpaca_checked_error(resp, "close_all_positions failed"), ts};
}
CloseAllResult result;
@@ -1069,8 +1153,8 @@ ApiResponse<QVector<BrokerQuote>> AlpacaBroker::get_multi_quotes(const BrokerCre
auto resp = BrokerHttp::instance().get(url, data_headers);
int64_t ts = now_ts();
if (!resp.success) {
- LOG_ERROR("AlpacaBroker",
- QString("get_multi_quotes batch failed: %1 | body: %2").arg(resp.error, resp.raw_body));
+ LOG_ERROR("AlpacaBroker", QString("get_multi_quotes batch failed: %1 | body: %2")
+ .arg(resp.error, redact_body(resp.raw_body)));
continue; // best-effort — partial batches still return what succeeded
}
diff --git a/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp b/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp
index fcba76af5..7e106adc1 100644
--- a/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp
+++ b/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp
@@ -322,7 +322,7 @@ TokenExchangeResponse AngelOneBroker::refresh_session(const BrokerCredentials& c
const QString client_code = extra.value("client_code").toString();
const QString totp_secret = extra.value("totp_secret").toString();
if (client_code.isEmpty() || totp_secret.isEmpty()) {
- return {false, "", "", "", "", "Angel One silent refresh requires stored client code and TOTP secret"};
+ return {.success = false, .error = "Angel One silent refresh requires stored client code and TOTP secret"};
}
const QJsonObject auth{{"client_code", client_code}, {"totp_secret", totp_secret}};
return exchange_token(creds.api_key, creds.api_secret,
diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
index 8024c11a1..458f015d3 100644
--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
@@ -15,6 +15,7 @@
#include "core/logging/Logger.h"
#include "trading/adapter/BrokerEnumMap.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerLogRedact.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -121,7 +122,7 @@ bool DhanBroker::is_token_expired(const BrokerHttpResponse& resp) {
LOG_WARN(TAG, QString("Dhan classified TOKEN_EXPIRED → will disconnect. status=%1 type=%2 code=%3 msg=%4 "
"body=%5")
.arg(resp.status_code)
- .arg(error_type, error_code, msg, resp.raw_body.left(400)));
+ .arg(error_type, error_code, msg, redact_body(resp.raw_body, 400)));
}
return auth_err;
}
@@ -194,10 +195,10 @@ QMap<QString, QString> DhanBroker::auth_headers(const BrokerCredentials& creds)
TokenExchangeResponse DhanBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& /*auth_code*/) {
if (api_key.trimmed().isEmpty()) {
- return {false, "", "", "", "", "Client ID is required"};
+ return {.success = false, .error = "Client ID is required"};
}
if (api_secret.trimmed().isEmpty() || api_secret.length() < 20) {
- return {false, "", "", "", "", "Access token appears invalid (too short)"};
+ return {.success = false, .error = "Access token appears invalid (too short)"};
}
// Validate by calling fundlimit — lightweight auth check
@@ -208,7 +209,7 @@ TokenExchangeResponse DhanBroker::exchange_token(const QString& api_key, const Q
auto resp = BrokerHttp::instance().get(BASE + "/v2/fundlimit", hdrs);
if (is_token_expired(resp)) {
- return {false, "", "", "", "", "[TOKEN_EXPIRED] Access token is invalid or expired"};
+ return {.success = false, .error = "[TOKEN_EXPIRED] Access token is invalid or expired"};
}
// Accept any non-auth error (market closed, etc.) as token valid.
// Dhan v2 access tokens are valid for 24h from generation (rolling window).
@@ -216,7 +217,7 @@ TokenExchangeResponse DhanBroker::exchange_token(const QString& api_key, const Q
// a startup hint so a token isn't shown green long after it has lapsed.
const QString extra = with_token_expiry({}, rolling_expiry_epoch(24));
LOG_INFO(TAG, "Token exchange OK"); // don't log client_id (P14)
- return {true, api_secret, /*refresh*/ "", api_key, /*additional*/ extra, ""};
+ return {.success = true, .access_token = api_secret, .user_id = api_key, .additional_data = extra};
}
// ── Place Order ───────────────────────────────────────────────────────────────
@@ -238,6 +239,10 @@ OrderPlaceResponse DhanBroker::place_order(const BrokerCredentials& creds, const
body["price"] = order.price;
body["triggerPrice"] = order.stop_price;
body["disclosedQuantity"] = 0;
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Dhan caps correlationId at 25 chars.
+ body["correlationId"] = make_client_order_ref(25);
if (order.amo)
body["afterMarketOrder"] = true;
diff --git a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp
index dee6d38ce..8ed9cd010 100644
--- a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp
@@ -139,11 +139,11 @@ TokenExchangeResponse FivePaisaBroker::exchange_token(const QString& api_key, co
const QString& auth_code) {
auto kp = unpack_key(api_key);
if (kp.app_key.isEmpty())
- return {false, "", "", "", "ApiKey must be 'app_key:::user_id:::client_id'", ""};
+ return {.success = false, .error = "ApiKey must be 'app_key:::user_id:::client_id'"};
QStringList auth_parts = auth_code.split(":::");
if (auth_parts.size() < 3)
- return {false, "", "", "", "AuthCode must be 'email:::pin:::totp'", ""};
+ return {.success = false, .error = "AuthCode must be 'email:::pin:::totp'"};
QString email = auth_parts[0].trimmed();
QString pin = auth_parts[1].trimmed();
QString totp = auth_parts[2].trimmed();
@@ -170,7 +170,7 @@ TokenExchangeResponse FivePaisaBroker::exchange_token(const QString& api_key, co
BrokerHttp::instance().post_json(QString(BASE_URL) + "/VendorsAPI/Service1.svc/TOTPLogin", req, headers);
if (!resp.success)
- return {false, "", "", "", checked_error(resp, "TOTP login network error"), ""};
+ return {.success = false, .error = checked_error(resp, "TOTP login network error")};
// Per SDK, success is indicated by head.statusDescription=="Success" AND
// body.Status==0; bypassing the status check buries auth errors in an
@@ -180,7 +180,7 @@ TokenExchangeResponse FivePaisaBroker::exchange_token(const QString& api_key, co
const QString req_token = body_obj["RequestToken"].toString();
if (req_token.isEmpty() || (status_code != 0 && status_code != -1)) {
const QString msg = body_obj["Message"].toString();
- return {false, "", "", "", msg.isEmpty() ? "TOTP login failed (no RequestToken)" : msg, ""};
+ return {.success = false, .error = msg.isEmpty() ? "TOTP login failed (no RequestToken)" : msg};
}
// Step 2: Get access token
@@ -198,18 +198,21 @@ TokenExchangeResponse FivePaisaBroker::exchange_token(const QString& api_key, co
req2, headers);
if (!resp2.success)
- return {false, "", "", "", checked_error(resp2, "GetAccessToken network error"), ""};
+ return {.success = false, .error = checked_error(resp2, "GetAccessToken network error")};
QString access_token = resp2.json["body"].toObject()["AccessToken"].toString();
if (access_token.isEmpty()) {
QString msg = resp2.json["body"].toObject()["Message"].toString();
- return {false, "", "", "", msg.isEmpty() ? "No AccessToken in response" : msg, ""};
+ return {.success = false, .error = msg.isEmpty() ? "No AccessToken in response" : msg};
}
// 5paisa access tokens expire at the daily reset. The live TOTP is a
// one-time code we can't replay, so there is no silent refresh.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, access_token, kp.client_id, "", extra, ""};
+ // clientId is the account identifier, not a refresh token — it used to
+ // be passed positionally into the refresh_token slot, which left
+ // user_id empty. Same defect as AliceBlue and IIFL.
+ return {.success = true, .access_token = access_token, .user_id = kp.client_id, .additional_data = extra};
}
}
@@ -482,6 +485,10 @@ ApiResponse<QVector<BrokerPosition>> FivePaisaBroker::get_positions(const Broker
pos.pnl = p["MTOM"].toDouble();
pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.product_type = product;
+ // NetQty carries the sign, but PortfolioReplicationService takes fabs()
+ // of quantity and reads direction from `side` alone — leaving it empty
+ // replicated every short as a long and inverted its P&L.
+ pos.side = net_qty > 0 ? "LONG" : "SHORT";
positions.append(pos);
}
diff --git a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
index f5361e84b..c86518f49 100644
--- a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
+++ b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
@@ -1,5 +1,7 @@
#include "trading/brokers/flattrade/FlattradeBroker.h"
+#include "trading/brokers/BrokerModifyFields.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -117,7 +119,7 @@ TokenExchangeResponse FlattradeBroker::exchange_token(const QString& api_key, co
QString request_code = auth_code.trimmed();
if (apikey.isEmpty() || api_secret.isEmpty() || request_code.isEmpty())
- return {false, "", "", "", "Flattrade login: api_key, api_secret and request_code are required", ""};
+ return {.success = false, .error = "Flattrade login: api_key, api_secret and request_code are required"};
QString security_hash = QString(
QCryptographicHash::hash((apikey + request_code + api_secret).toUtf8(), QCryptographicHash::Sha256).toHex());
@@ -131,24 +133,24 @@ TokenExchangeResponse FlattradeBroker::exchange_token(const QString& api_key, co
auto resp = http.post_json(AUTH_URL, payload, {{"Content-Type", "application/json"}});
if (!resp.success)
- return {false, "", "", "", "Login failed: " + resp.error, ""};
+ return {.success = false, .error = "Login failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Login: invalid response", ""};
+ return {.success = false, .error = "Login: invalid response"};
QJsonObject obj = doc.object();
if (obj.value("stat").toString() != "Ok")
- return {false, "", "", "", obj.value("emsg").toString("Login failed"), ""};
+ return {.success = false, .error = obj.value("emsg").toString("Login failed")};
QString token = obj.value("token").toString();
if (token.isEmpty())
- return {false, "", "", "", "Login: no token in response", ""};
+ return {.success = false, .error = "Login: no token in response"};
// Flattrade tokens lapse at the daily reset; re-auth needs a fresh web
// request_code, so there is no silent refresh. Hint only.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, token, "", uid, extra, ""};
+ return {.success = true, .access_token = token, .user_id = uid, .additional_data = extra};
}
// ---------- place_order ----------
@@ -171,7 +173,10 @@ OrderPlaceResponse FlattradeBroker::place_order(const BrokerCredentials& creds,
jdata["trgprc"] = QString::number(order.stop_price, 'f', 2);
jdata["ret"] = order.validity.isEmpty() ? "DAY" : order.validity;
jdata["mkt_protection"] = "0";
- jdata["remarks"] = "fincept";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ jdata["remarks"] = make_client_order_ref(20);
jdata["ordersource"] = "API";
auto& http = BrokerHttp::instance();
@@ -213,7 +218,8 @@ ApiResponse<QJsonObject> FlattradeBroker::modify_order(const BrokerCredentials&
// Only include trigger price for SL/SL-M — trgprc=0 on LMT causes a reject.
const QString prctyp = jdata["prctyp"].toString();
if (prctyp == "SL-LMT" || prctyp == "SL-MKT")
- jdata["trgprc"] = QString::number(mods.value("triggerPrice").toDouble(0), 'f', 2);
+ jdata["trgprc"] = QString::number(
+ modify_fields::number(mods, modify_fields::kTrigger), 'f', 2);
auto& http = BrokerHttp::instance();
auto resp = http.post_raw(QString("%1/ModifyOrder").arg(BASE), make_body(jdata, creds.access_token),
diff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
index 9635a1b3b..8ee9da14a 100644
--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
@@ -1,5 +1,6 @@
#include "trading/brokers/groww/GrowwBroker.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -224,23 +225,23 @@ TokenExchangeResponse GrowwBroker::exchange_token(const QString& api_key, const
auto resp = BrokerHttp::instance().post_json("https://api.groww.in/v1/token/api/access", body, headers);
if (!resp.success)
- return {false, "", "", "", checked_error(resp, "Network error"), ""};
+ return {.success = false, .error = checked_error(resp, "Network error")};
QString token = resp.json["token"].toString();
if (token.isEmpty())
- return {false, "", "", "", checked_error(resp, "No token in response"), ""};
+ return {.success = false, .error = checked_error(resp, "No token in response")};
// Groww daily access tokens are minted purely from the api_key + api_secret
// (checksum flow) — both are stored, so the session can be silently
// re-minted without any user interaction.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, token, "", "", extra, ""};
+ return {.success = true, .access_token = token, .additional_data = extra};
}
// Silent refresh = re-mint the daily token from the stored api_key + api_secret.
TokenExchangeResponse GrowwBroker::refresh_session(const BrokerCredentials& creds) {
if (creds.api_key.isEmpty() || creds.api_secret.isEmpty())
- return {false, "", "", "", "", "Groww silent refresh requires stored API key and secret"};
+ return {.success = false, .error = "Groww silent refresh requires stored API key and secret"};
return exchange_token(creds.api_key, creds.api_secret, QString());
}
@@ -260,6 +261,10 @@ OrderPlaceResponse GrowwBroker::place_order(const BrokerCredentials& creds, cons
body["product"] = groww_enum_map().product_or(order.product_type, "CNC");
body["order_type"] = groww_enum_map().order_type_or(order.order_type, "MARKET");
body["transaction_type"] = (order.side == OrderSide::Buy) ? "BUY" : "SELL";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Groww requires 8-20 alphanumeric chars.
+ body["order_reference_id"] = make_client_order_ref(20);
if (order.order_type != OrderType::Market)
body["price"] = order.price;
@@ -549,6 +554,11 @@ ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCred
pos.pnl = p["realised_pnl"].toDouble();
pos.product_type = p["product"].toString();
pos.pnl_pct = 0.0;
+ // credit - debit carries the sign, but PortfolioReplicationService
+ // takes fabs() of quantity and reads direction from `side` alone —
+ // leaving it empty replicated every short as a long and inverted
+ // its P&L.
+ pos.side = qty > 0 ? "LONG" : "SHORT";
SymbolRef ref;
ref.orig = pos.symbol;
diff --git a/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp b/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp
index b8070f236..246c16da6 100644
--- a/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp
+++ b/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp
@@ -1,5 +1,6 @@
#include "trading/brokers/ibkr/IBKRBroker.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include <QDateTime>
@@ -164,26 +165,22 @@ TokenExchangeResponse IBKRBroker::exchange_token(const QString& api_key, const Q
{{"Content-Type", "application/json"}, {"Accept", "application/json"}});
if (!resp.success)
- return {false, "", "", "", "Gateway not reachable at " + gw + ": " + resp.error, ""};
+ return {.success = false, .error = "Gateway not reachable at " + gw + ": " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Gateway: invalid auth status response", ""};
+ return {.success = false, .error = "Gateway: invalid auth status response"};
QJsonObject obj = doc.object();
bool authenticated = obj.value("authenticated").toBool();
if (!authenticated) {
- return {false,
- "",
- "",
- "",
- "Gateway is running but not authenticated. "
- "Please log in via the gateway browser interface first.",
- ""};
+ return {.success = false,
+ .error = "Gateway is running but not authenticated. "
+ "Please log in via the gateway browser interface first."};
}
// Store gateway URL as "access_token" — it's the only credential we need at runtime
- return {true, gw, "", api_key, "", ""};
+ return {.success = true, .access_token = gw, .user_id = api_key};
}
// ---------- place_order ----------
@@ -212,6 +209,10 @@ OrderPlaceResponse IBKRBroker::place_order(const BrokerCredentials& creds, const
if (order.stop_price > 0)
order_obj["auxPrice"] = order.stop_price;
order_obj["acctId"] = acct;
+ // Customer order id: unique per attempt so a retry after an 8s client-side
+ // timeout is rejected by IBKR as a duplicate rather than creating a second
+ // live order (see BrokerClientOrderId.h).
+ order_obj["cOID"] = make_client_order_ref(40);
QJsonObject body;
body["orders"] = QJsonArray{order_obj};
@@ -238,10 +239,41 @@ OrderPlaceResponse IBKRBroker::place_order(const BrokerCredentials& creds, const
if (arr.isEmpty())
return {false, "", "place_order: empty response"};
- QJsonObject result = arr[0].toObject();
- QString order_id = result.value("order_id").toString();
- if (order_id.isEmpty())
- order_id = QString::number(result.value("order_id").toVariant().toLongLong());
+ // The array branch above used to skip every check the object branch did, so
+ // an error payload or a confirmation prompt was reported as a placed order,
+ // and a missing order_id degraded to the string "0" — a phantom id the algo
+ // engine then tracked as a real position. Validate the element itself.
+ const QJsonObject result = arr[0].toObject();
+
+ const QString elem_err = result.value("error").toString();
+ if (!elem_err.isEmpty())
+ return {false, "", elem_err};
+
+ // A `message` element is IBKR's pre-submit confirmation dialog (order value
+ // warning, missing market data subscription, ...). The order has NOT been
+ // transmitted — it only goes live after POSTing to /iserver/reply/{id}.
+ if (result.contains("message")) {
+ QStringList msgs;
+ for (const QJsonValue& m : result.value("message").toArray())
+ msgs << m.toString();
+ if (msgs.isEmpty() && result.value("message").isString())
+ msgs << result.value("message").toString();
+ return {false, "",
+ QString("place_order requires confirmation and was NOT transmitted: %1")
+ .arg(msgs.isEmpty() ? QStringLiteral("(no detail)") : msgs.join(" | "))};
+ }
+
+ // order_id may arrive as a string or a JSON number; large ids must not go
+ // through a double->'g'-format round trip, so convert integrally.
+ const QJsonValue oid_val = result.value("order_id");
+ QString order_id;
+ if (oid_val.isString())
+ order_id = oid_val.toString().trimmed();
+ else if (oid_val.isDouble())
+ order_id = QString::number(static_cast<qint64>(oid_val.toDouble()));
+
+ if (order_id.isEmpty() || order_id == QLatin1String("0"))
+ return {false, "", "place_order: broker returned no order id — order not confirmed placed"};
return {true, order_id, ""};
}
diff --git a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
index 6be407c73..07446aa3e 100644
--- a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
+++ b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
@@ -1,6 +1,7 @@
#include "trading/brokers/icicidirect/IciciDirectBroker.h"
#include "core/logging/Logger.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerLogRedact.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -165,11 +166,25 @@ bool IciciDirectBroker::is_success(const BrokerHttpResponse& resp) {
QString IciciDirectBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
const QString err = resp.json.value("Error").toString();
- if (!err.isEmpty())
- return err;
- if (!resp.error.isEmpty())
- return resp.error;
- return fallback;
+ QString msg = err;
+ if (msg.isEmpty())
+ msg = resp.error;
+ if (msg.isEmpty())
+ msg = fallback;
+
+ // Breeze reports an expired/invalid session either through the HTTP status
+ // or through the envelope's Status field with a descriptive Error string.
+ // The [TOKEN_EXPIRED] marker is the contract BrokerInterface::validate_session
+ // classifies on (BrokerInterface.h) — without it the account reads
+ // "Connected" forever while every request fails, and the user is never
+ // prompted to reconnect.
+ const int envelope_status = resp.json.value("Status").toInt(resp.status_code);
+ const QString lower = msg.toLower();
+ if (resp.status_code == 401 || resp.status_code == 403 || envelope_status == 401 || envelope_status == 403 ||
+ lower.contains("session") || lower.contains("unauthor") || lower.contains("invalid token") ||
+ lower.contains("public key does not exist"))
+ return QStringLiteral("[TOKEN_EXPIRED] ") + msg;
+ return msg;
}
TokenExchangeResponse IciciDirectBroker::exchange_token(const QString& api_key, const QString& api_secret,
@@ -267,7 +282,10 @@ OrderPlaceResponse IciciDirectBroker::place_order(const BrokerCredentials& creds
{"expiry_date", expiry_iso},
{"right", right},
{"strike_price", strike_str},
- {"user_remark", "fincept"},
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h).
+ {"user_remark", make_client_order_ref(20)},
};
auto resp = breeze_request("POST", "/order", payload, creds);
diff --git a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp
index 3679c7be6..27f4eb18a 100644
--- a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp
+++ b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp
@@ -1,5 +1,7 @@
#include "trading/brokers/iifl/IIFLBroker.h"
+#include "trading/brokers/BrokerModifyFields.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -163,19 +165,19 @@ TokenExchangeResponse IIFLBroker::exchange_token(const QString& api_key, const Q
auto trade_resp = http.post_json(QString("%1/user/session").arg(INTERACTIVE_URL), trade_body,
{{"Content-Type", "application/json"}, {"Accept", "application/json"}});
if (!trade_resp.success)
- return {false, "", "", "", "Interactive login failed: " + trade_resp.error, ""};
+ return {.success = false, .error = "Interactive login failed: " + trade_resp.error};
QJsonDocument trade_doc = QJsonDocument::fromJson(trade_resp.raw_body.toUtf8());
if (!trade_doc.isObject())
- return {false, "", "", "", "Interactive login: invalid response", ""};
+ return {.success = false, .error = "Interactive login: invalid response"};
QJsonObject trade_obj = trade_doc.object();
if (trade_obj.value("type").toString() != "success")
- return {false, "", "", "", trade_obj.value("description").toString("Interactive login failed"), ""};
+ return {.success = false, .error = trade_obj.value("description").toString("Interactive login failed")};
QString trade_token = trade_obj.value("result").toObject().value("token").toString();
if (trade_token.isEmpty())
- return {false, "", "", "", "Interactive login: no token in response", ""};
+ return {.success = false, .error = "Interactive login: no token in response"};
// Step 2: Market data login (feed token)
QJsonObject market_body;
@@ -186,22 +188,22 @@ TokenExchangeResponse IIFLBroker::exchange_token(const QString& api_key, const Q
auto market_resp = http.post_json(QString("%1/auth/login").arg(MARKET_DATA_URL), market_body,
{{"Content-Type", "application/json"}, {"Accept", "application/json"}});
if (!market_resp.success)
- return {false, "", "", "", "Market data login failed: " + market_resp.error, ""};
+ return {.success = false, .error = "Market data login failed: " + market_resp.error};
QJsonDocument market_doc = QJsonDocument::fromJson(market_resp.raw_body.toUtf8());
if (!market_doc.isObject())
- return {false, "", "", "", "Market data login: invalid response", ""};
+ return {.success = false, .error = "Market data login: invalid response"};
QJsonObject market_obj = market_doc.object();
if (market_obj.value("type").toString() != "success")
- return {false, "", "", "", market_obj.value("description").toString("Market data login failed"), ""};
+ return {.success = false, .error = market_obj.value("description").toString("Market data login failed")};
QJsonObject market_result = market_obj.value("result").toObject();
QString feed_token = market_result.value("token").toString();
QString user_id = market_result.value("userID").toString();
if (feed_token.isEmpty())
- return {false, "", "", "", "Market data login: no token in response", ""};
+ return {.success = false, .error = "Market data login: no token in response"};
// Pack both tokens
QString packed_token = trade_token + ":::" + feed_token;
@@ -209,14 +211,16 @@ TokenExchangeResponse IIFLBroker::exchange_token(const QString& api_key, const Q
// pairs stored in api_key/api_secret — both are persisted, so the session is
// silently re-mintable. Tokens lapse at the daily reset.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, packed_token, user_id, "", extra, ""};
+ // XTS userID is the account identifier, not a refresh token — it used to be
+ // passed positionally into the refresh_token slot, which left user_id empty.
+ return {.success = true, .access_token = packed_token, .user_id = user_id, .additional_data = extra};
}
// Silent refresh = re-run the XTS interactive + market logins from the stored
// appKey/secret pairs (no TOTP/web code involved).
TokenExchangeResponse IIFLBroker::refresh_session(const BrokerCredentials& creds) {
if (creds.api_key.isEmpty() || creds.api_secret.isEmpty())
- return {false, "", "", "", "", "IIFL silent refresh requires stored app/secret keys"};
+ return {.success = false, .error = "IIFL silent refresh requires stored app/secret keys"};
return exchange_token(creds.api_key, creds.api_secret, QString());
}
@@ -239,7 +243,10 @@ OrderPlaceResponse IIFLBroker::place_order(const BrokerCredentials& creds, const
body["orderQuantity"] = static_cast<int>(order.quantity);
body["limitPrice"] = order.price;
body["stopPrice"] = order.stop_price;
- body["orderUniqueIdentifier"] = "fincept";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ body["orderUniqueIdentifier"] = make_client_order_ref(20);
auto& http = BrokerHttp::instance();
auto resp = http.post_json(
@@ -271,12 +278,15 @@ ApiResponse<QJsonObject> IIFLBroker::modify_order(const BrokerCredentials& creds
body["appOrderID"] = order_id.toLongLong();
body["modifiedProductType"] = mods.value("productType").toString("MIS");
body["modifiedOrderType"] = mods.value("orderType").toString("MARKET");
- body["modifiedOrderQuantity"] = mods.value("quantity").toInt(0);
+ body["modifiedOrderQuantity"] = static_cast<int>(modify_fields::number(mods, modify_fields::kQuantity));
body["modifiedDisclosedQuantity"] = 0;
- body["modifiedLimitPrice"] = mods.value("limitPrice").toDouble(0.0);
- body["modifiedStopPrice"] = mods.value("stopPrice").toDouble(0.0);
+ body["modifiedLimitPrice"] = modify_fields::number(mods, modify_fields::kPrice);
+ body["modifiedStopPrice"] = modify_fields::number(mods, modify_fields::kTrigger);
body["modifiedTimeInForce"] = mods.value("timeInForce").toString("DAY");
- body["orderUniqueIdentifier"] = "fincept";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ body["orderUniqueIdentifier"] = make_client_order_ref(20);
auto& http = BrokerHttp::instance();
auto resp = http.put_json(
@@ -442,6 +452,10 @@ ApiResponse<QVector<BrokerPosition>> IIFLBroker::get_positions(const BrokerCrede
pos.pnl = o.value("UnrealizedMTM").toDouble();
pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.product_type = o.value("ProductType").toString();
+ // Quantity carries the sign, but PortfolioReplicationService takes
+ // fabs() of quantity and reads direction from `side` alone — leaving it
+ // empty replicated every short as a long and inverted its P&L.
+ pos.side = qty > 0 ? "LONG" : "SHORT";
positions.append(pos);
}
diff --git a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
index 356c3a297..2a6606e22 100644
--- a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
+++ b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
@@ -267,13 +267,13 @@ TokenExchangeResponse KotakBroker::exchange_token(const QString& api_key, const
const QString ucc = parts.value(2).trimmed();
if (access_token_portal.isEmpty())
- return {false, "", "", "", "", "Access token is required (format: token|||+91mobile|||UCC)"};
+ return {.success = false, .error = "Access token is required (format: token|||+91mobile|||UCC)"};
if (ucc.isEmpty())
- return {false, "", "", "", "", "UCC is required (format: token|||+91mobile|||UCC)"};
+ return {.success = false, .error = "UCC is required (format: token|||+91mobile|||UCC)"};
if (api_secret.trimmed().isEmpty())
- return {false, "", "", "", "", "MPIN is required"};
+ return {.success = false, .error = "MPIN is required"};
if (auth_code.trimmed().isEmpty())
- return {false, "", "", "", "", "TOTP secret is required"};
+ return {.success = false, .error = "TOTP secret is required"};
// Normalise mobile to +91XXXXXXXXXX
mobile.remove(' ');
@@ -286,7 +286,7 @@ TokenExchangeResponse KotakBroker::exchange_token(const QString& api_key, const
const QString totp_code = generate_totp(auth_code.trimmed());
if (totp_code.isEmpty())
- return {false, "", "", "", "", "Failed to generate TOTP — check TOTP secret"};
+ return {.success = false, .error = "Failed to generate TOTP — check TOTP secret"};
auto& http = BrokerHttp::instance();
@@ -306,14 +306,14 @@ TokenExchangeResponse KotakBroker::exchange_token(const QString& api_key, const
auto r1 = http.post_json(LOGIN_BASE + "/login/1.0/tradeApiLogin", step1_body, step1_hdrs);
if (!r1.success) {
LOG_ERROR(TAG, "Step1 login HTTP error: " + r1.error);
- return {false, "", "", "", "", "TOTP login failed: " + r1.error};
+ return {.success = false, .error = "TOTP login failed: " + r1.error};
}
const auto d1 = r1.json.value("data").toObject();
if (d1.value("status").toString() != "success") {
const QString err = r1.json.value("errMsg").toString(r1.json.value("message").toString("TOTP login failed"));
LOG_ERROR(TAG, "Step1 login error: " + err);
- return {false, "", "", "", "", "TOTP login error: " + err};
+ return {.success = false, .error = "TOTP login error: " + err};
}
const QString view_token = d1.value("token").toString();
@@ -332,7 +332,7 @@ TokenExchangeResponse KotakBroker::exchange_token(const QString& api_key, const
auto r2 = http.post_json(LOGIN_BASE + "/login/1.0/tradeApiValidate", step2_body, step2_hdrs);
if (!r2.success) {
LOG_ERROR(TAG, "Step2 MPIN HTTP error: " + r2.error);
- return {false, "", "", "", "", "MPIN validation failed: " + r2.error};
+ return {.success = false, .error = "MPIN validation failed: " + r2.error};
}
const auto d2 = r2.json.value("data").toObject();
@@ -340,7 +340,7 @@ TokenExchangeResponse KotakBroker::exchange_token(const QString& api_key, const
const QString err =
r2.json.value("errMsg").toString(r2.json.value("message").toString("MPIN validation failed"));
LOG_ERROR(TAG, "Step2 MPIN error: " + err);
- return {false, "", "", "", "", "MPIN validation error: " + err};
+ return {.success = false, .error = "MPIN validation error: " + err};
}
const QString trading_token = d2.value("token").toString();
@@ -367,7 +367,7 @@ TokenExchangeResponse KotakBroker::exchange_token(const QString& api_key, const
const QString extra = with_token_expiry(QString::fromUtf8(QJsonDocument(extra_obj).toJson(QJsonDocument::Compact)),
next_ist_flush_epoch(6, 0));
LOG_INFO(TAG, "Kotak auth complete, ucc=" + ucc + " base_url=" + base_url + " sId=" + server_id);
- return {true, packed, /*refresh*/ "", ucc, /*additional*/ extra, ""};
+ return {.success = true, .access_token = packed, .user_id = ucc, .additional_data = extra};
}
// Silent refresh = replay the TOTP login (Step1) + MPIN validation (Step2) from
@@ -376,7 +376,7 @@ TokenExchangeResponse KotakBroker::refresh_session(const BrokerCredentials& cred
const auto extra = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();
const QString totp_secret = extra.value("totp_secret").toString();
if (creds.api_key.isEmpty() || creds.api_secret.isEmpty() || totp_secret.isEmpty())
- return {false, "", "", "", "", "Kotak silent refresh requires stored portal token, MPIN and TOTP secret"};
+ return {.success = false, .error = "Kotak silent refresh requires stored portal token, MPIN and TOTP secret"};
return exchange_token(creds.api_key, creds.api_secret, totp_secret);
}
@@ -432,8 +432,36 @@ ApiResponse<QJsonObject> KotakBroker::modify_order(const BrokerCredentials& cred
if (!p.valid)
return {false, std::nullopt, "[TOKEN_EXPIRED] Invalid session", ts};
+ // Kotak's modify endpoint is a full replace, not a patch: every field below
+ // is retransmitted and overwrites the resting order. All of them are owned
+ // by the caller, and each used to fall back to a hard-coded default — so a
+ // caller that sent only {quantity, price} silently rewrote the rest. The
+ // worst case was `side`, which defaulted to "B": modifying the price of a
+ // resting SELL or stop-loss converted it into a BUY, turning an exit into a
+ // new long entry. Never transmit a guess for a caller-owned field — fail
+ // the modify and let the caller supply the resting order's real values.
+ static const QStringList required_keys = {"side", "symbol", "exchange", "product", "order_type"};
+ for (const QString& key : required_keys) {
+ if (mods.value(key).toString().trimmed().isEmpty()) {
+ const QString err = QString("Cannot modify: order %1 unknown").arg(key);
+ LOG_ERROR(TAG, "modify_order: " + err);
+ return {false, std::nullopt, err, ts};
+ }
+ }
+
+ // Kotak's wire form is "B"/"S"; get_orders() hands callers the canonical
+ // "buy"/"sell". Accept either, reject anything else rather than guessing.
+ const QString side_in = mods.value("side").toString().trimmed().toLower();
+ QString kotak_side;
+ if (side_in == "b" || side_in == "buy")
+ kotak_side = "B";
+ else if (side_in == "s" || side_in == "sell")
+ kotak_side = "S";
+ else
+ return {false, std::nullopt, QString("Cannot modify: unrecognised order side '%1'").arg(side_in), ts};
+
const QString symbol = mods.value("symbol").toString();
- const QString exchange = mods.value("exchange").toString("NSE");
+ const QString exchange = mods.value("exchange").toString();
const QString psymbol = lookup_psymbol(symbol, exchange, creds.broker_id);
QJsonObject jobj;
@@ -447,13 +475,13 @@ ApiResponse<QJsonObject> KotakBroker::modify_order(const BrokerCredentials& cred
jobj["mp"] = "0";
jobj["dd"] = mods.value("goodtilldate").toString(""); // empty by default
jobj["vd"] = mods.value("validity").toString("DAY");
- jobj["pc"] = mods.value("product").toString("MIS");
+ jobj["pc"] = mods.value("product").toString();
jobj["pr"] = QString::number(mods.value("price").toDouble(0.0), 'f', 2);
- jobj["pt"] = mods.value("order_type").toString("L");
+ jobj["pt"] = mods.value("order_type").toString();
jobj["qt"] = QString::number(mods.value("quantity").toInt(0));
jobj["fq"] = QString::number(mods.value("filled_quantity").toInt(0));
jobj["tp"] = QString::number(mods.value("trigger_price").toDouble(0.0), 'f', 2);
- jobj["tt"] = mods.value("side").toString("B");
+ jobj["tt"] = kotak_side;
jobj["os"] = "NEOTRADEAPI";
auto hdrs = auth_headers(creds);
diff --git a/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp b/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
index 893857fa1..45068487a 100644
--- a/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
+++ b/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
@@ -53,8 +53,13 @@ QMap<QString, QString> MetaApiBroker::auth_headers(const BrokerCredentials& cred
QString MetaApiBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
if (resp.status_code == 400)
return QStringLiteral("MetaAPI: Invalid request. Check symbol and order parameters.");
- if (resp.status_code == 401)
- return QStringLiteral("MetaAPI token is invalid or expired. Get a new token from metaapi.cloud.");
+ // The [TOKEN_EXPIRED] marker is the contract BrokerInterface::validate_session
+ // classifies on (BrokerInterface.h) — without it the account reads
+ // "Connected" forever while every request 401s and the user is never
+ // prompted to reconnect.
+ if (resp.status_code == 401 || resp.status_code == 403)
+ return QStringLiteral(
+ "[TOKEN_EXPIRED] MetaAPI token is invalid or expired. Get a new token from metaapi.cloud.");
if (resp.status_code == 404)
return QStringLiteral("MT4 account not found on MetaAPI. Please re-provision.");
if (resp.status_code == 409)
diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
index edc36c1de..df96b8af9 100644
--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
@@ -1,5 +1,6 @@
#include "trading/brokers/motilal/MotilalBroker.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include "trading/instruments/InstrumentService.h"
@@ -180,24 +181,24 @@ TokenExchangeResponse MotilalBroker::exchange_token(const QString& api_key, cons
auto resp = http.post_json(QString("%1/rest/login/v3/authdirectapi").arg(BASE), body, login_headers);
if (!resp.success)
- return {false, "", "", "", "Login failed: " + resp.error, ""};
+ return {.success = false, .error = "Login failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Login: invalid response", ""};
+ return {.success = false, .error = "Login: invalid response"};
QJsonObject obj = doc.object();
if (obj.value("status").toString() != "SUCCESS")
- return {false, "", "", "", obj.value("message").toString("Login failed"), ""};
+ return {.success = false, .error = obj.value("message").toString("Login failed")};
QString token = obj.value("AuthToken").toString();
if (token.isEmpty())
- return {false, "", "", "", "Login: no AuthToken in response", ""};
+ return {.success = false, .error = "Login: no AuthToken in response"};
// Motilal AuthToken is valid for the trading day; 2FA (TOTP/OTP) can't be
// replayed silently, so detect-only. Startup hint.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, token, "", api_key, extra, ""};
+ return {.success = true, .access_token = token, .user_id = api_key, .additional_data = extra};
}
// ---------- place_order ----------
@@ -216,18 +217,28 @@ OrderPlaceResponse MotilalBroker::place_order(const BrokerCredentials& creds, co
// shares for cash. UnifiedOrder.quantity is pieces app-wide, so convert via the
// master's lot size (cash rows carry marketlot=1 → no-op). A 75-piece NIFTY
// order must not transmit as 75 lots.
- int qty_in_lot = static_cast<int>(order.quantity);
+ //
+ // Integer division must not be used to "let the broker reject it": that only
+ // holds below one lot. 100 pieces at lot 75 truncates to 1 lot = 75 pieces —
+ // accepted broker-side, but 25 pieces short of what the caller asked for and
+ // reported back as 100. Reject a non-multiple here instead of transmitting
+ // less than requested.
auto lot_inst = InstrumentService::instance().find_by_token(order.instrument_token.toUInt(), "motilal");
if (!lot_inst.has_value())
lot_inst = InstrumentService::instance().find(order.symbol, order.exchange, "motilal");
- if (lot_inst.has_value() && lot_inst->lot_size > 1)
- qty_in_lot = static_cast<int>(order.quantity) / lot_inst->lot_size; // partial lots → 0, rejects broker-side
- body["quantityinlot"] = qty_in_lot;
+ const int qty = static_cast<int>(order.quantity);
+ const int lot = (lot_inst.has_value() && lot_inst->lot_size > 1) ? lot_inst->lot_size : 1;
+ if (lot > 1 && qty % lot != 0)
+ return {false, "", QString("Quantity %1 is not a multiple of lot size %2").arg(qty).arg(lot)};
+ body["quantityinlot"] = qty / lot;
body["disclosedquantity"] = 0;
body["amoorder"] = order.amo ? "Y" : "N";
body["algoid"] = "";
body["goodtilldate"] = "";
- body["tag"] = "fincept";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Motilal caps `tag` at 10 chars.
+ body["tag"] = make_client_order_ref(10);
body["participantcode"] = "";
body["clientcode"] = creds.user_id; // required for dealer accounts; harmless for investor
@@ -282,8 +293,18 @@ ApiResponse<QJsonObject> MotilalBroker::modify_order(const BrokerCredentials& cr
if (o.value("uniqueorderid").toString() == order_id) {
const quint32 token = o.value("symboltoken").toVariant().toUInt();
auto minst = InstrumentService::instance().find_by_token(token, "motilal");
- if (minst.has_value() && minst->lot_size > 1)
- new_qty_lot = mods.value("quantity").toInt() / minst->lot_size;
+ if (minst.has_value() && minst->lot_size > 1) {
+ const int q = mods.value("quantity").toInt();
+ // Same rule as place_order: truncating a non-multiple
+ // silently modifies the order to fewer pieces than asked.
+ if (q % minst->lot_size != 0)
+ return {false, std::nullopt,
+ QString("Quantity %1 is not a multiple of lot size %2")
+ .arg(q)
+ .arg(minst->lot_size),
+ ts};
+ new_qty_lot = q / minst->lot_size;
+ }
break;
}
}
diff --git a/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp
index d2f809376..8f51a0ef4 100644
--- a/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp
+++ b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp
@@ -142,7 +142,7 @@ QMap<QString, QString> PaytmBroker::auth_headers(const BrokerCredentials& creds)
TokenExchangeResponse PaytmBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& auth_code) {
if (api_key.isEmpty() || api_secret.isEmpty() || auth_code.isEmpty())
- return {false, "", "", "", "Paytm login: api_key, api_secret and request_token are required", ""};
+ return {.success = false, .error = "Paytm login: api_key, api_secret and request_token are required"};
QJsonObject payload;
payload["api_key"] = api_key;
@@ -154,20 +154,20 @@ TokenExchangeResponse PaytmBroker::exchange_token(const QString& api_key, const
http.post_json(QString("%1/accounts/v2/gettoken").arg(BASE), payload, {{"Content-Type", "application/json"}});
if (!resp.success && resp.status_code == 0)
- return {false, "", "", "", "Login failed: " + resp.error, ""};
+ return {.success = false, .error = "Login failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Login: invalid response", ""};
+ return {.success = false, .error = "Login: invalid response"};
QJsonObject obj = doc.object();
QString access_token = obj.value("access_token").toString();
if (access_token.isEmpty())
- return {false, "", "", "", checked_error(resp, "Login failed: no access token"), ""};
+ return {.success = false, .error = checked_error(resp, "Login failed: no access token")};
// public_access_token is the WebSocket feed token — stash it in additional_data.
QString feed_token = obj.value("public_access_token").toString(access_token);
- return {true, access_token, "", "", feed_token, ""};
+ return {.success = true, .access_token = access_token, .additional_data = feed_token};
}
// ---------- place_order ----------
diff --git a/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp b/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp
index 61386d4b6..e0542dfe9 100644
--- a/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp
+++ b/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp
@@ -104,7 +104,7 @@ QMap<QString, QString> SamcoBroker::auth_headers(const BrokerCredentials& creds)
TokenExchangeResponse SamcoBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& auth_code) {
if (api_key.isEmpty() || api_secret.isEmpty() || auth_code.isEmpty())
- return {false, "", "", "", "Samco login: user id, password and secret API key are required", ""};
+ return {.success = false, .error = "Samco login: user id, password and secret API key are required"};
auto& http = BrokerHttp::instance();
@@ -115,17 +115,17 @@ TokenExchangeResponse SamcoBroker::exchange_token(const QString& api_key, const
auto tok_resp = http.post_json(QString("%1/accessToken/token").arg(BASE), tok_payload,
{{"Content-Type", "application/json"}, {"Accept", "application/json"}});
if (!tok_resp.success && tok_resp.status_code == 0)
- return {false, "", "", "", "Access token request failed: " + tok_resp.error, ""};
+ return {.success = false, .error = "Access token request failed: " + tok_resp.error};
QJsonDocument tok_doc = QJsonDocument::fromJson(tok_resp.raw_body.toUtf8());
if (!tok_doc.isObject())
- return {false, "", "", "", "Access token: invalid response", ""};
+ return {.success = false, .error = "Access token: invalid response"};
QJsonObject tok_obj = tok_doc.object();
if (tok_obj.value("status").toString() != "Success")
- return {false, "", "", "", tok_obj.value("statusMessage").toString("Access token generation failed"), ""};
+ return {.success = false, .error = tok_obj.value("statusMessage").toString("Access token generation failed")};
QString access_token = tok_obj.value("accessToken").toString();
if (access_token.isEmpty())
- return {false, "", "", "", "Access token: empty token in response", ""};
+ return {.success = false, .error = "Access token: empty token in response"};
// Step 2: login → sessionToken.
QJsonObject login_payload;
@@ -135,17 +135,17 @@ TokenExchangeResponse SamcoBroker::exchange_token(const QString& api_key, const
auto login_resp = http.post_json(QString("%1/login").arg(BASE), login_payload,
{{"Content-Type", "application/json"}, {"Accept", "application/json"}});
if (!login_resp.success && login_resp.status_code == 0)
- return {false, "", "", "", "Login failed: " + login_resp.error, ""};
+ return {.success = false, .error = "Login failed: " + login_resp.error};
QJsonDocument login_doc = QJsonDocument::fromJson(login_resp.raw_body.toUtf8());
if (!login_doc.isObject())
- return {false, "", "", "", "Login: invalid response", ""};
+ return {.success = false, .error = "Login: invalid response"};
QJsonObject login_obj = login_doc.object();
if (login_obj.value("status").toString() != "Success")
- return {false, "", "", "", login_obj.value("statusMessage").toString("Login failed"), ""};
+ return {.success = false, .error = login_obj.value("statusMessage").toString("Login failed")};
QString session = login_obj.value("sessionToken").toString();
if (session.isEmpty())
- return {false, "", "", "", "Login: no sessionToken in response", ""};
+ return {.success = false, .error = "Login: no sessionToken in response"};
// Samco's secretApiKey (auth_code) is permanent, and uid/password are stored
// — persist the secret so the daily session can be silently re-minted. Token
@@ -153,7 +153,7 @@ TokenExchangeResponse SamcoBroker::exchange_token(const QString& api_key, const
QJsonObject extra_obj{{"secret_api_key", auth_code}};
const QString extra = with_token_expiry(QString::fromUtf8(QJsonDocument(extra_obj).toJson(QJsonDocument::Compact)),
next_ist_flush_epoch(6, 0));
- return {true, session, "", api_key, extra, ""};
+ return {.success = true, .access_token = session, .user_id = api_key, .additional_data = extra};
}
// Silent refresh = replay the two-step login using the stored uid/password and
@@ -162,7 +162,7 @@ TokenExchangeResponse SamcoBroker::refresh_session(const BrokerCredentials& cred
const auto extra = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();
const QString secret_api_key = extra.value("secret_api_key").toString();
if (creds.api_key.isEmpty() || creds.api_secret.isEmpty() || secret_api_key.isEmpty())
- return {false, "", "", "", "", "Samco silent refresh requires stored user id, password and secret API key"};
+ return {.success = false, .error = "Samco silent refresh requires stored user id, password and secret API key"};
return exchange_token(creds.api_key, creds.api_secret, secret_api_key);
}
diff --git a/fincept-qt/src/trading/brokers/saxo/SaxoBankBroker.cpp b/fincept-qt/src/trading/brokers/saxo/SaxoBankBroker.cpp
index 4cd4304d1..cda2ba7f7 100644
--- a/fincept-qt/src/trading/brokers/saxo/SaxoBankBroker.cpp
+++ b/fincept-qt/src/trading/brokers/saxo/SaxoBankBroker.cpp
@@ -1,5 +1,6 @@
#include "trading/brokers/saxo/SaxoBankBroker.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include <QDateTime>
@@ -126,7 +127,7 @@ QMap<QString, QString> SaxoBankBroker::auth_headers(const BrokerCredentials& cre
TokenExchangeResponse SaxoBankBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& auth_code) {
if (auth_code.trimmed().isEmpty())
- return {false, "", "", "", "Authorization code is required", ""};
+ return {.success = false, .error = "Authorization code is required"};
// Try live token endpoint first; fall back to SIM if it fails
// In practice user should specify sim vs live via auth_code prefix "sim:::code"
@@ -146,18 +147,18 @@ TokenExchangeResponse SaxoBankBroker::exchange_token(const QString& api_key, con
{{"Content-Type", "application/x-www-form-urlencoded"}, {"Accept", "application/json"}});
if (!resp.success)
- return {false, "", "", "", "Token exchange failed: " + resp.error, ""};
+ return {.success = false, .error = "Token exchange failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Token exchange: invalid response", ""};
+ return {.success = false, .error = "Token exchange: invalid response"};
QJsonObject obj = doc.object();
QString access_token = obj.value("access_token").toString();
QString refresh_token = obj.value("refresh_token").toString();
if (access_token.isEmpty())
- return {false, "", "", "", obj.value("error_description").toString("Token exchange failed"), ""};
+ return {.success = false, .error = obj.value("error_description").toString("Token exchange failed")};
// Fetch AccountKey from /port/v1/clients/me
QString base = use_sim ? BASE_SIM : BASE_LIVE;
@@ -175,7 +176,7 @@ TokenExchangeResponse SaxoBankBroker::exchange_token(const QString& api_key, con
}
// Pack refresh_token into additional field
- return {true, access_token, refresh_token, account_key, "", ""};
+ return {.success = true, .access_token = access_token, .refresh_token = refresh_token, .user_id = account_key};
}
// ---------- place_order ----------
@@ -199,6 +200,10 @@ OrderPlaceResponse SaxoBankBroker::place_order(const BrokerCredentials& creds, c
order_obj["Amount"] = order.quantity;
order_obj["OrderType"] = saxo_enum_map().order_type_or(order.order_type, "Market");
order_obj["ManualOrder"] = false;
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h).
+ order_obj["ExternalReference"] = make_client_order_ref(50);
if (order.order_type != OrderType::Market)
order_obj["OrderPrice"] = order.price;
diff --git a/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.cpp b/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.cpp
index 4b6630437..a2aac87a2 100644
--- a/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.cpp
@@ -1,5 +1,7 @@
#include "trading/brokers/shoonya/ShoonyaBroker.h"
+#include "trading/brokers/BrokerModifyFields.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -129,26 +131,26 @@ TokenExchangeResponse ShoonyaBroker::exchange_token(const QString& api_key, cons
{{"Content-Type", "application/x-www-form-urlencoded"}});
if (!resp.success)
- return {false, "", "", "", "Login failed: " + resp.error, ""};
+ return {.success = false, .error = "Login failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Login: invalid response", ""};
+ return {.success = false, .error = "Login: invalid response"};
QJsonObject obj = doc.object();
if (obj.value("stat").toString() != "Ok")
- return {false, "", "", "", obj.value("emsg").toString("Login failed"), ""};
+ return {.success = false, .error = obj.value("emsg").toString("Login failed")};
QString token = obj.value("susertoken").toString();
QString uid = obj.value("uid").toString(api_key);
if (token.isEmpty())
- return {false, "", "", "", "Login: no susertoken in response", ""};
+ return {.success = false, .error = "Login: no susertoken in response"};
// Shoonya session tokens lapse at the daily reset; factor2 (TOTP/OTP) is a
// one-time code we can't replay, so detect-only. Startup hint.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, token, "", uid, extra, ""};
+ return {.success = true, .access_token = token, .user_id = uid, .additional_data = extra};
}
// ---------- place_order ----------
@@ -169,7 +171,10 @@ OrderPlaceResponse ShoonyaBroker::place_order(const BrokerCredentials& creds, co
jdata["prc"] = QString::number(order.price, 'f', 2);
jdata["trgprc"] = QString::number(order.stop_price, 'f', 2);
jdata["ret"] = order.validity.isEmpty() ? "DAY" : order.validity;
- jdata["remarks"] = "fincept";
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ jdata["remarks"] = make_client_order_ref(20);
// ordersource is a PlaceOrder-only field per NorenAPI spec (values: WEB/MOB/TT).
jdata["ordersource"] = "WEB";
@@ -207,9 +212,14 @@ ApiResponse<QJsonObject> ShoonyaBroker::modify_order(const BrokerCredentials& cr
jdata["qty"] = QString::number(mods.value("quantity").toInt(0));
jdata["prctyp"] = mods.value("orderType").toString("LMT");
jdata["prc"] = QString::number(mods.value("price").toDouble(0), 'f', 2);
- jdata["trgprc"] = QString::number(mods.value("triggerPrice").toDouble(0), 'f', 2);
jdata["dscqty"] = "0";
jdata["ret"] = mods.value("validity").toString("DAY");
+ // Only include trigger price for SL/SL-M — trgprc=0 on LMT causes a reject.
+ // (Same guard as the line-identical Noren twin in FlattradeBroker.)
+ const QString prctyp = jdata["prctyp"].toString();
+ if (prctyp == "SL-LMT" || prctyp == "SL-MKT")
+ jdata["trgprc"] = QString::number(
+ modify_fields::number(mods, modify_fields::kTrigger), 'f', 2);
// ordersource not part of ModifyOrder spec — omit.
auto& http = BrokerHttp::instance();
diff --git a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
index d5b3a3267..0b4ede3cb 100644
--- a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
+++ b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
@@ -1,4 +1,5 @@
#include "trading/brokers/tradejini/TradejiniBroker.h"
+#include "trading/brokers/BrokerModifyFields.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -104,7 +105,7 @@ QMap<QString, QString> TradejiniBroker::auth_headers(const BrokerCredentials& cr
TokenExchangeResponse TradejiniBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& auth_code) {
if (api_key.isEmpty() || api_secret.isEmpty() || auth_code.isEmpty())
- return {false, "", "", "", "Tradejini login: api_key, password and TOTP are required", ""};
+ return {.success = false, .error = "Tradejini login: api_key, password and TOTP are required"};
QMap<QString, QString> params;
params["password"] = api_secret;
@@ -116,21 +117,21 @@ TokenExchangeResponse TradejiniBroker::exchange_token(const QString& api_key, co
{{"Authorization", QString("Bearer %1").arg(api_key)}});
if (!resp.success && resp.status_code == 0)
- return {false, "", "", "", "Login failed: " + resp.error, ""};
+ return {.success = false, .error = "Login failed: " + resp.error};
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Login: invalid response", ""};
+ return {.success = false, .error = "Login: invalid response"};
QJsonObject obj = doc.object();
QString token = obj.value("access_token").toString();
if (token.isEmpty())
- return {false, "", "", "", obj.value("message").toString("Login failed: no access token"), ""};
+ return {.success = false, .error = obj.value("message").toString("Login failed: no access token")};
// Tradejini tokens expire at the daily reset; the TOTP is a one-time code we
// can't replay, so detect-only. Startup hint.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(6, 0));
- return {true, token, "", "", extra, ""};
+ return {.success = true, .access_token = token, .additional_data = extra};
}
// ---------- place_order ----------
@@ -182,7 +183,31 @@ ApiResponse<QJsonObject> TradejiniBroker::modify_order(const BrokerCredentials&
const QJsonObject& mods) {
int64_t ts = now_ts();
- const QString price_type = mods.value("orderType").toString("limit").toLower();
+ // Tradejini's modify endpoint is a full replace, not a patch: every field
+ // below overwrites the resting order. All of them are caller-owned and each
+ // used to fall back to a hard-coded default, so a caller that sent only
+ // {quantity, price} silently rewrote the rest. The worst case was `side`,
+ // which defaulted to "buy": modifying the price of a resting SELL or
+ // stop-loss converted it into a BUY, turning an exit into a new long entry.
+ // Never transmit a guess for a caller-owned field.
+ static const QStringList required_keys = {"side", "symbol", "orderType"};
+ for (const QString& key : required_keys) {
+ if (mods.value(key).toString().trimmed().isEmpty())
+ return {false, std::nullopt, QString("Cannot modify: order %1 unknown").arg(key), ts};
+ }
+
+ // Tradejini's wire form is "buy"/"sell"; accept the short forms too, and
+ // reject anything else rather than guessing a direction.
+ const QString side_in = mods.value("side").toString().trimmed().toLower();
+ QString tj_side;
+ if (side_in == "b" || side_in == "buy")
+ tj_side = "buy";
+ else if (side_in == "s" || side_in == "sell")
+ tj_side = "sell";
+ else
+ return {false, std::nullopt, QString("Cannot modify: unrecognised order side '%1'").arg(side_in), ts};
+
+ const QString price_type = mods.value("orderType").toString().toLower();
QString tj_type = "limit";
if (price_type.contains("market") && price_type.contains("stop"))
tj_type = "stopmarket";
@@ -197,11 +222,11 @@ ApiResponse<QJsonObject> TradejiniBroker::modify_order(const BrokerCredentials&
params["qty"] = QString::number(mods.value("quantity").toInt(0));
params["type"] = tj_type;
params["validity"] = "day";
- params["side"] = mods.value("side").toString("buy").toLower();
+ params["side"] = tj_side;
if (tj_type == "limit" || tj_type == "stoplimit")
- params["limitPrice"] = QString::number(mods.value("price").toDouble(0), 'f', 2);
+ params["limitPrice"] = QString::number(modify_fields::number(mods, modify_fields::kPrice), 'f', 2);
if (tj_type == "stoplimit" || tj_type == "stopmarket")
- params["trigPrice"] = QString::number(mods.value("triggerPrice").toDouble(0), 'f', 2);
+ params["trigPrice"] = QString::number(modify_fields::number(mods, modify_fields::kTrigger), 'f', 2);
auto& http = BrokerHttp::instance();
auto resp = http.put_form(QString("%1/api/oms/modify-order").arg(BASE), params, {{"Authorization", bearer(creds)}});
diff --git a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
index 7e486cd20..1f5f49bd9 100644
--- a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
+++ b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
@@ -1,5 +1,6 @@
#include "trading/brokers/tradier/TradierBroker.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include <QDateTime>
@@ -94,7 +95,7 @@ QMap<QString, QString> TradierBroker::auth_headers(const BrokerCredentials& cred
TokenExchangeResponse TradierBroker::exchange_token(const QString& api_key, const QString& api_secret,
const QString& /*auth_code*/) {
if (api_key.trimmed().isEmpty())
- return {false, "", "", "", "Access token is required", ""};
+ return {.success = false, .error = "Access token is required"};
QString env_base = (api_secret.trimmed().toLower() == "sandbox" || api_secret.trimmed().toLower() == "paper")
? "https://sandbox.tradier.com"
@@ -106,17 +107,17 @@ TokenExchangeResponse TradierBroker::exchange_token(const QString& api_key, cons
if (!resp.success) {
if (resp.status_code == 401)
- return {false, "", "", "", "[TOKEN_EXPIRED] Access token is invalid or expired", ""};
- return {false, "", "", "", "Profile fetch failed: " + resp.error, ""};
+ return {.success = false, .error = "[TOKEN_EXPIRED] Access token is invalid or expired"};
+ return {.success = false, .error = "Profile fetch failed: " + resp.error};
}
QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
if (!doc.isObject())
- return {false, "", "", "", "Profile: invalid response", ""};
+ return {.success = false, .error = "Profile: invalid response"};
QJsonObject profile = doc.object().value("profile").toObject();
if (profile.isEmpty())
- return {false, "", "", "", "Profile: missing profile object", ""};
+ return {.success = false, .error = "Profile: missing profile object"};
// account may be object (single) or array (multiple) — take first
QString account_id;
@@ -128,9 +129,9 @@ TokenExchangeResponse TradierBroker::exchange_token(const QString& api_key, cons
}
if (account_id.isEmpty())
- return {false, "", "", "", "Profile: could not find account_number", ""};
+ return {.success = false, .error = "Profile: could not find account_number"};
- return {true, api_key, "", account_id, "", ""};
+ return {.success = true, .access_token = api_key, .user_id = account_id};
}
// ---------- place_order ----------
@@ -150,7 +151,10 @@ OrderPlaceResponse TradierBroker::place_order(const BrokerCredentials& creds, co
form.addQueryItem("price", QString::number(order.price, 'f', 2));
if (order.stop_price > 0)
form.addQueryItem("stop", QString::number(order.stop_price, 'f', 2));
- form.addQueryItem("tag", "fincept");
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ form.addQueryItem("tag", make_client_order_ref(20));
QMap<QString, QString> hdrs = auth_headers(creds);
hdrs["Content-Type"] = "application/x-www-form-urlencoded";
diff --git a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp
index 881993d83..34c74b1ad 100644
--- a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp
+++ b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp
@@ -2,6 +2,7 @@
#include "core/logging/Logger.h"
#include "trading/adapter/BrokerEnumMap.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerTokenUtil.h"
#include "trading/instruments/InstrumentService.h"
@@ -163,7 +164,7 @@ TokenExchangeResponse UpstoxBroker::exchange_token(const QString& api_key, const
if (!resp.success) {
LOG_ERROR("Upstox", "exchange_token HTTP error: " + resp.error);
- return {false, "", "", "", "", resp.error};
+ return {.success = false, .error = resp.error};
}
// Success: {"access_token":"...","extended_token":"...","user_id":"..."}
@@ -172,18 +173,18 @@ TokenExchangeResponse UpstoxBroker::exchange_token(const QString& api_key, const
const QString user = resp.json.value("user_id").toString();
if (access.isEmpty()) {
const QString err = checked_error(resp, "Empty access_token in response");
- return {false, "", "", "", "", err};
+ return {.success = false, .error = err};
}
// Upstox tokens expire daily at 03:30 IST regardless of when issued.
// There is no OAuth refresh token, so on expiry the user must re-auth.
const QString extra = with_token_expiry({}, next_ist_flush_epoch(3, 30));
LOG_INFO("Upstox", "Token exchange OK, user=" + user);
- return {true, access, /*refresh*/ "", user, /*additional*/ extra, ""};
+ return {.success = true, .access_token = access, .user_id = user, .additional_data = extra};
}
const QString err = checked_error(resp, "Token exchange failed");
LOG_ERROR("Upstox", "exchange_token failed: " + err);
- return {false, "", "", "", "", err};
+ return {.success = false, .error = err};
}
// ── Place Order ───────────────────────────────────────────────────────────────
@@ -202,7 +203,10 @@ OrderPlaceResponse UpstoxBroker::place_order(const BrokerCredentials& creds, con
body["trigger_price"] = order.stop_price;
body["disclosed_quantity"] = 0;
body["is_amo"] = order.amo;
- body["tag"] = "fincept"; // visible in order history for reconciliation
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Was the constant "fincept", which deduplicated nothing.
+ body["tag"] = make_client_order_ref(20); // also visible in order history for reconciliation
auto& http = BrokerHttp::instance();
// v2 order mutations live on the HFT host; api.upstox.com returns 404 for /order/*
diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
index dbbed175e..81f103cd4 100644
--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
@@ -2,6 +2,7 @@
#include "core/logging/Logger.h"
#include "trading/adapter/BrokerEnumMap.h"
+#include "trading/brokers/BrokerClientOrderId.h"
#include "trading/brokers/BrokerHttp.h"
#include "trading/brokers/BrokerLogRedact.h"
#include "trading/brokers/BrokerTokenUtil.h"
@@ -43,7 +44,7 @@ TokenExchangeResponse ZerodhaBroker::refresh_session(const BrokerCredentials& cr
const QString password = extra.value("password").toString();
const QString totp_secret = extra.value("totp_secret").toString();
if (creds.user_id.isEmpty() || password.isEmpty() || totp_secret.isEmpty()) {
- return {false, "", "", "", "", "Zerodha silent refresh requires stored user id, password and TOTP secret"};
+ return {.success = false, .error = "Zerodha silent refresh requires stored user id, password and TOTP secret"};
}
return login_with_totp(creds.user_id, password, creds.api_key, creds.api_secret, totp_secret, {});
}
@@ -211,7 +212,10 @@ OrderPlaceResponse ZerodhaBroker::place_order(const BrokerCredentials& creds, co
{"product", kite_enum_map().product_or(order.product_type, "MIS")},
{"validity", order.validity.isEmpty() ? "DAY" : order.validity},
{"disclosed_quantity", "0"},
- {"tag", "fincept"},
+ // Unique per attempt so a retry after an 8s client-side timeout is a
+ // broker-side duplicate rather than a second live order (see
+ // BrokerClientOrderId.h). Kite caps `tag` at 20 alphanumeric chars.
+ {"tag", make_client_order_ref(20)},
};
if (order.price > 0)
params["price"] = QString::number(order.price, 'f', 2);
@@ -235,17 +239,33 @@ ApiResponse<QJsonObject> ZerodhaBroker::modify_order(const BrokerCredentials& cr
const QJsonObject& mods) {
QString variety = mods.value("variety").toString("regular");
QMap<QString, QString> params;
+
+ // The numeric fields arrive as JSON NUMBERS (every caller inserts doubles).
+ // QJsonValue::toString() returns an EMPTY string for a non-string value, so
+ // reading them that way sent Kite `quantity=`, `price=` and `trigger_price=`
+ // on every modify. Go through toVariant(), which yields the value for both a
+ // numeric and a string JSON node, and format exactly as place_order does:
+ // integral quantities, 2-decimal prices.
+ auto as_int_str = [&mods](const char* key) {
+ return QString::number(static_cast<int>(mods.value(QLatin1String(key)).toVariant().toDouble()));
+ };
+ auto as_price_str = [&mods](const char* key) {
+ return QString::number(mods.value(QLatin1String(key)).toVariant().toDouble(), 'f', 2);
+ };
+
if (mods.contains("order_type"))
- params["order_type"] = mods.value("order_type").toString();
+ params["order_type"] = mods.value("order_type").toVariant().toString();
if (mods.contains("quantity"))
- params["quantity"] = mods.value("quantity").toString();
+ params["quantity"] = as_int_str("quantity");
if (mods.contains("price"))
- params["price"] = mods.value("price").toString();
+ params["price"] = as_price_str("price");
if (mods.contains("trigger_price"))
- params["trigger_price"] = mods.value("trigger_price").toString();
+ params["trigger_price"] = as_price_str("trigger_price");
if (mods.contains("disclosed_quantity"))
- params["disclosed_quantity"] = mods.value("disclosed_quantity").toString();
- params["validity"] = mods.value("validity").toString("DAY");
+ params["disclosed_quantity"] = as_int_str("disclosed_quantity");
+ params["validity"] = mods.value("validity").toVariant().toString();
+ if (params["validity"].isEmpty())
+ params["validity"] = QStringLiteral("DAY");
auto resp = BrokerHttp::instance().put_form(QString("%1/orders/%2/%3").arg(base_url(), variety, order_id), params,
auth_headers(creds));
diff --git a/fincept-qt/src/trading/instruments/InstrumentRepository.cpp b/fincept-qt/src/trading/instruments/InstrumentRepository.cpp
index 6e58e62d4..6d8add538 100644
--- a/fincept-qt/src/trading/instruments/InstrumentRepository.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentRepository.cpp
@@ -64,27 +64,39 @@ fincept::Result<void> InstrumentRepository::replace_all(const QString& broker_id
// transaction still "succeeds". Coalesce nulls to "" so the row persists.
auto nn = [](const QString& s) { return s.isNull() ? QStringLiteral("") : s; };
+ // One prepare, N binds. The previous loop called exec_write() per instrument,
+ // and exec_write() → Database::execute() re-prepares the statement every
+ // call — a broker master contract is ~100k rows, so an import paid 100k
+ // sqlite3_prepare_v2 compilations of this one identical INSERT.
+ // execute_many() opens no transaction of its own, so it runs inside the
+ // begin_transaction() above and the whole import is still a single commit.
+ QVector<QVariantList> rows;
+ rows.reserve(instruments.size());
for (const auto& inst : instruments) {
- auto ri = exec_write(sql, {
- inst.instrument_token,
- inst.exchange_token,
- nn(inst.symbol),
- nn(inst.brsymbol),
- nn(inst.name),
- nn(inst.exchange),
- nn(inst.brexchange),
- nn(inst.expiry),
- inst.strike,
- inst.lot_size,
- QString(instrument_type_str(inst.instrument_type)),
- inst.tick_size,
- broker_id,
- nn(inst.broker_token),
- });
- if (ri.is_err()) {
- db().rollback();
- return ri;
- }
+ rows.append(QVariantList{
+ inst.instrument_token,
+ inst.exchange_token,
+ nn(inst.symbol),
+ nn(inst.brsymbol),
+ nn(inst.name),
+ nn(inst.exchange),
+ nn(inst.brexchange),
+ nn(inst.expiry),
+ inst.strike,
+ inst.lot_size,
+ QString(instrument_type_str(inst.instrument_type)),
+ inst.tick_size,
+ broker_id,
+ nn(inst.broker_token),
+ });
+ }
+
+ auto ri = db().execute_many(sql, rows);
+ if (ri.is_err()) {
+ LOG_ERROR("InstrumentRepo", QString("replace_all bulk insert failed for %1: %2")
+ .arg(broker_id, QString::fromStdString(ri.error())));
+ db().rollback();
+ return ri;
}
auto rc2 = db().commit();
diff --git a/fincept-qt/src/trading/instruments/InstrumentService.cpp b/fincept-qt/src/trading/instruments/InstrumentService.cpp
index 13d2721fa..8ac779308 100644
--- a/fincept-qt/src/trading/instruments/InstrumentService.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentService.cpp
@@ -257,12 +257,12 @@ void InstrumentService::refresh(const QString& broker_id, const BrokerCredential
// Instruments on disk are fresh but may not be in the in-memory
// cache yet (e.g. first refresh() of a relaunch within
// max_age_hours). Without this, is_loaded() stays false forever
- // and every lookup fails. load_from_db() uses the shared
- // main-thread QSqlDatabase connection; refresh() is only ever
- // called from the UI/main thread (ChainSubTab + EquityTradingScreen
- // callbacks), so this is safe here.
- if (!is_loaded(broker_id))
- load_from_db(broker_id);
+ // and every lookup fails. refresh() is called from the UI thread
+ // (ChainSubTab + EquityTradingScreen callbacks) and a broker
+ // master is 100k+ rows, so the load goes through the async twin
+ // — it opens its own worker-thread connection and rebuilds the
+ // cache back on this thread (§P1).
+ load_from_db_async(broker_id, {});
return;
}
}
@@ -314,20 +314,23 @@ void InstrumentService::force_refresh(const QString& broker_id, const BrokerCred
}
void InstrumentService::load_from_db(const QString& broker_id) {
- // Called at startup before QApplication::exec() — runs synchronously on
- // the main thread so that the single QSqlDatabase connection is not
- // accessed concurrently (QSqlDatabase is not thread-safe).
- QVector<Instrument> all;
- for (const QString& exch : QStringList{"NSE", "BSE", "NFO", "CDS", "MCX", "NSE_INDEX", "BSE_INDEX", "BFO", "BCD"}) {
- auto rows = InstrumentRepository::instance().list(exch, broker_id);
- all.append(rows);
- }
- if (all.isEmpty()) {
- LOG_WARN("InstrumentService", QString("No instruments found in DB for %1 — run refresh").arg(broker_id));
- return;
- }
- build_cache(broker_id, all);
- LOG_INFO("InstrumentService", QString("Loaded %1 instruments from DB for %2").arg(all.size()).arg(broker_id));
+ // DEPRECATED shim — kept only so out-of-tree call sites keep linking.
+ //
+ // The old body ran nine unbounded `SELECT ... WHERE exchange=? AND
+ // broker_id=? ORDER BY symbol` queries on the shared main-thread
+ // connection, on the claim that it "runs at startup before
+ // QApplication::exec()". That was false: PortfolioReplicationDialog calls
+ // it twice on every combo change, and refresh() reaches it from the Equity
+ // Trading / options-chain callbacks. A broker master is 100k+ rows, so the
+ // UI froze for the whole scan (§P1).
+ //
+ // Forwarding to the async twin preserves the common case exactly —
+ // load_from_db_async() short-circuits synchronously when the cache is
+ // already warm — and moves only the genuinely cold load onto a worker
+ // thread with its own private connection. New code should call
+ // load_from_db_async() (UI thread) or load_from_db_worker() (already off
+ // the UI thread) directly.
+ load_from_db_async(broker_id, {});
}
void InstrumentService::load_from_db_async(const QString& broker_id, std::function<void(int)> callback) {
diff --git a/fincept-qt/src/trading/websocket/UpstoxWebSocket.cpp b/fincept-qt/src/trading/websocket/UpstoxWebSocket.cpp
index b8e897421..3a73c3810 100644
--- a/fincept-qt/src/trading/websocket/UpstoxWebSocket.cpp
+++ b/fincept-qt/src/trading/websocket/UpstoxWebSocket.cpp
@@ -124,8 +124,14 @@ class ProtoReader {
return false;
}
+ // Bytes still unread. Every bounds check below compares against THIS value
+ // rather than doing `p_ + n > end_`: with an attacker-controlled 64-bit
+ // varint length, `p_ + len` wraps modulo 2^64 and silently lands *below*
+ // end_, letting the guard pass with p_ far out of bounds.
+ uint64_t remaining() const { return static_cast<uint64_t>(end_ - p_); }
+
bool read_double(double& out) {
- if (p_ + 8 > end_)
+ if (remaining() < 8)
return false;
uint64_t bits = 0;
std::memcpy(&bits, p_, 8); // little-endian on all supported platforms
@@ -135,7 +141,7 @@ class ProtoReader {
}
bool read_float(float& out) {
- if (p_ + 4 > end_)
+ if (remaining() < 4)
return false;
uint32_t bits = 0;
std::memcpy(&bits, p_, 4);
@@ -149,7 +155,11 @@ class ProtoReader {
uint64_t len = 0;
if (!read_varint(len))
return false;
- if (p_ + len > end_)
+ // NEVER `p_ + len > end_` here — len is a full 64-bit varint straight
+ // off the wire and the pointer add wraps modulo 2^64, landing below
+ // end_ and passing the guard. Compare against the byte count instead;
+ // that also bounds len by the buffer size, so the size_t cast is safe.
+ if (len > remaining())
return false;
begin = p_;
length = static_cast<size_t>(len);
@@ -165,7 +175,7 @@ class ProtoReader {
return read_varint(v);
}
case 1: // 64-bit
- if (p_ + 8 > end_)
+ if (remaining() < 8)
return false;
p_ += 8;
return true;
@@ -175,7 +185,7 @@ class ProtoReader {
return read_bytes(b, l);
}
case 5: // 32-bit
- if (p_ + 4 > end_)
+ if (remaining() < 4)
return false;
p_ += 4;
return true;
@@ -250,7 +260,7 @@ PbOhlc decode_ohlc(const uint8_t* data, size_t len) {
const uint8_t* b;
size_t l;
if (r.read_bytes(b, l))
- out.interval = QString::fromUtf8(reinterpret_cast<const char*>(b), int(l));
+ out.interval = QString::fromUtf8(reinterpret_cast<const char*>(b), static_cast<qsizetype>(l));
} else if (fn == 2 && wt == 1) {
r.read_double(out.open);
} else if (fn == 3 && wt == 1) {
@@ -685,7 +695,8 @@ void UpstoxWebSocket::parse_feed_response(const QByteArray& data) {
size_t el;
if (efn == 1 && ewt == 2) {
if (entry.read_bytes(eb, el))
- instrument_key = QString::fromUtf8(reinterpret_cast<const char*>(eb), int(el));
+ instrument_key =
+ QString::fromUtf8(reinterpret_cast<const char*>(eb), static_cast<qsizetype>(el));
} else if (efn == 2 && ewt == 2) {
if (entry.read_bytes(eb, el)) {
feed = decode_feed(eb, el);
diff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cpp
index 18e831def..ac28d304b 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.cpp
+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp
@@ -119,6 +119,16 @@ ToolBar::ToolBar(QWidget* parent) : QWidget(parent) {
plan_btn_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(plan_btn_, &QPushButton::clicked, this, &ToolBar::plan_clicked);
hl->addWidget(plan_btn_);
+
+ // Enterprise CTA. Deliberately added without its own separator: the
+ // credits/chat visibility toggles in apply_responsive_layout() index into
+ // separators_ by position, so inserting one here would shift them.
+ upgrade_btn_ = new QPushButton;
+ upgrade_btn_->setFixedHeight(20);
+ upgrade_btn_->setCursor(Qt::PointingHandCursor);
+ upgrade_btn_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+ connect(upgrade_btn_, &QPushButton::clicked, this, &ToolBar::upgrade_clicked);
+ hl->addWidget(upgrade_btn_);
sep();
chat_mode_btn_ = new QPushButton;
@@ -168,6 +178,13 @@ void ToolBar::retranslateUi() {
live_label_->setText(tr(" LIVE"));
if (plan_btn_)
plan_btn_->setToolTip(tr("View Plans & Pricing"));
+ if (upgrade_btn_) {
+ // U+25B4 up-pointing triangle as an icon; only the label translates.
+ // fromUtf8 is required — QStringLiteral would widen each UTF-8 byte
+ // into its own UTF-16 unit and render as mojibake.
+ upgrade_btn_->setText(QString::fromUtf8("\xe2\x96\xb4 ") + tr("UPGRADE"));
+ upgrade_btn_->setToolTip(tr("Upgrade to Fincept Terminal Enterprise — the private edition"));
+ }
if (chat_mode_btn_) {
// Keep the ⬡ glyph (U+2B21) as a visual icon; only the label after it
// translates. Must use fromUtf8 to decode the UTF-8 bytes — wrapping
@@ -228,6 +245,15 @@ void ToolBar::refresh_theme() {
"QPushButton:hover{color:%2;}")
.arg(colors::TEXT_PRIMARY())
.arg(colors::AMBER()));
+ // Filled rather than outlined — the only solid button on the row, so the
+ // Enterprise CTA reads as the primary action next to LOGOUT and CHAT.
+ if (upgrade_btn_)
+ upgrade_btn_->setStyleSheet(QString("QPushButton{background:%1;color:%2;border:1px solid %1;"
+ "padding:0 8px;font-weight:700;}"
+ "QPushButton:hover{background:%3;border-color:%3;}")
+ .arg(colors::AMBER())
+ .arg(colors::BG_BASE())
+ .arg(colors::AMBER_DIM()));
if (chat_mode_btn_)
chat_mode_btn_->setStyleSheet(QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
"padding:0 8px;font-weight:700;}"
diff --git a/fincept-qt/src/ui/navigation/ToolBar.h b/fincept-qt/src/ui/navigation/ToolBar.h
index 53cc1889a..65b8d47c8 100644
--- a/fincept-qt/src/ui/navigation/ToolBar.h
+++ b/fincept-qt/src/ui/navigation/ToolBar.h
@@ -33,6 +33,7 @@ class ToolBar : public QWidget {
void action_triggered(const QString& action);
void logout_clicked();
void plan_clicked();
+ void upgrade_clicked();
void chat_mode_toggled();
protected:
@@ -52,6 +53,8 @@ class ToolBar : public QWidget {
QLabel* live_dot_ = nullptr;
QLabel* live_label_ = nullptr;
QPushButton* plan_btn_ = nullptr;
+ /// Always-visible CTA for Fincept Terminal Enterprise (the private edition).
+ QPushButton* upgrade_btn_ = nullptr;
QPushButton* chat_mode_btn_ = nullptr;
QPushButton* logout_btn_ = nullptr;
QTimer* clock_timer_ = nullptr;
diff --git a/fincept-qt/src/ui/tables/DataTable.cpp b/fincept-qt/src/ui/tables/DataTable.cpp
index fcd92a73a..d118b5238 100644
--- a/fincept-qt/src/ui/tables/DataTable.cpp
+++ b/fincept-qt/src/ui/tables/DataTable.cpp
@@ -6,6 +6,13 @@
namespace fincept::ui {
+namespace {
+/// Uniform row height, applied once on the vertical header in the constructor
+/// rather than per row. Kept in sync with the `height: 26px` item rule in the
+/// stylesheet below.
+constexpr int kRowHeightPx = 26;
+} // namespace
+
DataTable::DataTable(QWidget* parent) : QTableWidget(parent) {
setAlternatingRowColors(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
@@ -13,6 +20,12 @@ DataTable::DataTable(QWidget* parent) : QTableWidget(parent) {
setEditTriggers(QAbstractItemView::NoEditTriggers);
setShowGrid(false);
verticalHeader()->setVisible(false);
+ // Row height is uniform, so set it once here rather than calling
+ // setRowHeight() per row (each call triggers a geometry recalculation).
+ // setSectionResizeMode(Fixed) also lets the view skip per-row height
+ // queries entirely when laying out.
+ verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
+ verticalHeader()->setDefaultSectionSize(kRowHeightPx);
horizontalHeader()->setStretchLastSection(true);
horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
// NOTE: sorting is intentionally NOT enabled here.
@@ -33,12 +46,35 @@ void DataTable::set_headers(const QStringList& headers) {
}
void DataTable::set_data(const QVector<QStringList>& rows) {
- setRowCount(0);
- for (const auto& row : rows) {
- add_row(row);
+ // Size the model once, then fill. The previous form called add_row() per
+ // row, and add_row() calls insertRow() — an O(n) model mutation that emits
+ // rowsInserted every time, so the attached view ran a layout pass per row
+ // and the whole fill was O(n²) in view work. This is the one shared table
+ // abstraction in the codebase, so the pattern propagated by example.
+ //
+ // Bulk updates are also suppressed and re-enabled around the fill; without
+ // it the viewport repaints on every setItem.
+ const bool had_updates = updatesEnabled();
+ setUpdatesEnabled(false);
+ const bool was_sorting = isSortingEnabled();
+ setSortingEnabled(false); // sorting during a fill reorders rows mid-insert
+
+ setRowCount(rows.size());
+ for (int r = 0; r < rows.size(); ++r) {
+ const QStringList& row = rows[r];
+ for (int c = 0; c < row.size() && c < columnCount(); ++c) {
+ auto* item = new QTableWidgetItem(row[c]);
+ item->setForeground(QColor(colors::WHITE()));
+ setItem(r, c, item);
+ }
}
+
+ setSortingEnabled(was_sorting);
+ setUpdatesEnabled(had_updates);
}
+/// Appends a single row. Kept incremental for callers that genuinely add one
+/// row at a time; prefer set_data() for a bulk fill — see the note there.
void DataTable::add_row(const QStringList& row) {
int r = rowCount();
insertRow(r);
@@ -47,7 +83,9 @@ void DataTable::add_row(const QStringList& row) {
item->setForeground(QColor(colors::WHITE()));
setItem(r, c, item);
}
- setRowHeight(r, 26);
+ // Row height is a per-table constant, not a per-row property — it is set
+ // once on the vertical header in the constructor. Calling setRowHeight()
+ // here forced a geometry recalculation for every appended row.
}
void DataTable::clear_data() {
diff --git a/fincept-qt/src/ui/widgets/EnterprisePromo.cpp b/fincept-qt/src/ui/widgets/EnterprisePromo.cpp
new file mode 100644
index 000000000..39d984d97
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/EnterprisePromo.cpp
@@ -0,0 +1,296 @@
+#include "ui/widgets/EnterprisePromo.h"
+
+#include "core/config/AppConfig.h"
+#include "ui/theme/Theme.h"
+
+#include <QCheckBox>
+#include <QDesktopServices>
+#include <QGuiApplication>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QPushButton>
+#include <QUrl>
+#include <QVBoxLayout>
+
+namespace fincept::ui {
+
+namespace {
+
+/// AppConfig key for the "Don't show this again" opt-out.
+constexpr const char* kEntSuppressKey = "ui/upgrade_prompt_suppressed";
+
+/// A platform plugin with no window system — headless CI, --smoke-test runs
+/// under offscreen. A modal there would block until the process is killed.
+bool ent_headless_platform() {
+ const QString p = QGuiApplication::platformName();
+ return p.isEmpty() || p == QLatin1String("offscreen") || p == QLatin1String("minimal");
+}
+
+QString ent_accent_button_ss() {
+ return QString("QPushButton{background:%1;color:%2;border:1px solid %1;"
+ "padding:7px 18px;font-weight:700;}"
+ "QPushButton:hover{background:%3;border-color:%3;}")
+ .arg(colors::AMBER())
+ .arg(colors::BG_BASE())
+ .arg(colors::AMBER_DIM());
+}
+
+QString ent_ghost_button_ss() {
+ return QString("QPushButton{background:transparent;color:%1;border:1px solid %2;"
+ "padding:7px 18px;font-weight:700;}"
+ "QPushButton:hover{color:%3;border-color:%3;}")
+ .arg(colors::TEXT_SECONDARY())
+ .arg(colors::BORDER_DIM())
+ .arg(colors::AMBER());
+}
+
+} // namespace
+
+// ── Canonical destinations ───────────────────────────────────────────────────
+
+namespace enterprise {
+
+QString site_url() {
+ return QStringLiteral("https://fincept.in/enterprise");
+}
+QString pricing_url() {
+ return QStringLiteral("https://fincept.in/pricing");
+}
+QString comparison_url() {
+ return QStringLiteral("https://fincept.in/comparison");
+}
+QString signup_url() {
+ return QStringLiteral("https://fincept.in/enterprise/signup");
+}
+QString demo_url() {
+ return QStringLiteral("https://calendly.com/nikultilak/fincept-terminal-demo");
+}
+
+void open_url(const QString& url) {
+ QDesktopServices::openUrl(QUrl(url));
+}
+
+} // namespace enterprise
+
+// ── UpgradeDialog ────────────────────────────────────────────────────────────
+
+UpgradeDialog::UpgradeDialog(QWidget* parent) : QDialog(parent) {
+ setObjectName("upgradeDialog");
+ setModal(true);
+ setMinimumWidth(560);
+
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(28, 24, 28, 20);
+ root->setSpacing(0);
+
+ kicker_label_ = new QLabel;
+ kicker_label_->setObjectName("upgradeKicker");
+ root->addWidget(kicker_label_);
+ root->addSpacing(4);
+
+ title_label_ = new QLabel;
+ title_label_->setObjectName("upgradeTitle");
+ root->addWidget(title_label_);
+ root->addSpacing(10);
+
+ pitch_label_ = new QLabel;
+ pitch_label_->setObjectName("upgradePitch");
+ pitch_label_->setWordWrap(true);
+ root->addWidget(pitch_label_);
+ root->addSpacing(16);
+
+ // Feature list — four rows, kept in the same order as retranslateUi().
+ for (int i = 0; i < 4; ++i) {
+ auto* row = new QLabel;
+ row->setObjectName("upgradeFeature");
+ row->setWordWrap(true);
+ feature_labels_.append(row);
+ root->addWidget(row);
+ root->addSpacing(6);
+ }
+
+ root->addSpacing(10);
+ price_label_ = new QLabel;
+ price_label_->setObjectName("upgradePrice");
+ price_label_->setWordWrap(true);
+ root->addWidget(price_label_);
+
+ root->addSpacing(4);
+ oss_note_label_ = new QLabel;
+ oss_note_label_->setObjectName("upgradeNote");
+ oss_note_label_->setWordWrap(true);
+ root->addWidget(oss_note_label_);
+
+ root->addSpacing(20);
+
+ auto* buttons = new QHBoxLayout;
+ buttons->setContentsMargins(0, 0, 0, 0);
+ buttons->setSpacing(8);
+
+ dont_show_check_ = new QCheckBox;
+ dont_show_check_->setObjectName("upgradeDontShow");
+ dont_show_check_->setCursor(Qt::PointingHandCursor);
+ buttons->addWidget(dont_show_check_);
+ buttons->addStretch();
+
+ later_btn_ = new QPushButton;
+ later_btn_->setCursor(Qt::PointingHandCursor);
+ later_btn_->setStyleSheet(ent_ghost_button_ss());
+ connect(later_btn_, &QPushButton::clicked, this, &QDialog::reject);
+ buttons->addWidget(later_btn_);
+
+ compare_btn_ = new QPushButton;
+ compare_btn_->setCursor(Qt::PointingHandCursor);
+ compare_btn_->setStyleSheet(ent_ghost_button_ss());
+ connect(compare_btn_, &QPushButton::clicked, this,
+ [this]() { enterprise::open_url(enterprise::comparison_url()); });
+ buttons->addWidget(compare_btn_);
+
+ primary_btn_ = new QPushButton;
+ primary_btn_->setCursor(Qt::PointingHandCursor);
+ primary_btn_->setDefault(true);
+ primary_btn_->setStyleSheet(ent_accent_button_ss());
+ connect(primary_btn_, &QPushButton::clicked, this, [this]() {
+ enterprise::open_url(enterprise::site_url());
+ accept();
+ });
+ buttons->addWidget(primary_btn_);
+
+ root->addLayout(buttons);
+
+ // Persist the opt-out whichever way the dialog is dismissed.
+ connect(this, &QDialog::finished, this, [this](int) {
+ if (dont_show_check_ && dont_show_check_->isChecked())
+ set_startup_prompt_enabled(false);
+ });
+
+ setStyleSheet(QString("#upgradeDialog{background:%1;border:1px solid %2;}"
+ "#upgradeKicker{color:%3;font-weight:700;letter-spacing:1px;font-size:11px;"
+ " background:transparent;}"
+ "#upgradeTitle{color:%4;font-size:20px;font-weight:700;background:transparent;}"
+ "#upgradePitch{color:%5;font-size:13px;background:transparent;}"
+ "#upgradeFeature{color:%4;font-size:12px;background:transparent;}"
+ "#upgradePrice{color:%3;font-size:13px;font-weight:700;background:transparent;}"
+ "#upgradeNote{color:%6;font-size:11px;background:transparent;}"
+ "#upgradeDontShow{color:%6;font-size:11px;background:transparent;}")
+ .arg(colors::BG_SURFACE()) // %1
+ .arg(colors::BORDER_DIM()) // %2
+ .arg(colors::AMBER()) // %3
+ .arg(colors::TEXT_PRIMARY()) // %4
+ .arg(colors::TEXT_SECONDARY()) // %5
+ .arg(colors::TEXT_TERTIARY())); // %6
+
+ retranslateUi();
+}
+
+void UpgradeDialog::changeEvent(QEvent* event) {
+ if (event->type() == QEvent::LanguageChange)
+ retranslateUi();
+ QDialog::changeEvent(event);
+}
+
+void UpgradeDialog::retranslateUi() {
+ setWindowTitle(tr("Upgrade to Fincept Terminal Enterprise"));
+ if (kicker_label_)
+ kicker_label_->setText(tr("PRIVATE EDITION"));
+ if (title_label_)
+ title_label_->setText(tr("Fincept Terminal Enterprise"));
+ if (pitch_label_)
+ pitch_label_->setText(tr("You are running the free open-source build. Enterprise is the private edition "
+ "the team develops daily — built for funds, family offices and research desks."));
+
+ if (feature_labels_.size() == 4) {
+ // U+2192 arrow used as a bullet glyph — decoded from UTF-8 so it does
+ // not widen into mojibake the way a raw QStringLiteral would.
+ const QString bullet = QString::fromUtf8("\xe2\x96\xb8 ");
+ feature_labels_[0]->setText(bullet + tr("41 modules across 6 desks, on private and proprietary datasets"));
+ feature_labels_[1]->setText(bullet +
+ tr("Multi-agent research that plans and delegates, plus a private dataroom"));
+ feature_labels_[2]->setText(bullet + tr("Live broker routing, live algo deployment, point-in-time backtests"));
+ feature_labels_[3]->setText(bullet + tr("SSO/SAML, audit logs, role-based access and SLA-backed support"));
+ }
+
+ if (price_label_)
+ price_label_->setText(tr("From $99/user/month — no annual lock-in, no seat minimum."));
+ if (oss_note_label_)
+ oss_note_label_->setText(tr("This open-source edition stays free and public under AGPL-3.0, with one "
+ "release a month. Enterprise needs a separate account."));
+
+ if (dont_show_check_)
+ dont_show_check_->setText(tr("Don't show this again"));
+ if (later_btn_)
+ later_btn_->setText(tr("Maybe later"));
+ if (compare_btn_)
+ compare_btn_->setText(tr("Compare editions"));
+ if (primary_btn_)
+ primary_btn_->setText(tr("See Enterprise"));
+}
+
+bool UpgradeDialog::startup_prompt_enabled() {
+ return !AppConfig::instance().get(kEntSuppressKey, false).toBool();
+}
+
+void UpgradeDialog::set_startup_prompt_enabled(bool enabled) {
+ AppConfig::instance().set(kEntSuppressKey, !enabled);
+}
+
+void UpgradeDialog::show_now(QWidget* parent) {
+ if (ent_headless_platform())
+ return;
+ auto* dlg = new UpgradeDialog(parent);
+ dlg->setAttribute(Qt::WA_DeleteOnClose);
+ // open() rather than exec(): the startup call site runs inside a timer
+ // callback, and exec() there would spin a nested event loop.
+ dlg->open();
+}
+
+void UpgradeDialog::maybe_show_at_startup(QWidget* parent) {
+ if (!startup_prompt_enabled())
+ return;
+ show_now(parent);
+}
+
+// ── Inline banner ────────────────────────────────────────────────────────────
+
+QWidget* make_enterprise_banner(QWidget* parent) {
+ auto* panel = new QWidget(parent);
+ panel->setObjectName("entBanner");
+
+ auto* hl = new QHBoxLayout(panel);
+ hl->setContentsMargins(18, 14, 18, 14);
+ hl->setSpacing(14);
+
+ auto* text_col = new QVBoxLayout;
+ text_col->setContentsMargins(0, 0, 0, 0);
+ text_col->setSpacing(3);
+
+ auto* head = new QLabel(QObject::tr("FINCEPT TERMINAL ENTERPRISE"), panel);
+ head->setObjectName("entBannerHead");
+ text_col->addWidget(head);
+
+ auto* sub = new QLabel(QObject::tr("The private edition — 41 modules, proprietary data, multi-agent research, "
+ "live broker routing, SSO and an SLA. From $99/user/month."),
+ panel);
+ sub->setObjectName("entBannerSub");
+ sub->setWordWrap(true);
+ text_col->addWidget(sub);
+
+ hl->addLayout(text_col, 1);
+
+ auto* btn = new QPushButton(QObject::tr("See Enterprise"), panel);
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setStyleSheet(ent_accent_button_ss());
+ QObject::connect(btn, &QPushButton::clicked, panel, []() { enterprise::open_url(enterprise::site_url()); });
+ hl->addWidget(btn, 0, Qt::AlignVCenter);
+
+ panel->setStyleSheet(QString("#entBanner{background:%1;border:1px solid %2;}"
+ "#entBannerHead{color:%2;font-weight:700;letter-spacing:1px;font-size:12px;"
+ " background:transparent;}"
+ "#entBannerSub{color:%3;font-size:12px;background:transparent;}")
+ .arg(colors::BG_SURFACE())
+ .arg(colors::AMBER())
+ .arg(colors::TEXT_SECONDARY()));
+ return panel;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/EnterprisePromo.h b/fincept-qt/src/ui/widgets/EnterprisePromo.h
new file mode 100644
index 000000000..50029f50b
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/EnterprisePromo.h
@@ -0,0 +1,80 @@
+#pragma once
+// EnterprisePromo — the single place the terminal talks about Fincept Terminal
+// Enterprise (the private, closed-source edition).
+//
+// This open-source build is AGPL-3.0 and Fincept no longer sells a commercial
+// licence for it; commercial, institutional and academic use is served by
+// Enterprise instead. Every surface that mentions that — the toolbar UPGRADE
+// button, the startup dialog, the pricing screen banner — reads its copy and
+// its URLs from here so pricing lives in exactly one file.
+
+#include <QDialog>
+#include <QEvent>
+#include <QString>
+
+class QCheckBox;
+class QLabel;
+class QPushButton;
+
+namespace fincept::ui {
+
+namespace enterprise {
+
+/// Canonical destinations. Keep in sync with README.md and
+/// docs/COMMERCIAL_LICENSE.md — those three are the published surfaces.
+QString site_url();
+QString pricing_url();
+QString comparison_url();
+QString signup_url();
+QString demo_url();
+
+/// Opens `url` in the user's browser.
+void open_url(const QString& url);
+
+} // namespace enterprise
+
+/// Modal "Upgrade to Enterprise" dialog. Shown once per launch at startup
+/// (unless suppressed) and on demand from the toolbar UPGRADE button.
+class UpgradeDialog : public QDialog {
+ Q_OBJECT
+ public:
+ explicit UpgradeDialog(QWidget* parent = nullptr);
+
+ /// False once the user has ticked "Don't show this again".
+ static bool startup_prompt_enabled();
+ static void set_startup_prompt_enabled(bool enabled);
+
+ /// Non-blocking show, heap-allocated with WA_DeleteOnClose. Used by both
+ /// the toolbar button and the startup hook so neither spins a nested
+ /// event loop inside a timer callback.
+ static void show_now(QWidget* parent);
+
+ /// Startup entry point. No-ops when the user has suppressed the prompt or
+ /// when the platform has no window system (headless CI, --smoke-test),
+ /// where a modal would hang the run.
+ static void maybe_show_at_startup(QWidget* parent);
+
+ protected:
+ void changeEvent(QEvent* event) override;
+
+ private:
+ void retranslateUi();
+
+ QLabel* title_label_ = nullptr;
+ QLabel* kicker_label_ = nullptr;
+ QLabel* pitch_label_ = nullptr;
+ QLabel* price_label_ = nullptr;
+ QLabel* oss_note_label_ = nullptr;
+ QList<QLabel*> feature_labels_;
+ QCheckBox* dont_show_check_ = nullptr;
+ QPushButton* primary_btn_ = nullptr;
+ QPushButton* compare_btn_ = nullptr;
+ QPushButton* later_btn_ = nullptr;
+};
+
+/// Inline Enterprise banner for embedding at the top of a screen (currently
+/// the pricing screen). Caller takes ownership via the returned widget's
+/// parent, as usual for Qt.
+QWidget* make_enterprise_banner(QWidget* parent = nullptr);
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/PhoneCodeComboBox.cpp b/fincept-qt/src/ui/widgets/PhoneCodeComboBox.cpp
deleted file mode 100644
index ed811e5b2..000000000
--- a/fincept-qt/src/ui/widgets/PhoneCodeComboBox.cpp
+++ /dev/null
@@ -1,376 +0,0 @@
-#include "ui/widgets/PhoneCodeComboBox.h"
-
-#include <QAbstractItemView>
-#include <QCompleter>
-#include <QLabel>
-#include <QLineEdit>
-#include <QResizeEvent>
-#include <QScrollBar>
-#include <QStandardItem>
-
-namespace fincept::ui {
-
-static const struct {
- const char* flag;
- const char* name;
- const char* code;
-} k_countries[] = {
- {"🇦🇫", "Afghanistan", "+93"},
- {"🇦🇱", "Albania", "+355"},
- {"🇩🇿", "Algeria", "+213"},
- {"🇦🇩", "Andorra", "+376"},
- {"🇦🇴", "Angola", "+244"},
- {"🇦🇬", "Antigua & Barbuda", "+1-268"},
- {"🇦🇷", "Argentina", "+54"},
- {"🇦🇲", "Armenia", "+374"},
- {"🇦🇺", "Australia", "+61"},
- {"🇦🇹", "Austria", "+43"},
- {"🇦🇿", "Azerbaijan", "+994"},
- {"🇧🇸", "Bahamas", "+1-242"},
- {"🇧🇭", "Bahrain", "+973"},
- {"🇧🇩", "Bangladesh", "+880"},
- {"🇧🇧", "Barbados", "+1-246"},
- {"🇧🇾", "Belarus", "+375"},
- {"🇧🇪", "Belgium", "+32"},
- {"🇧🇿", "Belize", "+501"},
- {"🇧🇯", "Benin", "+229"},
- {"🇧🇹", "Bhutan", "+975"},
- {"🇧🇴", "Bolivia", "+591"},
- {"🇧🇦", "Bosnia & Herzegovina", "+387"},
- {"🇧🇼", "Botswana", "+267"},
- {"🇧🇷", "Brazil", "+55"},
- {"🇧🇳", "Brunei", "+673"},
- {"🇧🇬", "Bulgaria", "+359"},
- {"🇧🇫", "Burkina Faso", "+226"},
- {"🇧🇮", "Burundi", "+257"},
- {"🇨🇻", "Cabo Verde", "+238"},
- {"🇰🇭", "Cambodia", "+855"},
- {"🇨🇲", "Cameroon", "+237"},
- {"🇨🇦", "Canada", "+1"},
- {"🇨🇫", "Central African Republic", "+236"},
- {"🇹🇩", "Chad", "+235"},
- {"🇨🇱", "Chile", "+56"},
- {"🇨🇳", "China", "+86"},
- {"🇨🇴", "Colombia", "+57"},
- {"🇰🇲", "Comoros", "+269"},
- {"🇨🇩", "Congo (DRC)", "+243"},
- {"🇨🇬", "Congo (Republic)", "+242"},
- {"🇨🇷", "Costa Rica", "+506"},
- {"🇭🇷", "Croatia", "+385"},
- {"🇨🇺", "Cuba", "+53"},
- {"🇨🇾", "Cyprus", "+357"},
- {"🇨🇿", "Czech Republic", "+420"},
- {"🇩🇰", "Denmark", "+45"},
- {"🇩🇯", "Djibouti", "+253"},
- {"🇩🇲", "Dominica", "+1-767"},
- {"🇩🇴", "Dominican Republic", "+1-809"},
- {"🇪🇨", "Ecuador", "+593"},
- {"🇪🇬", "Egypt", "+20"},
- {"🇸🇻", "El Salvador", "+503"},
- {"🇬🇶", "Equatorial Guinea", "+240"},
- {"🇪🇷", "Eritrea", "+291"},
- {"🇪🇪", "Estonia", "+372"},
- {"🇸🇿", "Eswatini", "+268"},
- {"🇪🇹", "Ethiopia", "+251"},
- {"🇫🇯", "Fiji", "+679"},
- {"🇫🇮", "Finland", "+358"},
- {"🇫🇷", "France", "+33"},
- {"🇬🇦", "Gabon", "+241"},
- {"🇬🇲", "Gambia", "+220"},
- {"🇬🇪", "Georgia", "+995"},
- {"🇩🇪", "Germany", "+49"},
- {"🇬🇭", "Ghana", "+233"},
- {"🇬🇷", "Greece", "+30"},
- {"🇬🇩", "Grenada", "+1-473"},
- {"🇬🇹", "Guatemala", "+502"},
- {"🇬🇳", "Guinea", "+224"},
- {"🇬🇼", "Guinea-Bissau", "+245"},
- {"🇬🇾", "Guyana", "+592"},
- {"🇭🇹", "Haiti", "+509"},
- {"🇭🇳", "Honduras", "+504"},
- {"🇭🇺", "Hungary", "+36"},
- {"🇮🇸", "Iceland", "+354"},
- {"🇮🇳", "India", "+91"},
- {"🇮🇩", "Indonesia", "+62"},
- {"🇮🇷", "Iran", "+98"},
- {"🇮🇶", "Iraq", "+964"},
- {"🇮🇪", "Ireland", "+353"},
- {"🇮🇱", "Israel", "+972"},
- {"🇮🇹", "Italy", "+39"},
- {"🇯🇲", "Jamaica", "+1-876"},
- {"🇯🇵", "Japan", "+81"},
- {"🇯🇴", "Jordan", "+962"},
- {"🇰🇿", "Kazakhstan", "+7"},
- {"🇰🇪", "Kenya", "+254"},
- {"🇰🇮", "Kiribati", "+686"},
- {"🇽🇰", "Kosovo", "+383"},
- {"🇰🇼", "Kuwait", "+965"},
- {"🇰🇬", "Kyrgyzstan", "+996"},
- {"🇱🇦", "Laos", "+856"},
- {"🇱🇻", "Latvia", "+371"},
- {"🇱🇧", "Lebanon", "+961"},
- {"🇱🇸", "Lesotho", "+266"},
- {"🇱🇷", "Liberia", "+231"},
- {"🇱🇾", "Libya", "+218"},
- {"🇱🇮", "Liechtenstein", "+423"},
- {"🇱🇹", "Lithuania", "+370"},
- {"🇱🇺", "Luxembourg", "+352"},
- {"🇲🇬", "Madagascar", "+261"},
- {"🇲🇼", "Malawi", "+265"},
- {"🇲🇾", "Malaysia", "+60"},
- {"🇲🇻", "Maldives", "+960"},
- {"🇲🇱", "Mali", "+223"},
- {"🇲🇹", "Malta", "+356"},
- {"🇲🇭", "Marshall Islands", "+692"},
- {"🇲🇷", "Mauritania", "+222"},
- {"🇲🇺", "Mauritius", "+230"},
- {"🇲🇽", "Mexico", "+52"},
- {"🇫🇲", "Micronesia", "+691"},
- {"🇲🇩", "Moldova", "+373"},
- {"🇲🇨", "Monaco", "+377"},
- {"🇲🇳", "Mongolia", "+976"},
- {"🇲🇪", "Montenegro", "+382"},
- {"🇲🇦", "Morocco", "+212"},
- {"🇲🇿", "Mozambique", "+258"},
- {"🇲🇲", "Myanmar", "+95"},
- {"🇳🇦", "Namibia", "+264"},
- {"🇳🇷", "Nauru", "+674"},
- {"🇳🇵", "Nepal", "+977"},
- {"🇳🇱", "Netherlands", "+31"},
- {"🇳🇿", "New Zealand", "+64"},
- {"🇳🇮", "Nicaragua", "+505"},
- {"🇳🇪", "Niger", "+227"},
- {"🇳🇬", "Nigeria", "+234"},
- {"🇲🇰", "North Macedonia", "+389"},
- {"🇳🇴", "Norway", "+47"},
- {"🇴🇲", "Oman", "+968"},
- {"🇵🇰", "Pakistan", "+92"},
- {"🇵🇼", "Palau", "+680"},
- {"🇵🇦", "Panama", "+507"},
- {"🇵🇬", "Papua New Guinea", "+675"},
- {"🇵🇾", "Paraguay", "+595"},
- {"🇵🇪", "Peru", "+51"},
- {"🇵🇭", "Philippines", "+63"},
- {"🇵🇱", "Poland", "+48"},
- {"🇵🇹", "Portugal", "+351"},
- {"🇶🇦", "Qatar", "+974"},
- {"🇷🇴", "Romania", "+40"},
- {"🇷🇺", "Russia", "+7"},
- {"🇷🇼", "Rwanda", "+250"},
- {"🇰🇳", "Saint Kitts & Nevis", "+1-869"},
- {"🇱🇨", "Saint Lucia", "+1-758"},
- {"🇻🇨", "Saint Vincent & Grenadines", "+1-784"},
- {"🇼🇸", "Samoa", "+685"},
- {"🇸🇲", "San Marino", "+378"},
- {"🇸🇹", "São Tomé & Príncipe", "+239"},
- {"🇸🇦", "Saudi Arabia", "+966"},
- {"🇸🇳", "Senegal", "+221"},
- {"🇷🇸", "Serbia", "+381"},
- {"🇸🇨", "Seychelles", "+248"},
- {"🇸🇱", "Sierra Leone", "+232"},
- {"🇸🇬", "Singapore", "+65"},
- {"🇸🇰", "Slovakia", "+421"},
- {"🇸🇮", "Slovenia", "+386"},
- {"🇸🇧", "Solomon Islands", "+677"},
- {"🇸🇴", "Somalia", "+252"},
- {"🇿🇦", "South Africa", "+27"},
- {"🇸🇸", "South Sudan", "+211"},
- {"🇪🇸", "Spain", "+34"},
- {"🇱🇰", "Sri Lanka", "+94"},
- {"🇸🇩", "Sudan", "+249"},
- {"🇸🇷", "Suriname", "+597"},
- {"🇸🇪", "Sweden", "+46"},
- {"🇨🇭", "Switzerland", "+41"},
- {"🇸🇾", "Syria", "+963"},
- {"🇹🇼", "Taiwan", "+886"},
- {"🇹🇯", "Tajikistan", "+992"},
- {"🇹🇿", "Tanzania", "+255"},
- {"🇹🇭", "Thailand", "+66"},
- {"🇹🇱", "Timor-Leste", "+670"},
- {"🇹🇬", "Togo", "+228"},
- {"🇹🇴", "Tonga", "+676"},
- {"🇹🇹", "Trinidad & Tobago", "+1-868"},
- {"🇹🇳", "Tunisia", "+216"},
- {"🇹🇷", "Turkey", "+90"},
- {"🇹🇲", "Turkmenistan", "+993"},
- {"🇹🇻", "Tuvalu", "+688"},
- {"🇺🇬", "Uganda", "+256"},
- {"🇺🇦", "Ukraine", "+380"},
- {"🇦🇪", "United Arab Emirates", "+971"},
- {"🇬🇧", "United Kingdom", "+44"},
- {"🇺🇸", "United States", "+1"},
- {"🇺🇾", "Uruguay", "+598"},
- {"🇺🇿", "Uzbekistan", "+998"},
- {"🇻🇺", "Vanuatu", "+678"},
- {"🇻🇦", "Vatican City", "+379"},
- {"🇻🇪", "Venezuela", "+58"},
- {"🇻🇳", "Vietnam", "+84"},
- {"🇾🇪", "Yemen", "+967"},
- {"🇿🇲", "Zambia", "+260"},
- {"🇿🇼", "Zimbabwe", "+263"},
-};
-
-static const char* k_scrollbar_style =
- "QScrollBar:vertical { background:#0a0a0a; width:5px; border:none; }"
- "QScrollBar::handle:vertical { background:#2a2a2a; border-radius:2px; min-height:20px; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }";
-
-static const char* k_popup_style =
- "QAbstractItemView {"
- " background:#111111; color:#e5e5e5; border:1px solid #2a2a2a;"
- " selection-background-color:#1c1400; selection-color:#d97706;"
- " font-size:13px; font-family:'Consolas',monospace; outline:none; padding:2px; }"
- "QAbstractItemView::item { padding:5px 12px; min-height:28px; border:none; }"
- "QScrollBar:vertical { background:#0a0a0a; width:5px; border:none; }"
- "QScrollBar::handle:vertical { background:#2a2a2a; border-radius:2px; min-height:20px; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }";
-
-PhoneCodeComboBox::PhoneCodeComboBox(QWidget* parent) : QComboBox(parent) {
- model_ = new QStandardItemModel(this);
-
- setEditable(true);
- setInsertPolicy(QComboBox::NoInsert);
- setMaxVisibleItems(12);
-
- populate();
- setModel(model_);
-
- // Wide enough to show full country names without clipping
- view()->setMinimumWidth(320);
- view()->setStyleSheet(k_popup_style);
- view()->verticalScrollBar()->setStyleSheet(k_scrollbar_style);
-
- // Completer: MatchContains so typing any part of name/code filters the list
- auto* comp = new QCompleter(model_, this);
- comp->setCaseSensitivity(Qt::CaseInsensitive);
- comp->setFilterMode(Qt::MatchContains);
- comp->setCompletionMode(QCompleter::PopupCompletion);
- comp->setCompletionColumn(0);
- if (auto* popup = comp->popup()) {
- popup->setMinimumWidth(320);
- popup->setStyleSheet(k_popup_style);
- popup->verticalScrollBar()->setStyleSheet(k_scrollbar_style);
- }
- setCompleter(comp);
-
- // When completer picks a match, sync the index and display
- connect(comp, QOverload<const QModelIndex&>::of(&QCompleter::activated), this, [this](const QModelIndex& idx) {
- int row = idx.row();
- setCurrentIndex(row);
- sync_display(row);
- });
-
- setStyleSheet("QComboBox {"
- " background:#0a0a0a; color:#e5e5e5; border:1px solid #1a1a1a;"
- " padding:4px 8px; font-size:14px;"
- " font-family:'Consolas','Courier New',monospace; }"
- "QComboBox:focus { border:1px solid #333333; }"
- // Reserve space on the right for the custom drop-down button
- "QComboBox::drop-down {"
- " subcontrol-origin: padding; subcontrol-position: right center;"
- " width: 28px; border-left: 1px solid #1a1a1a; background: #111111;"
- " border-radius: 0 2px 2px 0; }"
- // Use the unicode chevron as the arrow via a UTF-8 string trick
- "QComboBox::down-arrow {"
- " image: none; width:0; height:0; }"
- "QComboBox QAbstractItemView {"
- " background:#111111; color:#e5e5e5; border:1px solid #2a2a2a;"
- " selection-background-color:#1c1400; selection-color:#d97706;"
- " font-size:13px; font-family:'Consolas',monospace; outline:none; padding:2px; }"
- "QComboBox QAbstractItemView::item { padding:5px 12px; min-height:28px; border:none; }"
- "QComboBox QAbstractItemView QScrollBar:vertical { background:#0a0a0a; width:5px; border:none; }"
- "QComboBox QAbstractItemView QScrollBar::handle:vertical { background:#2a2a2a; border-radius:2px; }"
- "QComboBox QAbstractItemView QScrollBar::add-line:vertical,"
- "QComboBox QAbstractItemView QScrollBar::sub-line:vertical { height:0; }");
-
- // Draw a proper chevron "⌄" in the drop-down button area via a QLabel overlay
- arrow_lbl_ = new QLabel("⌄", this);
- arrow_lbl_->setAlignment(Qt::AlignCenter);
- arrow_lbl_->setStyleSheet("color:#707070; font-size:16px; background:transparent;"
- "font-family:'Consolas',monospace;");
- arrow_lbl_->setAttribute(Qt::WA_TransparentForMouseEvents);
- arrow_lbl_->setGeometry(width() - 28, 0, 28, height());
-
- if (auto* le = lineEdit()) {
- le->setStyleSheet("QLineEdit { background:transparent; color:#e5e5e5; border:none;"
- " font-size:14px; font-family:'Consolas','Courier New',monospace; padding:0; }");
- le->setPlaceholderText(tr("Search country…"));
-
- // When user manually edits the field, try to match and update dial code
- connect(le, &QLineEdit::textEdited, this, [this](const QString& text) {
- // Try to find an exact code match first (e.g. user typed "+91")
- for (int i = 0; i < model_->rowCount(); i++) {
- if (model_->item(i)->data(Qt::UserRole).toString().compare(text.trimmed(), Qt::CaseInsensitive) == 0) {
- setCurrentIndex(i);
- return;
- }
- }
- });
- }
-
- // Default to United States
- set_dial_code("+1");
-
- // On selection from native dropdown: show compact flag + code
- connect(this, &QComboBox::activated, this, &PhoneCodeComboBox::sync_display);
-}
-
-void PhoneCodeComboBox::populate() {
- for (const auto& c : k_countries) {
- auto* item = new QStandardItem;
- QString flag = QString::fromUtf8(c.flag);
- QString name = QString::fromUtf8(c.name);
- QString code = QString::fromUtf8(c.code);
- item->setText(QString("%1 %2 %3").arg(flag, name, code));
- item->setData(code, Qt::UserRole);
- item->setData(flag, Qt::UserRole + 1);
- model_->appendRow(item);
- }
-}
-
-void PhoneCodeComboBox::sync_display(int index) {
- if (index < 0 || index >= model_->rowCount())
- return;
- QString flag = model_->item(index)->data(Qt::UserRole + 1).toString();
- QString code = model_->item(index)->data(Qt::UserRole).toString();
- if (auto* le = lineEdit())
- le->setText(QString("%1 %2").arg(flag, code));
-}
-
-QString PhoneCodeComboBox::dial_code() const {
- int idx = currentIndex();
- if (idx >= 0 && idx < model_->rowCount())
- return model_->item(idx)->data(Qt::UserRole).toString();
- return {};
-}
-
-void PhoneCodeComboBox::resizeEvent(QResizeEvent* e) {
- QComboBox::resizeEvent(e);
- if (arrow_lbl_)
- arrow_lbl_->setGeometry(width() - 28, 0, 28, height());
-}
-
-void PhoneCodeComboBox::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QComboBox::changeEvent(event);
-}
-
-void PhoneCodeComboBox::retranslateUi() {
- // Country names + dial codes are locale-neutral data, not UI labels — only
- // the search placeholder translates.
- if (auto* le = lineEdit())
- le->setPlaceholderText(tr("Search country…"));
-}
-
-void PhoneCodeComboBox::set_dial_code(const QString& code) {
- for (int i = 0; i < model_->rowCount(); i++) {
- if (model_->item(i)->data(Qt::UserRole).toString() == code) {
- setCurrentIndex(i);
- sync_display(i);
- return;
- }
- }
-}
-
-} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/PhoneCodeComboBox.h b/fincept-qt/src/ui/widgets/PhoneCodeComboBox.h
deleted file mode 100644
index 3cfca947f..000000000
--- a/fincept-qt/src/ui/widgets/PhoneCodeComboBox.h
+++ /dev/null
@@ -1,37 +0,0 @@
-#pragma once
-#include <QComboBox>
-#include <QEvent>
-#include <QLabel>
-#include <QResizeEvent>
-#include <QStandardItemModel>
-#include <QString>
-
-namespace fincept::ui {
-
-/// Searchable country dial-code selector using QStandardItemModel.
-/// Dropdown shows: flag + country name + dial code (searchable by any field).
-/// Closed field shows compact: flag + dial code only (e.g. "🇺🇸 +1").
-/// Use dial_code() to retrieve the E.164 prefix (e.g. "+1").
-class PhoneCodeComboBox : public QComboBox {
- Q_OBJECT
- public:
- explicit PhoneCodeComboBox(QWidget* parent = nullptr);
-
- QString dial_code() const;
- void set_dial_code(const QString& code);
-
- protected:
- void resizeEvent(QResizeEvent* e) override;
- void changeEvent(QEvent* event) override;
-
- private:
- QStandardItemModel* model_ = nullptr;
- QLabel* arrow_lbl_ = nullptr;
- void populate();
- void sync_display(int index);
-
- /// Re-apply tr() lookups to the search placeholder after a language switch.
- void retranslateUi();
-};
-
-} // namespace fincept::ui
diff --git a/fincept-qt/tests/CMakeLists.txt b/fincept-qt/tests/CMakeLists.txt
new file mode 100644
index 000000000..8dbb8c4af
--- /dev/null
+++ b/fincept-qt/tests/CMakeLists.txt
@@ -0,0 +1,122 @@
+# ── Fincept Terminal unit tests (Qt Test) ────────────────────────────────────
+#
+# Reached ONLY from the top-level CMakeLists.txt under `if(FINCEPT_BUILD_TESTS)`,
+# which is OFF by default. Nothing in this file affects a normal build.
+#
+# cmake -B build -DFINCEPT_BUILD_TESTS=ON ...
+# cmake --build build
+# ctest --test-dir build --output-on-failure # add -C Release on MSVC
+#
+# ─────────────────────────────────────────────────────────────────────────────
+# HARD RULE — read this before adding a target.
+#
+# A test target lists the SPECIFIC sources it needs, explicitly, by path.
+#
+# Do NOT "solve" a missing symbol by refactoring the app into an OBJECT library
+# and linking it here. The release/CI presets build with CMAKE_UNITY_BUILD=ON
+# (batch size 20) while `win-dev` builds unity OFF, so any change to the main
+# source list re-batches every file after it and can produce file-scope symbol
+# redefinitions that appear ONLY on CI and never reproduce locally. See the
+# "unity build" notes in ../CLAUDE.md.
+#
+# If a unit cannot be tested without dragging in half the application, that is a
+# signal about the unit, not about this file: extract the pure logic into a small
+# header (or a leaf .cpp) and test that. Do not grow the link line.
+#
+# Current cost of the whole suite: 3 executables, 5 translation units.
+# ─────────────────────────────────────────────────────────────────────────────
+
+# Qt Test ships with every Qt installation, so this adds no new dependency.
+# _FINCEPT_QT_VER_ARGS is inherited from the parent scope so the version pin
+# (6.8.3 EXACT by default) stays identical to the one the app is built against.
+find_package(Qt6 ${_FINCEPT_QT_VER_ARGS} QUIET COMPONENTS Test)
+if(NOT Qt6Test_FOUND)
+ message(FATAL_ERROR
+ "FINCEPT_BUILD_TESTS=ON but the Qt6 Test module was not found.\n"
+ "Qt Test ships with the standard Qt installer — re-run the Qt maintenance "
+ "tool and make sure 'Qt Test' is selected for your kit, or configure with "
+ "-DFINCEPT_BUILD_TESTS=OFF.")
+endif()
+
+# Windows has no rpath: a freshly built tst_*.exe cannot find Qt6Core.dll unless
+# the Qt bin dir is on PATH. Resolve it once and inject it per-test below, so
+# `ctest` works straight out of a fresh configure without anyone having to run
+# windeployqt against the test binaries.
+#
+# Best-effort by design: if the Qt layout is unusual (distro split packages, no
+# qmake shipped) we simply skip the injection rather than fail the configure —
+# on those layouts Qt is on the loader path already.
+set(_fincept_qt_bindir "")
+set(_fincept_qt_libdir "")
+if(TARGET Qt6::qmake)
+ get_target_property(_fincept_qt_qmake Qt6::qmake IMPORTED_LOCATION)
+ if(_fincept_qt_qmake AND EXISTS "${_fincept_qt_qmake}")
+ get_filename_component(_fincept_qt_bindir "${_fincept_qt_qmake}" DIRECTORY)
+ get_filename_component(_fincept_qt_prefix "${_fincept_qt_bindir}" DIRECTORY)
+ set(_fincept_qt_libdir "${_fincept_qt_prefix}/lib")
+ endif()
+endif()
+if(NOT _fincept_qt_bindir AND Qt6_DIR)
+ # Qt6_DIR is <prefix>/lib/cmake/Qt6 for a standard installer layout.
+ get_filename_component(_fincept_qt_prefix "${Qt6_DIR}/../../.." ABSOLUTE)
+ if(EXISTS "${_fincept_qt_prefix}/bin")
+ set(_fincept_qt_bindir "${_fincept_qt_prefix}/bin")
+ set(_fincept_qt_libdir "${_fincept_qt_prefix}/lib")
+ endif()
+endif()
+
+# fincept_add_test(<name> <source> [<extra sources>...])
+#
+# <name> must be tst_<unit>. Extra sources are the app .cpp files this unit
+# genuinely needs — keep that list as short as it can possibly be.
+function(fincept_add_test _name)
+ add_executable(${_name} ${ARGN})
+
+ # Qt6::Test pulls in Qt6::Core. Deliberately no Widgets/Network/Sql here:
+ # a unit test that needs those is testing the wrong seam.
+ target_link_libraries(${_name} PRIVATE Qt6::Test Qt6::Core)
+
+ # Sources use project-root-relative includes ("trading/OrderValidator.h"),
+ # matching target_include_directories(FinceptTerminal PRIVATE src).
+ target_include_directories(${_name} PRIVATE "${PROJECT_SOURCE_DIR}/src")
+
+ set_target_properties(${_name} PROPERTIES
+ AUTOMOC ON # Q_OBJECT test classes live in the .cpp (+ #include "<name>.moc")
+ UNITY_BUILD OFF # never batch test TUs, whatever the parent preset says
+ FOLDER "tests")
+
+ # NOTE: no install() rule, by design. Test executables must never ship in a
+ # release artifact. They also land in ${CMAKE_CURRENT_BINARY_DIR} (build/tests/),
+ # not next to FinceptTerminal.exe, so the installer's
+ # install(DIRECTORY "$<TARGET_FILE_DIR:FinceptTerminal>/" ... FILES_MATCHING "*.dll")
+ # rule cannot pick them up either.
+
+ add_test(NAME ${_name} COMMAND ${_name})
+
+ if(WIN32 AND _fincept_qt_bindir)
+ set_tests_properties(${_name} PROPERTIES
+ ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${_fincept_qt_bindir}")
+ elseif(UNIX AND NOT APPLE AND _fincept_qt_libdir)
+ set_tests_properties(${_name} PROPERTIES
+ ENVIRONMENT_MODIFICATION "LD_LIBRARY_PATH=path_list_prepend:${_fincept_qt_libdir}")
+ endif()
+endfunction()
+
+# ── Suites ───────────────────────────────────────────────────────────────────
+
+# src/trading/brokers/BrokerModifyFields.h — header-only, zero app sources.
+fincept_add_test(tst_broker_modify_fields
+ tst_broker_modify_fields.cpp)
+
+# src/core/result/Result.h — header-only, zero app sources.
+fincept_add_test(tst_result
+ tst_result.cpp)
+
+# src/trading/OrderValidator.{h,cpp} — the .cpp includes only its own header,
+# which includes only trading/TradingTypes.h (Qt Core types + plain structs, no
+# .cpp of its own). One extra TU, no service/network/broker-registry linkage.
+fincept_add_test(tst_order_validator
+ tst_order_validator.cpp
+ "${PROJECT_SOURCE_DIR}/src/trading/OrderValidator.cpp")
+
+message(STATUS "Fincept tests: tst_broker_modify_fields, tst_result, tst_order_validator")
diff --git a/fincept-qt/tests/README.md b/fincept-qt/tests/README.md
new file mode 100644
index 000000000..37fcb0584
--- /dev/null
+++ b/fincept-qt/tests/README.md
@@ -0,0 +1,111 @@
+# Unit tests
+
+Qt Test suites for the pure, side-effect-free units of Fincept Terminal.
+Off by default: a normal `cmake --preset win-dev` build compiles none of this.
+
+These complement — they do not replace — the headless `--selftest-*` flags on the
+main binary, which cover end-to-end screen/engine behaviour and run in
+`.github/workflows/build-pr.yml`.
+
+## Configure
+
+Add `-DFINCEPT_BUILD_TESTS=ON` to any normal configure. Everything else stays the
+same; the option only adds test targets.
+
+```powershell
+cmake --preset win-dev -DFINCEPT_BUILD_TESTS=ON
+cmake --build --preset win-dev
+```
+
+Or without a preset:
+
+```bash
+cmake -B build -DCMAKE_PREFIX_PATH=/path/to/Qt/6.8.3/kit -DFINCEPT_BUILD_TESTS=ON
+cmake --build build
+```
+
+## Run
+
+```bash
+ctest --test-dir build --output-on-failure
+```
+
+On a multi-config generator (the Visual Studio generator, which is what CI uses on
+Windows) add the config:
+
+```bash
+ctest --test-dir build -C Release --output-on-failure
+```
+
+One suite at a time:
+
+```bash
+ctest --test-dir build --output-on-failure -R tst_order_validator
+```
+
+Or run an executable directly for Qt Test's own flags (`-functions`, `-v2`,
+a single slot by name):
+
+```bash
+./build/tests/tst_order_validator -functions
+./build/tests/tst_order_validator smart_flatten_with_zero_quantity_is_valid
+```
+
+Test binaries live in `build/tests/`, never next to `FinceptTerminal.exe`, and
+have no `install()` rule — they cannot end up in a release artifact.
+
+## THE RULE: a test target lists its own sources
+
+**Every test target names the specific app sources it needs, explicitly, by path.
+Never link the whole application into a test.**
+
+```cmake
+fincept_add_test(tst_order_validator
+ tst_order_validator.cpp
+ "${PROJECT_SOURCE_DIR}/src/trading/OrderValidator.cpp")
+```
+
+The tempting alternative — splitting the app into an `OBJECT` library and linking
+it into both the app and the tests — is **forbidden here**. The release and CI
+presets build with `CMAKE_UNITY_BUILD=ON` (batch size 20) while `win-dev` builds
+unity OFF. Any change to the main source list re-batches every file after it, and
+two file-scope symbols that land in the same batch become a hard redefinition
+error **that appears only on CI and never reproduces locally**. A restructure to
+make testing convenient is not worth breaking the release build.
+
+The suites currently cost three executables and five translation units in total.
+Keep it that way.
+
+### When a unit resists testing
+
+If you cannot test something without dragging in services, the broker registry,
+`QNetworkAccessManager`, `PythonRunner` or a database, **that is a fact about the
+unit, not a reason to grow the link line.** Extract the pure logic into a small
+header (or a leaf `.cpp` with no app includes) and test that. If you decide not to
+test it yet, say so in the PR rather than adding a heavyweight target.
+
+Known example: `extract_json()` and `extract_error_envelope()` in
+`src/python/PythonRunner.cpp` are exactly the kind of pure string/JSON logic that
+belongs under test, but `extract_error_envelope` is file-`static` (unreachable
+from another TU) and reaching `extract_json` means linking `PythonRunner.cpp`,
+which pulls in `Logger`, `PythonSetupManager`, `PythonWorker`, `SecureStorage` and
+`config/KeyedConnectorCredentials.inc`. They should move to a small
+`PythonPayload.h` first; then a `tst_python_payload` target costs one TU.
+
+## Conventions
+
+- One executable per unit, named `tst_<unit>`; register it with
+ `fincept_add_test()` in `CMakeLists.txt`.
+- `QTEST_GUILESS_MAIN` — no `QApplication`, no display, no `QT_QPA_PLATFORM`
+ juggling in CI.
+- The `Q_OBJECT` test class lives in the `.cpp`; end the file with
+ `#include "tst_<unit>.moc"` (AUTOMOC generates it).
+- Link `Qt6::Test` and `Qt6::Core` only. Needing `Widgets`, `Network` or `Sql` in
+ a unit test is a signal you are testing at the wrong seam.
+- Name slots after the behaviour, not the function
+ (`smart_flatten_with_zero_quantity_is_valid`, not `test_validate_smart_1`).
+- Pin real incidents as named regression tests
+ (`regression_iifl_price_modify`) so the next reader learns why the code is
+ shaped the way it is.
+- Assert behaviour that is actually documented or load-bearing. A test of an
+ incidental implementation detail is a future false alarm.
diff --git a/fincept-qt/tests/tst_broker_modify_fields.cpp b/fincept-qt/tests/tst_broker_modify_fields.cpp
new file mode 100644
index 000000000..e7f7aa29b
--- /dev/null
+++ b/fincept-qt/tests/tst_broker_modify_fields.cpp
@@ -0,0 +1,342 @@
+// Unit tests for src/trading/brokers/BrokerModifyFields.h
+//
+// The untyped modify_order(mods) map is read under 32 distinct key names across
+// 22 broker adapters. Every spelling mismatch reads as "absent" and transmits
+// the type default — for a price field, 0. Two live examples this header exists
+// to stop, both pinned as regression tests at the bottom of this file:
+//
+// * IIFL read "limitPrice" while callers send "price" -> limit price 0
+// * Shoonya/Flattrade/Tradejini read "triggerPrice" while
+// callers send "trigger_price" -> trgprc = 0
+//
+// The subtle invariant, and the reason first_present() exists at all:
+// PRESENCE decides, not truthiness. A caller that deliberately sends price 0
+// must get 0 back, not the next alias in the list and not the fallback.
+
+#include "trading/brokers/BrokerModifyFields.h"
+
+#include <QByteArray>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QString>
+#include <QTest>
+
+using namespace fincept::trading::modify_fields;
+
+class TstBrokerModifyFields : public QObject {
+ Q_OBJECT
+
+ private slots:
+ void canonical_key_wins_over_alias();
+ void alias_is_used_when_canonical_is_absent();
+ void every_declared_alias_is_readable();
+ void legitimate_zero_beats_a_later_alias();
+ void missing_key_returns_caller_fallback();
+ void numeric_strings_parse();
+ void non_numeric_values_fall_back();
+ void null_is_treated_as_absent();
+ void undefined_is_treated_as_absent();
+ void text_reads_and_empty_string_falls_back();
+ void has_any_reports_presence_not_truthiness();
+ void regression_iifl_price_modify();
+ void regression_shoonya_trigger_price_modify();
+};
+
+// ── canonical vs alias ───────────────────────────────────────────────────────
+
+void TstBrokerModifyFields::canonical_key_wins_over_alias() {
+ // Priority comes from the KEY ARRAY order, not from the object's storage
+ // order. QJsonObject keeps keys sorted, so "limitPrice" physically precedes
+ // "price" here — if the implementation ever iterated the object instead of
+ // the key set, this test is what catches it.
+ QJsonObject mods;
+ mods.insert(QStringLiteral("limitPrice"), 999.0);
+ mods.insert(QStringLiteral("price"), 101.5);
+ QCOMPARE(number(mods, kPrice, -1.0), 101.5);
+
+ QJsonObject trig;
+ trig.insert(QStringLiteral("auxPrice"), 77.0);
+ trig.insert(QStringLiteral("stopPrice"), 66.0);
+ trig.insert(QStringLiteral("trigger_price"), 50.0);
+ QCOMPARE(number(trig, kTrigger, -1.0), 50.0);
+
+ QJsonObject qty;
+ qty.insert(QStringLiteral("qty"), 999.0);
+ qty.insert(QStringLiteral("quantity"), 25.0);
+ QCOMPARE(number(qty, kQuantity, -1.0), 25.0);
+
+ QJsonObject typ;
+ typ.insert(QStringLiteral("type"), QStringLiteral("MARKET"));
+ typ.insert(QStringLiteral("orderType"), QStringLiteral("SL"));
+ typ.insert(QStringLiteral("order_type"), QStringLiteral("LIMIT"));
+ QCOMPARE(text(typ, kOrderType), QStringLiteral("LIMIT"));
+
+ QJsonObject prod;
+ prod.insert(QStringLiteral("productType"), QStringLiteral("NRML"));
+ prod.insert(QStringLiteral("product"), QStringLiteral("MIS"));
+ QCOMPARE(text(prod, kProduct), QStringLiteral("MIS"));
+}
+
+void TstBrokerModifyFields::alias_is_used_when_canonical_is_absent() {
+ QJsonObject a;
+ a.insert(QStringLiteral("limitPrice"), 250.25);
+ QCOMPARE(number(a, kPrice, -1.0), 250.25);
+
+ QJsonObject b;
+ b.insert(QStringLiteral("limit_price"), 42.0);
+ QCOMPARE(number(b, kPrice, -1.0), 42.0);
+
+ // Last entry in the list must still be reachable.
+ QJsonObject c;
+ c.insert(QStringLiteral("auxPrice"), 12.5);
+ QCOMPARE(number(c, kTrigger, -1.0), 12.5);
+
+ QJsonObject d;
+ d.insert(QStringLiteral("qty"), 7.0);
+ QCOMPARE(number(d, kQuantity, -1.0), 7.0);
+
+ QJsonObject e;
+ e.insert(QStringLiteral("type"), QStringLiteral("SL-M"));
+ QCOMPARE(text(e, kOrderType), QStringLiteral("SL-M"));
+
+ QJsonObject f;
+ f.insert(QStringLiteral("product_type"), QStringLiteral("CNC"));
+ QCOMPARE(text(f, kProduct), QStringLiteral("CNC"));
+}
+
+void TstBrokerModifyFields::every_declared_alias_is_readable() {
+ // Table-driven guard: if someone typos or drops an entry while editing the
+ // key arrays, the adapter that used that spelling starts silently sending 0.
+ for (const char* k : kPrice) {
+ QJsonObject m;
+ m.insert(QString::fromLatin1(k), 123.0);
+ QVERIFY2(has_any(m, kPrice), k);
+ QCOMPARE(number(m, kPrice, -1.0), 123.0);
+ }
+ for (const char* k : kTrigger) {
+ QJsonObject m;
+ m.insert(QString::fromLatin1(k), 456.0);
+ QVERIFY2(has_any(m, kTrigger), k);
+ QCOMPARE(number(m, kTrigger, -1.0), 456.0);
+ }
+ for (const char* k : kQuantity) {
+ QJsonObject m;
+ m.insert(QString::fromLatin1(k), 10.0);
+ QCOMPARE(number(m, kQuantity, -1.0), 10.0);
+ }
+ for (const char* k : kOrderType) {
+ QJsonObject m;
+ m.insert(QString::fromLatin1(k), QStringLiteral("LIMIT"));
+ QCOMPARE(text(m, kOrderType), QStringLiteral("LIMIT"));
+ }
+ for (const char* k : kProduct) {
+ QJsonObject m;
+ m.insert(QString::fromLatin1(k), QStringLiteral("MIS"));
+ QCOMPARE(text(m, kProduct), QStringLiteral("MIS"));
+ }
+}
+
+// ── the subtle one: 0 is a value, not an absence ─────────────────────────────
+
+void TstBrokerModifyFields::legitimate_zero_beats_a_later_alias() {
+ // A caller that explicitly sends price 0 means 0. Truthiness-based lookup
+ // would fall through to limitPrice and transmit 99 — a wrong-price order.
+ QJsonObject p;
+ p.insert(QStringLiteral("price"), 0.0);
+ p.insert(QStringLiteral("limitPrice"), 99.0);
+ QCOMPARE(number(p, kPrice, -1.0), 0.0);
+
+ QJsonObject t;
+ t.insert(QStringLiteral("trigger_price"), 0.0);
+ t.insert(QStringLiteral("stopPrice"), 42.0);
+ QCOMPARE(number(t, kTrigger, -1.0), 0.0);
+
+ // ...and it must not degrade to the caller's fallback either.
+ QJsonObject only_zero;
+ only_zero.insert(QStringLiteral("price"), 0.0);
+ QCOMPARE(number(only_zero, kPrice, 250.0), 0.0);
+
+ // The primitive underneath says the same thing.
+ const QJsonValue v = first_present(only_zero, kPrice);
+ QVERIFY(!v.isUndefined());
+ QCOMPARE(v.toDouble(-1.0), 0.0);
+ QVERIFY(has_any(only_zero, kPrice));
+
+ // Same rule for a numeric-string zero.
+ QJsonObject zero_str;
+ zero_str.insert(QStringLiteral("price"), QStringLiteral("0"));
+ zero_str.insert(QStringLiteral("limitPrice"), 99.0);
+ QCOMPARE(number(zero_str, kPrice, -1.0), 0.0);
+}
+
+// ── absence ──────────────────────────────────────────────────────────────────
+
+void TstBrokerModifyFields::missing_key_returns_caller_fallback() {
+ QJsonObject unrelated;
+ unrelated.insert(QStringLiteral("order_id"), QStringLiteral("ABC123"));
+
+ QCOMPARE(number(unrelated, kPrice, 7.5), 7.5);
+ QCOMPARE(number(unrelated, kTrigger, -1.0), -1.0);
+ QCOMPARE(number(unrelated, kQuantity), 0.0); // documented default fallback
+ QCOMPARE(text(unrelated, kProduct, QStringLiteral("MIS")), QStringLiteral("MIS"));
+ QVERIFY(text(unrelated, kOrderType).isEmpty()); // documented default fallback
+ QVERIFY(!has_any(unrelated, kPrice));
+ QVERIFY(first_present(unrelated, kPrice).isUndefined());
+
+ const QJsonObject empty;
+ QCOMPARE(number(empty, kPrice, 3.25), 3.25);
+ QVERIFY(!has_any(empty, kTrigger));
+}
+
+void TstBrokerModifyFields::null_is_treated_as_absent() {
+ QJsonObject m;
+ m.insert(QStringLiteral("price"), QJsonValue(QJsonValue::Null));
+ QCOMPARE(number(m, kPrice, 12.0), 12.0);
+ QVERIFY(!has_any(m, kPrice));
+
+ // A null canonical key must not shadow a real alias.
+ QJsonObject shadow;
+ shadow.insert(QStringLiteral("price"), QJsonValue(QJsonValue::Null));
+ shadow.insert(QStringLiteral("limitPrice"), 88.0);
+ QCOMPARE(number(shadow, kPrice, -1.0), 88.0);
+
+ // Same behaviour when the null arrives through a real JSON parse.
+ QJsonParseError perr{};
+ const QJsonDocument doc =
+ QJsonDocument::fromJson(QByteArray(R"({"trigger_price": null, "stopPrice": 55.5})"), &perr);
+ QVERIFY(perr.error == QJsonParseError::NoError);
+ QCOMPARE(number(doc.object(), kTrigger, -1.0), 55.5);
+}
+
+void TstBrokerModifyFields::undefined_is_treated_as_absent() {
+ // Whether Qt stores an Undefined value or drops the key on insert, the
+ // observable contract is identical: the reader must skip it.
+ QJsonObject m;
+ m.insert(QStringLiteral("price"), QJsonValue(QJsonValue::Undefined));
+ QCOMPARE(number(m, kPrice, 31.0), 31.0);
+ QVERIFY(!has_any(m, kPrice));
+
+ QJsonObject shadow;
+ shadow.insert(QStringLiteral("price"), QJsonValue(QJsonValue::Undefined));
+ shadow.insert(QStringLiteral("limit_price"), 64.0);
+ QCOMPARE(number(shadow, kPrice, -1.0), 64.0);
+}
+
+// ── numeric strings (the Zerodha bug) ────────────────────────────────────────
+
+void TstBrokerModifyFields::numeric_strings_parse() {
+ // Why number() goes through toVariant() rather than a typed accessor:
+ // QJsonValue::toString() on a NUMBER returns an empty string, which is how
+ // Zerodha's adapter turned a perfectly good price into "".
+ QCOMPARE(QJsonValue(101.25).toString(), QString());
+
+ QJsonObject s;
+ s.insert(QStringLiteral("price"), QStringLiteral("101.25"));
+ QCOMPARE(number(s, kPrice, -1.0), 101.25);
+
+ QJsonObject q;
+ q.insert(QStringLiteral("quantity"), QStringLiteral("50"));
+ QCOMPARE(number(q, kQuantity, -1.0), 50.0);
+
+ QJsonObject neg;
+ neg.insert(QStringLiteral("trigger_price"), QStringLiteral("-12.5"));
+ QCOMPARE(number(neg, kTrigger, 0.0), -12.5);
+
+ // ...and a JSON number still reads as a number.
+ QJsonObject n;
+ n.insert(QStringLiteral("price"), 101.25);
+ QCOMPARE(number(n, kPrice, -1.0), 101.25);
+}
+
+void TstBrokerModifyFields::non_numeric_values_fall_back() {
+ QJsonObject junk;
+ junk.insert(QStringLiteral("price"), QStringLiteral("not-a-number"));
+ QCOMPARE(number(junk, kPrice, 9.0), 9.0);
+
+ QJsonObject inner;
+ inner.insert(QStringLiteral("v"), 1.0);
+ QJsonObject structured;
+ structured.insert(QStringLiteral("price"), inner);
+ QCOMPARE(number(structured, kPrice, 9.0), 9.0);
+
+ QJsonArray list;
+ list.append(1.0);
+ list.append(2.0);
+ QJsonObject arr;
+ arr.insert(QStringLiteral("quantity"), list);
+ QCOMPARE(number(arr, kQuantity, 9.0), 9.0);
+}
+
+// ── text() ───────────────────────────────────────────────────────────────────
+
+void TstBrokerModifyFields::text_reads_and_empty_string_falls_back() {
+ QJsonObject ok;
+ ok.insert(QStringLiteral("product"), QStringLiteral("NRML"));
+ QCOMPARE(text(ok, kProduct, QStringLiteral("MIS")), QStringLiteral("NRML"));
+
+ // An empty string is treated as "no usable value" and yields the fallback.
+ QJsonObject blank;
+ blank.insert(QStringLiteral("product"), QStringLiteral(""));
+ QCOMPARE(text(blank, kProduct, QStringLiteral("MIS")), QStringLiteral("MIS"));
+
+ // Documented asymmetry vs number(): an empty CANONICAL string does not fall
+ // through to a later alias — first_present() already committed to the key,
+ // and text() then applies the caller's fallback. Pinned so a future change
+ // to either half is a deliberate one.
+ QJsonObject blank_then_alias;
+ blank_then_alias.insert(QStringLiteral("product"), QStringLiteral(""));
+ blank_then_alias.insert(QStringLiteral("productType"), QStringLiteral("NRML"));
+ QCOMPARE(text(blank_then_alias, kProduct, QStringLiteral("MIS")), QStringLiteral("MIS"));
+}
+
+void TstBrokerModifyFields::has_any_reports_presence_not_truthiness() {
+ QJsonObject zero;
+ zero.insert(QStringLiteral("quantity"), 0.0);
+ QVERIFY(has_any(zero, kQuantity));
+
+ QJsonObject blank;
+ blank.insert(QStringLiteral("product"), QStringLiteral(""));
+ QVERIFY(has_any(blank, kProduct)); // present, even though text() falls back
+
+ QJsonObject nulled;
+ nulled.insert(QStringLiteral("product"), QJsonValue(QJsonValue::Null));
+ QVERIFY(!has_any(nulled, kProduct));
+
+ QVERIFY(!has_any(QJsonObject(), kProduct));
+}
+
+// ── regressions, named for the incidents ─────────────────────────────────────
+
+void TstBrokerModifyFields::regression_iifl_price_modify() {
+ // Caller-side spelling. IIFL read "limitPrice" and so transmitted
+ // modifiedLimitPrice = 0 for every price modify.
+ QJsonObject mods;
+ mods.insert(QStringLiteral("price"), 145.5);
+ mods.insert(QStringLiteral("quantity"), 50.0);
+
+ QCOMPARE(number(mods, kPrice, 0.0), 145.5);
+ QVERIFY2(!qFuzzyIsNull(number(mods, kPrice, 0.0)), "the IIFL bug transmitted 0 here");
+ QCOMPARE(number(mods, kQuantity, 0.0), 50.0);
+}
+
+void TstBrokerModifyFields::regression_shoonya_trigger_price_modify() {
+ // Shoonya / Flattrade / Tradejini read "triggerPrice" and so transmitted
+ // trgprc = 0 for every stop-loss modify.
+ QJsonObject mods;
+ mods.insert(QStringLiteral("trigger_price"), 99.5);
+ mods.insert(QStringLiteral("price"), 100.0);
+
+ QCOMPARE(number(mods, kTrigger, 0.0), 99.5);
+ QVERIFY2(!qFuzzyIsNull(number(mods, kTrigger, 0.0)), "the Shoonya bug transmitted trgprc=0 here");
+ QCOMPARE(number(mods, kPrice, 0.0), 100.0);
+
+ // And the mirror image: an adapter-spelled payload read by canonical name.
+ QJsonObject adapter_spelled;
+ adapter_spelled.insert(QStringLiteral("triggerPrice"), 99.5);
+ QCOMPARE(number(adapter_spelled, kTrigger, 0.0), 99.5);
+}
+
+QTEST_GUILESS_MAIN(TstBrokerModifyFields)
+#include "tst_broker_modify_fields.moc"
diff --git a/fincept-qt/tests/tst_order_validator.cpp b/fincept-qt/tests/tst_order_validator.cpp
new file mode 100644
index 000000000..118835572
--- /dev/null
+++ b/fincept-qt/tests/tst_order_validator.cpp
@@ -0,0 +1,440 @@
+// Unit tests for src/trading/OrderValidator.{h,cpp}
+//
+// OrderValidator.cpp includes only its own header, which includes only
+// trading/TradingTypes.h (Qt Core types + plain aggregate structs, no .cpp of
+// its own). That is why this suite costs exactly one extra translation unit and
+// links nothing from the broker registry, the HTTP stack or any service.
+//
+// The headline case is validate_smart()'s FLATTEN order: position_size == 0 is a
+// legitimate target ("close me out"), and the engine derives the quantity from
+// the live book — so quantity == 0 alongside it must validate. A rule that
+// required a positive quantity here would have rejected every flatten order the
+// terminal ever sends.
+
+#include "trading/OrderValidator.h"
+#include "trading/TradingTypes.h"
+
+#include <QString>
+#include <QStringList>
+#include <QTest>
+
+using fincept::trading::BasketOrderRequest;
+using fincept::trading::OrderSide;
+using fincept::trading::OrderType;
+using fincept::trading::OrderValidator;
+using fincept::trading::ProductType;
+using fincept::trading::SmartOrder;
+using fincept::trading::UnifiedOrder;
+
+using Validation = OrderValidator::ValidationResult;
+
+static bool has_error(const Validation& r, const QString& needle) {
+ for (const QString& e : r.errors) {
+ if (e.contains(needle))
+ return true;
+ }
+ return false;
+}
+
+static QString joined(const Validation& r) {
+ return r.errors.join(QStringLiteral(" | "));
+}
+
+// A minimal order that must validate, so each test can perturb exactly one field.
+static UnifiedOrder good_order() {
+ UnifiedOrder o;
+ o.symbol = QStringLiteral("RELIANCE");
+ o.exchange = QStringLiteral("NSE");
+ o.side = OrderSide::Buy;
+ o.order_type = OrderType::Market;
+ o.quantity = 10;
+ o.product_type = ProductType::Intraday;
+ return o;
+}
+
+static SmartOrder good_smart() {
+ SmartOrder o;
+ o.symbol = QStringLiteral("RELIANCE");
+ o.exchange = QStringLiteral("NSE");
+ o.action = OrderSide::Buy;
+ o.order_type = OrderType::Market;
+ o.quantity = 10;
+ o.position_size = 100;
+ return o;
+}
+
+class TstOrderValidator : public QObject {
+ Q_OBJECT
+
+ private slots:
+ // validate()
+ void accepts_a_well_formed_market_order();
+ void rejects_missing_or_blank_symbol();
+ void rejects_missing_exchange();
+ void rejects_unknown_exchange();
+ void exchange_whitelist_spot_checks();
+ void exchange_match_is_case_insensitive_but_not_whitespace_tolerant();
+ void rejects_non_positive_quantity();
+ void price_required_only_for_limit_family();
+ void trigger_required_only_for_stop_family();
+ void stop_loss_limit_requires_both_price_and_trigger();
+ void errors_accumulate();
+
+ // validate_smart()
+ void smart_flatten_with_zero_quantity_is_valid();
+ void smart_allows_zero_quantity_for_any_position_size();
+ void smart_rejects_negative_quantity();
+ void smart_validates_symbol_and_exchange();
+ void smart_price_and_trigger_rules_match_validate();
+
+ // validate_basket()
+ void basket_rejects_empty();
+ void basket_accepts_all_valid_legs();
+ void basket_reports_the_failing_leg_by_index_and_symbol();
+};
+
+// ── validate() ───────────────────────────────────────────────────────────────
+
+void TstOrderValidator::accepts_a_well_formed_market_order() {
+ const auto r = OrderValidator::validate(good_order());
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+ QVERIFY(r.errors.isEmpty());
+}
+
+void TstOrderValidator::rejects_missing_or_blank_symbol() {
+ UnifiedOrder o = good_order();
+ o.symbol.clear();
+ auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Symbol is required")));
+
+ // Whitespace is trimmed before the emptiness check.
+ o.symbol = QStringLiteral(" ");
+ r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Symbol is required")));
+}
+
+void TstOrderValidator::rejects_missing_exchange() {
+ UnifiedOrder o = good_order();
+ o.exchange.clear();
+ auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Exchange is required")));
+ // A blank exchange is "required", not "invalid" — only one of the two fires.
+ QVERIFY(!has_error(r, QStringLiteral("Invalid exchange")));
+
+ o.exchange = QStringLiteral(" ");
+ r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Exchange is required")));
+}
+
+void TstOrderValidator::rejects_unknown_exchange() {
+ UnifiedOrder o = good_order();
+ o.exchange = QStringLiteral("NOTANEXCHANGE");
+ const auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Invalid exchange: NOTANEXCHANGE")));
+}
+
+void TstOrderValidator::exchange_whitelist_spot_checks() {
+ // India
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("NSE")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("BSE")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("NFO")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("BFO")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("MCX")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("CDS")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("NSE_INDEX")));
+ // US / global
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("NYSE")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("NASDAQ")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("LSE")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("XETRA")));
+ // crypto / forex
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("CRYPTO")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("FOREX")));
+
+ // Not on the list.
+ QVERIFY(!OrderValidator::is_valid_exchange(QString()));
+ QVERIFY(!OrderValidator::is_valid_exchange(QStringLiteral("BINANCE")));
+ QVERIFY(!OrderValidator::is_valid_exchange(QStringLiteral("NSEINDEX")));
+ QVERIFY(!OrderValidator::is_valid_exchange(QStringLiteral("N")));
+}
+
+void TstOrderValidator::exchange_match_is_case_insensitive_but_not_whitespace_tolerant() {
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("nse")));
+ QVERIFY(OrderValidator::is_valid_exchange(QStringLiteral("Nasdaq")));
+
+ // Documented quirk, pinned so a change to it is deliberate: validate() trims
+ // only for the emptiness check and then hands the RAW string to the
+ // whitelist, so a padded exchange is rejected as invalid rather than
+ // normalised. Callers must trim upstream.
+ QVERIFY(!OrderValidator::is_valid_exchange(QStringLiteral(" NSE ")));
+
+ UnifiedOrder o = good_order();
+ o.exchange = QStringLiteral(" NSE ");
+ const auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Invalid exchange")));
+}
+
+void TstOrderValidator::rejects_non_positive_quantity() {
+ UnifiedOrder o = good_order();
+ o.quantity = 0;
+ auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Quantity must be positive")));
+
+ o.quantity = -5;
+ r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Quantity must be positive")));
+
+ // Fractional quantities are permitted (crypto / fractional shares).
+ o.quantity = 0.5;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+}
+
+void TstOrderValidator::price_required_only_for_limit_family() {
+ UnifiedOrder o = good_order();
+
+ o.order_type = OrderType::Limit;
+ o.price = 0;
+ auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Price is required")));
+
+ o.price = 2500.75;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+
+ // Market orders never need a price.
+ o.order_type = OrderType::Market;
+ o.price = 0;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+
+ // A negative price is as bad as a missing one.
+ o.order_type = OrderType::Limit;
+ o.price = -1;
+ r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Price is required")));
+}
+
+void TstOrderValidator::trigger_required_only_for_stop_family() {
+ UnifiedOrder o = good_order();
+
+ o.order_type = OrderType::StopLoss;
+ o.stop_price = 0;
+ auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Trigger price is required")));
+
+ o.stop_price = 2400;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+
+ // A plain Market order with no trigger is fine.
+ o.order_type = OrderType::Market;
+ o.stop_price = 0;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+
+ // ...and so is a Limit order (trigger belongs to the stop family only).
+ o.order_type = OrderType::Limit;
+ o.price = 2500;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+}
+
+void TstOrderValidator::stop_loss_limit_requires_both_price_and_trigger() {
+ UnifiedOrder o = good_order();
+ o.order_type = OrderType::StopLossLimit;
+ o.price = 0;
+ o.stop_price = 0;
+
+ auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QCOMPARE(r.errors.size(), qsizetype(2));
+ QVERIFY(has_error(r, QStringLiteral("Price is required")));
+ QVERIFY(has_error(r, QStringLiteral("Trigger price is required")));
+
+ o.price = 2500;
+ r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QCOMPARE(r.errors.size(), qsizetype(1));
+ QVERIFY(has_error(r, QStringLiteral("Trigger price is required")));
+
+ o.stop_price = 2490;
+ r = OrderValidator::validate(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+}
+
+void TstOrderValidator::errors_accumulate() {
+ UnifiedOrder o;
+ o.symbol.clear();
+ o.exchange = QStringLiteral("NOPE");
+ o.order_type = OrderType::Limit;
+ o.quantity = 0;
+ o.price = 0;
+
+ const auto r = OrderValidator::validate(o);
+ QVERIFY(!r.valid);
+ QCOMPARE(r.errors.size(), qsizetype(4));
+ QVERIFY(has_error(r, QStringLiteral("Symbol is required")));
+ QVERIFY(has_error(r, QStringLiteral("Invalid exchange: NOPE")));
+ QVERIFY(has_error(r, QStringLiteral("Quantity must be positive")));
+ QVERIFY(has_error(r, QStringLiteral("Price is required")));
+}
+
+// ── validate_smart() ─────────────────────────────────────────────────────────
+
+void TstOrderValidator::smart_flatten_with_zero_quantity_is_valid() {
+ // THE case this suite exists for. "Flatten": target net position 0, quantity
+ // left at 0 because the engine reads the live book and derives it. Requiring
+ // a positive quantity here rejects every flatten order.
+ SmartOrder o = good_smart();
+ o.position_size = 0;
+ o.quantity = 0;
+
+ const auto r = OrderValidator::validate_smart(o);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+ QVERIFY(r.errors.isEmpty());
+ QVERIFY(!has_error(r, QStringLiteral("Quantity")));
+}
+
+void TstOrderValidator::smart_allows_zero_quantity_for_any_position_size() {
+ // Not just the flatten case: quantity is always derivable, so 0 is never an
+ // error on a smart order regardless of the target size.
+ SmartOrder o = good_smart();
+ o.quantity = 0;
+
+ o.position_size = 100;
+ QVERIFY(OrderValidator::validate_smart(o).valid);
+
+ o.position_size = -100; // target short
+ QVERIFY(OrderValidator::validate_smart(o).valid);
+
+ o.position_size = 0;
+ QVERIFY(OrderValidator::validate_smart(o).valid);
+
+ // An explicit quantity is fine too.
+ o.quantity = 25;
+ QVERIFY(OrderValidator::validate_smart(o).valid);
+}
+
+void TstOrderValidator::smart_rejects_negative_quantity() {
+ // Only a nonsensical NEGATIVE fallback quantity is an error.
+ SmartOrder o = good_smart();
+ o.quantity = -1;
+
+ const auto r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Quantity cannot be negative")));
+ // And specifically NOT the stricter validate() wording.
+ QVERIFY(!has_error(r, QStringLiteral("Quantity must be positive")));
+}
+
+void TstOrderValidator::smart_validates_symbol_and_exchange() {
+ SmartOrder o = good_smart();
+ o.symbol = QStringLiteral(" ");
+ auto r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Symbol is required")));
+
+ o = good_smart();
+ o.exchange.clear();
+ r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Exchange is required")));
+
+ o = good_smart();
+ o.exchange = QStringLiteral("NOPE");
+ r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Invalid exchange: NOPE")));
+}
+
+void TstOrderValidator::smart_price_and_trigger_rules_match_validate() {
+ SmartOrder o = good_smart();
+
+ o.order_type = OrderType::Limit;
+ o.price = 0;
+ auto r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Price is required")));
+
+ o.price = 2500;
+ QVERIFY(OrderValidator::validate_smart(o).valid);
+
+ o = good_smart();
+ o.order_type = OrderType::StopLoss;
+ o.trigger_price = 0;
+ r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Trigger price is required")));
+
+ o.trigger_price = 2400;
+ QVERIFY(OrderValidator::validate_smart(o).valid);
+
+ // A flatten order with a stop type still needs its trigger.
+ o = good_smart();
+ o.position_size = 0;
+ o.quantity = 0;
+ o.order_type = OrderType::StopLoss;
+ o.trigger_price = 0;
+ r = OrderValidator::validate_smart(o);
+ QVERIFY(!r.valid);
+ QVERIFY(has_error(r, QStringLiteral("Trigger price is required")));
+ QVERIFY(!has_error(r, QStringLiteral("Quantity")));
+}
+
+// ── validate_basket() ────────────────────────────────────────────────────────
+
+void TstOrderValidator::basket_rejects_empty() {
+ BasketOrderRequest b;
+ const auto r = OrderValidator::validate_basket(b);
+ QVERIFY(!r.valid);
+ QCOMPARE(r.errors.size(), qsizetype(1));
+ QVERIFY(has_error(r, QStringLiteral("Basket has no orders")));
+}
+
+void TstOrderValidator::basket_accepts_all_valid_legs() {
+ BasketOrderRequest b;
+ b.strategy_name = QStringLiteral("pair");
+ b.orders.append(good_order());
+
+ UnifiedOrder leg2 = good_order();
+ leg2.symbol = QStringLiteral("TCS");
+ leg2.side = OrderSide::Sell;
+ b.orders.append(leg2);
+
+ const auto r = OrderValidator::validate_basket(b);
+ QVERIFY2(r.valid, qPrintable(joined(r)));
+ QVERIFY(r.errors.isEmpty());
+}
+
+void TstOrderValidator::basket_reports_the_failing_leg_by_index_and_symbol() {
+ BasketOrderRequest b;
+ b.orders.append(good_order()); // leg 1: fine
+
+ UnifiedOrder bad = good_order();
+ bad.symbol = QStringLiteral("TCS");
+ bad.quantity = 0; // leg 2: broken
+ b.orders.append(bad);
+
+ const auto r = OrderValidator::validate_basket(b);
+ QVERIFY(!r.valid);
+ QCOMPARE(r.errors.size(), qsizetype(1));
+ // 1-based index, then the leg's symbol, then the underlying message.
+ QVERIFY2(has_error(r, QStringLiteral("Order 2 (TCS): Quantity must be positive")),
+ qPrintable(joined(r)));
+ QVERIFY(!has_error(r, QStringLiteral("Order 1")));
+}
+
+QTEST_GUILESS_MAIN(TstOrderValidator)
+#include "tst_order_validator.moc"
diff --git a/fincept-qt/tests/tst_result.cpp b/fincept-qt/tests/tst_result.cpp
new file mode 100644
index 000000000..e23886133
--- /dev/null
+++ b/fincept-qt/tests/tst_result.cpp
@@ -0,0 +1,202 @@
+// Unit tests for src/core/result/Result.h
+//
+// Result<T> is the error-handling contract for the whole codebase ("Use Result<T>
+// for error handling" — CLAUDE.md Code Standards), so its edges are worth pinning
+// precisely rather than assuming.
+//
+// The two behaviours most likely to surprise a caller, both asserted below:
+//
+// 1. Result<T>::value() on an error is NOT infallible. It is std::get<T> on a
+// variant holding the Error alternative, i.e. it throws std::bad_variant_access.
+// Same for error() on an ok result. Callers must branch on is_ok()/is_err()
+// first; there is no checked accessor and no default-returning overload.
+// 2. Result<void> does NOT behave the same way: its error() is a plain member
+// read that returns an empty string on success. So `r.error().empty()` is a
+// safe (if wrong-headed) success test for Result<void> and a THROWING one
+// for Result<T> — and it is not even a correct success test for
+// Result<void>, because err("") is still an error.
+
+#include "core/result/Result.h"
+
+#include <QString>
+#include <QTest>
+
+#include <memory>
+#include <string>
+#include <variant>
+
+using fincept::Result;
+
+// Compare through QString so a failure prints the actual text rather than
+// QTest's generic "Compared values are not the same".
+static QString qs(const std::string& s) {
+ return QString::fromStdString(s);
+}
+
+class TstResult : public QObject {
+ Q_OBJECT
+
+ private slots:
+ void ok_construction();
+ void err_construction();
+ void value_is_mutable();
+ void moves_a_move_only_payload();
+ void copies_preserve_state();
+ void empty_error_message_is_still_an_error();
+ void value_on_error_throws();
+ void error_on_ok_throws();
+ void void_ok();
+ void void_err();
+ void void_error_on_ok_is_empty_not_throwing();
+ void map_transforms_ok();
+ void map_propagates_error();
+ void map_changes_type();
+};
+
+// ── Result<T> ────────────────────────────────────────────────────────────────
+
+void TstResult::ok_construction() {
+ const auto r = Result<int>::ok(42);
+ QVERIFY(r.is_ok());
+ QVERIFY(!r.is_err());
+ QCOMPARE(r.value(), 42);
+
+ // A falsy payload is still a success — Result carries state, not truthiness.
+ const auto zero = Result<int>::ok(0);
+ QVERIFY(zero.is_ok());
+ QCOMPARE(zero.value(), 0);
+
+ const auto empty_str = Result<std::string>::ok(std::string());
+ QVERIFY(empty_str.is_ok());
+ QVERIFY(empty_str.value().empty());
+}
+
+void TstResult::err_construction() {
+ const auto r = Result<int>::err("network unreachable");
+ QVERIFY(r.is_err());
+ QVERIFY(!r.is_ok());
+ QCOMPARE(qs(r.error()), QStringLiteral("network unreachable"));
+}
+
+void TstResult::value_is_mutable() {
+ auto r = Result<int>::ok(1);
+ r.value() = 7;
+ QCOMPARE(r.value(), 7);
+ QVERIFY(r.is_ok());
+}
+
+void TstResult::moves_a_move_only_payload() {
+ // ok() takes T by value and moves it into the variant, so a move-only payload
+ // (unique_ptr, socket handle, …) round-trips without requiring a copy ctor.
+ auto r = Result<std::unique_ptr<int>>::ok(std::make_unique<int>(5));
+ QVERIFY(r.is_ok());
+ QVERIFY(r.value() != nullptr);
+ QCOMPARE(*r.value(), 5);
+
+ const auto e = Result<std::unique_ptr<int>>::err("alloc failed");
+ QVERIFY(e.is_err());
+ QCOMPARE(qs(e.error()), QStringLiteral("alloc failed"));
+}
+
+void TstResult::copies_preserve_state() {
+ const auto ok_src = Result<int>::ok(11);
+ const Result<int> ok_copy = ok_src;
+ QVERIFY(ok_copy.is_ok());
+ QCOMPARE(ok_copy.value(), 11);
+
+ const auto err_src = Result<int>::err("boom");
+ const Result<int> err_copy = err_src;
+ QVERIFY(err_copy.is_err());
+ QCOMPARE(qs(err_copy.error()), QStringLiteral("boom"));
+}
+
+void TstResult::empty_error_message_is_still_an_error() {
+ // is_err() is decided by which variant alternative is engaged, never by the
+ // message. Using `error().empty()` as a proxy for failure is a bug.
+ const auto r = Result<int>::err("");
+ QVERIFY(r.is_err());
+ QVERIFY(!r.is_ok());
+ QVERIFY(r.error().empty());
+}
+
+void TstResult::value_on_error_throws() {
+#ifdef QT_NO_EXCEPTIONS
+ QSKIP("Qt built without exception support; std::get would terminate, not throw");
+#else
+ const auto r = Result<int>::err("nope");
+ QVERIFY(r.is_err());
+ QVERIFY_THROWS_EXCEPTION(std::bad_variant_access, (void)r.value());
+
+ auto mutable_r = Result<int>::err("nope");
+ QVERIFY_THROWS_EXCEPTION(std::bad_variant_access, (void)mutable_r.value());
+#endif
+}
+
+void TstResult::error_on_ok_throws() {
+#ifdef QT_NO_EXCEPTIONS
+ QSKIP("Qt built without exception support; std::get would terminate, not throw");
+#else
+ const auto r = Result<int>::ok(1);
+ QVERIFY(r.is_ok());
+ QVERIFY_THROWS_EXCEPTION(std::bad_variant_access, (void)r.error());
+#endif
+}
+
+// ── Result<void> ─────────────────────────────────────────────────────────────
+
+void TstResult::void_ok() {
+ const auto r = Result<void>::ok();
+ QVERIFY(r.is_ok());
+ QVERIFY(!r.is_err());
+}
+
+void TstResult::void_err() {
+ const auto r = Result<void>::err("write failed");
+ QVERIFY(r.is_err());
+ QVERIFY(!r.is_ok());
+ QCOMPARE(qs(r.error()), QStringLiteral("write failed"));
+
+ // Same rule as Result<T>: an empty message is still a failure.
+ const auto blank = Result<void>::err("");
+ QVERIFY(blank.is_err());
+ QVERIFY(blank.error().empty());
+}
+
+void TstResult::void_error_on_ok_is_empty_not_throwing() {
+ // The asymmetry with Result<T>::error(), pinned deliberately: this one is a
+ // plain member read, so it is safe on success and returns "".
+ const auto r = Result<void>::ok();
+ QVERIFY(r.error().empty());
+}
+
+// ── map() ────────────────────────────────────────────────────────────────────
+
+void TstResult::map_transforms_ok() {
+ const auto r = Result<int>::ok(21).map([](int v) { return v * 2; });
+ QVERIFY(r.is_ok());
+ QCOMPARE(r.value(), 42);
+}
+
+void TstResult::map_propagates_error() {
+ bool called = false;
+ const auto r = Result<int>::err("upstream failed").map([&called](int v) {
+ called = true;
+ return v * 2;
+ });
+ QVERIFY(r.is_err());
+ QCOMPARE(qs(r.error()), QStringLiteral("upstream failed"));
+ QVERIFY2(!called, "map() must not invoke the transform on an error result");
+}
+
+void TstResult::map_changes_type() {
+ const auto r = Result<int>::ok(7).map([](int v) { return std::to_string(v) + "s"; });
+ QVERIFY(r.is_ok());
+ QCOMPARE(qs(r.value()), QStringLiteral("7s"));
+
+ const auto e = Result<int>::err("bad").map([](int v) { return std::to_string(v); });
+ QVERIFY(e.is_err());
+ QCOMPARE(qs(e.error()), QStringLiteral("bad"));
+}
+
+QTEST_GUILESS_MAIN(TstResult)
+#include "tst_result.moc"
diff --git a/fincept-qt/v2.txt b/fincept-qt/v2.txt
deleted file mode 100644
index fc08631de..000000000
--- a/fincept-qt/v2.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-### files defining connectBroker / calling exchange_token ###
-(eval):3: no matches found: --include=*.cpp