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.1.0 update

tilakpatel225a4af2784998
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index dd1d3ae48..6caaabd3a 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -552,8 +552,8 @@ jobs:
<key>CFBundleIdentifier</key><string>com.fincept.terminal</string>
<key>CFBundleName</key><string>FinceptTerminal</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>4.0.3</string>
- <key>CFBundleVersion</key><string>4.0.3</string>
+ <key>CFBundleShortVersionString</key><string>4.1.0</string>
+ <key>CFBundleVersion</key><string>4.1.0</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c6cd9076b..d548ae716 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -591,6 +591,46 @@ jobs:
echo "Built: FinceptTerminal-${VERSION}-linux-x64.rpm ($(du -sh "build/FinceptTerminal-${VERSION}-linux-x64.rpm" | cut -f1))"
+ # ── Optional: QtIFW "wizard" installer with a Target Directory page ─────
+ # Additive to the portable AppImage (which stays the auto-update channel).
+ # Packages the linuxdeploy AppDir (binary + bundled Qt + plugins) so the
+ # install is relocatable to ANY chosen path; the staged qt.conf + rpath
+ # resolve Qt at the install location. Renamed "-wizard.bin" so it never
+ # matches the updater regex (\.run$|linux.*setup).
+ # NOTE: VALIDATE ON A REAL RUNNER — first IFW-on-Linux build with bundled
+ # Qt; confirm the installed app launches (platform plugin loads via qt.conf).
+ - name: Generate IFW wizard installer
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ VERSION=$(grep -Po 'project\(FinceptTerminal VERSION \K[0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt)
+ if [ ! -d build/AppDir/usr ]; then
+ echo "::error::build/AppDir/usr missing — the AppImage step must run first"; exit 1
+ fi
+
+ # QtIFW tool (binarycreator)
+ python3 -m pip install --upgrade aqtinstall
+ aqt install-tool linux desktop ${{ env.QT_IFW_TOOL }} --outputdir "${{ runner.temp }}/qtifw"
+ export QT_IFW_DIR="${{ runner.temp }}/qtifw/Tools/QtInstallerFramework/${{ env.QT_IFW_VERSION }}"
+ export PATH="${QT_IFW_DIR}/bin:${PATH}"
+ command -v binarycreator >/dev/null || { echo "::error::binarycreator not on PATH"; exit 1; }
+
+ # Reconfigure with the installer path ON + the linuxdeploy AppDir as the
+ # relocatable payload. deb/rpm already built (FHS), so order is safe.
+ cmake -S . -B build \
+ -DFINCEPT_BUILD_INSTALLER=ON \
+ -DFINCEPT_IFW_PAYLOAD="${PWD}/build/AppDir/usr" >/dev/null
+ BASENAME="FinceptTerminal-${VERSION}-linux-x64-wizard"
+ ( cd build && cpack -G IFW -D CPACK_PACKAGE_FILE_NAME="${BASENAME}" --verbose )
+
+ # IFW emits <name>.run; rename to .bin so the updater regex
+ # (\.run$|linux.*setup) never selects it over the AppImage.
+ SRC=$(ls build/${BASENAME}.run 2>/dev/null | head -1)
+ [ -n "${SRC}" ] || { echo "::error::IFW .run not produced"; ls -la build; exit 1; }
+ mv "${SRC}" "build/${BASENAME}.bin"
+ chmod +x "build/${BASENAME}.bin"
+ echo "Built: ${BASENAME}.bin ($(du -sh "build/${BASENAME}.bin" | cut -f1))"
+
# ── Upload ────────────────────────────────────────────────────────────
# Version-stamped filename so update-manifest regex picks it up.
- name: Upload artifact
@@ -602,6 +642,7 @@ jobs:
fincept-qt/build/FinceptTerminal-*-linux-x64-setup.run.zsync
fincept-qt/build/FinceptTerminal-*-linux-x64.deb
fincept-qt/build/FinceptTerminal-*-linux-x64.rpm
+ fincept-qt/build/FinceptTerminal-*-linux-x64-wizard.bin
retention-days: 30
# ═════════════════════════════════════════════════════════════════════════════
@@ -637,6 +678,17 @@ jobs:
cache: true
cache-key-prefix: qt-macos-arm64-release
+ # ── Qt Installer Framework (for the optional wizard installer) ─────────
+ - name: Install Qt Installer Framework
+ run: |
+ set -euo pipefail
+ python3 -m pip install --upgrade aqtinstall
+ aqt install-tool mac desktop ${{ env.QT_IFW_TOOL }} \
+ --outputdir "${{ runner.temp }}/qtifw"
+ IFW_DIR="${{ runner.temp }}/qtifw/Tools/QtInstallerFramework/${{ env.QT_IFW_VERSION }}"
+ echo "QT_IFW_DIR=${IFW_DIR}" >> "$GITHUB_ENV"
+ echo "${IFW_DIR}/bin" >> "$GITHUB_PATH"
+
- name: Install Python 3.12
run: brew install [email protected] || brew upgrade [email protected] || true
@@ -737,8 +789,8 @@ jobs:
<key>CFBundleIdentifier</key><string>com.fincept.terminal</string>
<key>CFBundleName</key><string>FinceptTerminal</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>4.0.3</string>
- <key>CFBundleVersion</key><string>4.0.3</string>
+ <key>CFBundleShortVersionString</key><string>4.1.0</string>
+ <key>CFBundleVersion</key><string>4.1.0</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict></plist>
@@ -1453,6 +1505,62 @@ jobs:
cp -R "build/${{ env.APP_NAME }}.app" "dist/"
echo "Final bundle size: $(du -sh "dist/${{ env.APP_NAME }}.app" | cut -f1)"
+ # ── Optional: QtIFW "wizard" installer with a Target Directory page ─────
+ # Additive to the DMG (which stays the auto-update channel). The CMake
+ # install rule copies the SIGNED build/FinceptTerminal.app via `ditto`, so
+ # code signatures survive (issue #139). Output is named "-wizard.zip" so it
+ # never matches the updater regex (\.dmg$|macos.*setup) — it won't compete
+ # with the DMG for the auto-update asset.
+ # NOTE: VALIDATE ON A REAL RUNNER — this is the first IFW-on-macOS
+ # build/sign/notarize path. The bundle is signed + stapled BEFORE this step
+ # (the staple step above), satisfying the install-rule contract.
+ - name: Generate IFW wizard installer (sign + notarize)
+ working-directory: fincept-qt
+ env:
+ SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
+ APPLE_ID: ${{ secrets.MACOS_NOTARY_APPLE_ID }}
+ TEAM_ID: ${{ secrets.MACOS_NOTARY_TEAM_ID }}
+ NOTARY_PASSWORD: ${{ secrets.MACOS_NOTARY_PASSWORD }}
+ run: |
+ set -euo pipefail
+ VERSION=$(grep -Eo 'project\(FinceptTerminal VERSION [0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt | awk '{print $3}')
+ command -v binarycreator >/dev/null || { echo "::error::binarycreator not on PATH"; exit 1; }
+
+ # Reconfigure with the installer path ON (reuses the cached build); the
+ # install(CODE ditto) rule packages the already-signed bundle.
+ cmake -S . -B build -DFINCEPT_BUILD_INSTALLER=ON >/dev/null
+ BASENAME="FinceptTerminal-${VERSION}-macos-arm64-wizard"
+ ( cd build && cpack -G IFW -C ${{ env.BUILD_TYPE }} \
+ -D CPACK_PACKAGE_FILE_NAME="${BASENAME}" --verbose )
+
+ WIZ_APP="build/${BASENAME}.app"
+ [ -d "${WIZ_APP}" ] || { echo "::error::IFW installer not produced"; ls -la build; exit 1; }
+
+ # Sign the installer app's own Mach-Os leaf-first (the payload is an
+ # embedded archive that is already signed+notarized+stapled).
+ while IFS= read -r m; do
+ codesign --force --options runtime --timestamp --sign "$SIGNING_IDENTITY" "$m" || true
+ done < <(find "${WIZ_APP}" -type f \( -perm -u+x -o -name "*.dylib" \) 2>/dev/null)
+ codesign --force --options runtime --timestamp --sign "$SIGNING_IDENTITY" "${WIZ_APP}"
+
+ # Notarize a zip of the installer app, then staple. (For production,
+ # adopt the submit/poll/staple loop used by the DMG step — --wait has
+ # no retry on the runner's transient notary network errors.)
+ ZIP="${RUNNER_TEMP}/${BASENAME}.zip"
+ /usr/bin/ditto -c -k --keepParent "${WIZ_APP}" "${ZIP}"
+ if SUB_ID=$(xcrun notarytool submit "${ZIP}" \
+ --apple-id "$APPLE_ID" --team-id "$TEAM_ID" --password "$NOTARY_PASSWORD" \
+ --wait --output-format json | jq -r '.id // empty') && [ -n "${SUB_ID}" ]; then
+ xcrun stapler staple "${WIZ_APP}" || echo "::warning::stapling wizard failed"
+ else
+ echo "::warning::wizard installer notarization unconfirmed — validate manually"
+ fi
+
+ # Ship as a zip (a bare .app can't be a GH release asset).
+ DIST_ZIP="build/${BASENAME}.zip"
+ /usr/bin/ditto -c -k --keepParent "${WIZ_APP}" "${DIST_ZIP}"
+ ls -lh "${DIST_ZIP}"
+
# ── Generate Installer (DMG via hdiutil) ──────────────────────────────
# We intentionally skip CPack IFW on macOS: CPack's install(TARGETS ...
# BUNDLE) rule packages the raw build-tree .app, NOT the post-processed
@@ -1596,7 +1704,9 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: FinceptTerminal-macOS-arm64-installer
- path: fincept-qt/build/FinceptTerminal-*-macos-arm64-setup.dmg
+ path: |
+ fincept-qt/build/FinceptTerminal-*-macos-arm64-setup.dmg
+ fincept-qt/build/FinceptTerminal-*-macos-arm64-wizard.zip
retention-days: 30
# ═════════════════════════════════════════════════════════════════════════════
diff --git a/README.md b/README.md
index 7aa4ed5dd..ae44b1cdc 100644
--- a/README.md
+++ b/README.md
@@ -65,13 +65,13 @@ State-of-the-art financial intelligence platform with institutional-grade financ
<!-- DOWNLOAD-TABLE-START -->
### Option 1 — Download Installer (Recommended)
-Latest release: **v4.0.3** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.0.3)
+Latest release: **v4.1.0** — [View all releases](https://github.com/Fincept-Corporation/FinceptTerminal/releases/tag/v4.1.0)
| Platform | Download | Run |
|----------|----------|-----|
-| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
-| **Linux x64** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-linux-x64-setup.run) | `chmod +x` → run installer |
-| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.0.3/FinceptTerminal-4.0.3-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
+| **Windows x64** | [FinceptTerminal-Windows-x64-setup.exe](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.1.0/FinceptTerminal-4.1.0-windows-x64-setup.exe) | Run installer → launch `FinceptTerminal.exe` |
+| **Linux x64** | [FinceptTerminal-Linux-x64.run](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.1.0/FinceptTerminal-4.1.0-linux-x64-setup.run) | `chmod +x` → run installer |
+| **macOS Apple Silicon** | [FinceptTerminal-macOS-arm64.dmg](https://github.com/Fincept-Corporation/FinceptTerminal/releases/download/v4.1.0/FinceptTerminal-4.1.0-macos-arm64-setup.dmg) | Open DMG → drag to Applications |
<!-- DOWNLOAD-TABLE-END -->
---
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 39d5c2fd2..fdb051d9e 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -33,7 +33,7 @@ if(WIN32 AND CMAKE_HOST_WIN32)
unset(_fincept_sdk_dirs)
endif()
-project(FinceptTerminal VERSION 4.0.3 LANGUAGES C CXX)
+project(FinceptTerminal VERSION 4.1.0 LANGUAGES C CXX)
# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.
if(WIN32)
@@ -1165,6 +1165,7 @@ set(SERVICE_SOURCES
src/services/dbnomics/DBnomicsService.cpp
src/services/gov_data/GovDataService.cpp
src/services/equity/EquityResearchService.cpp
+ src/services/equity/EquitySentimentService.cpp
src/services/equity/MarketSentimentService.cpp
src/services/equity/MarketSentimentSupport.cpp
src/services/ma_analytics/MAAnalyticsService.cpp
@@ -1798,7 +1799,6 @@ set(SCREEN_SOURCES
src/screens/equity_research/EquityFinancialsTab_Populate.cpp
src/screens/equity_research/EquityAnalysisTab.cpp
src/screens/equity_research/EquityTechnicalsTab.cpp
- src/screens/equity_research/EquityTalippTab.cpp
src/screens/equity_research/EquityPeersTab.cpp
src/screens/equity_research/EquityNewsTab.cpp
src/screens/equity_research/EquitySentimentTab.cpp
@@ -2157,7 +2157,6 @@ set_source_files_properties(
src/screens/equity_research/EquityPeersTab.cpp
src/screens/equity_research/EquityResearchScreen.cpp
src/screens/equity_research/EquitySentimentTab.cpp
- src/screens/equity_research/EquityTalippTab.cpp
src/screens/equity_research/EquityTechnicalsTab.cpp
src/screens/excel/ExcelScreen.cpp
src/screens/excel/SpreadsheetWidget.cpp
@@ -3317,18 +3316,71 @@ if(WIN32)
DESTINATION "resources/notebooks" COMPONENT core)
elseif(APPLE)
- # macOS: install the .app bundle
- install(TARGETS FinceptTerminal BUNDLE DESTINATION "." COMPONENT core)
- # Requirements files — deployed beside the .app so PythonSetupManager finds them
- install(FILES
- "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"
- "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"
- DESTINATION "FinceptTerminal.app/Contents/Resources/resources" COMPONENT core)
- # Prebuilt Fincept Notebook library (bundled + seeded into the File Manager).
- install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/resources/notebooks/"
- DESTINATION "FinceptTerminal.app/Contents/Resources/resources/notebooks" COMPONENT core)
+ if(FINCEPT_BUILD_INSTALLER)
+ # ── macOS IFW installer path ─────────────────────────────────────────
+ # Package the bundle that CI has ALREADY run macdeployqt + deep codesign
+ # over (build/FinceptTerminal.app, signed in place). Copy it with
+ # `ditto`, which preserves framework symlinks AND code signatures —
+ # plain install(TARGETS)/file(INSTALL) rewrites them and triggers the
+ # dyld "Code Signature Invalid" SIGKILL from issue #139. The signed
+ # bundle already contains scripts/, resources/, requirements, and
+ # notebooks (staged before signing), so we copy it whole and inject
+ # NOTHING afterwards (any post-sign edit breaks the seal).
+ # CONTRACT: CI must macdeployqt + codesign the bundle BEFORE `cpack -G IFW`.
+ install(CODE "
+ message(STATUS \"[Fincept] Packaging signed .app via ditto for IFW installer\")
+ execute_process(
+ COMMAND /usr/bin/ditto
+ \"$<TARGET_BUNDLE_DIR:FinceptTerminal>\"
+ \"\${CMAKE_INSTALL_PREFIX}/FinceptTerminal.app\"
+ RESULT_VARIABLE _fincept_ditto_rc)
+ if(NOT _fincept_ditto_rc EQUAL 0)
+ message(FATAL_ERROR \"[Fincept] ditto of signed .app failed (rc=\${_fincept_ditto_rc})\")
+ endif()
+ " COMPONENT core)
+ else()
+ # ── Plain `cmake --install` (DMG path / dev) ─────────────────────────
+ # macOS: install the .app bundle
+ install(TARGETS FinceptTerminal BUNDLE DESTINATION "." COMPONENT core)
+ # Requirements files — deployed beside the .app so PythonSetupManager finds them
+ install(FILES
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"
+ DESTINATION "FinceptTerminal.app/Contents/Resources/resources" COMPONENT core)
+ # Prebuilt Fincept Notebook library (bundled + seeded into the File Manager).
+ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/resources/notebooks/"
+ DESTINATION "FinceptTerminal.app/Contents/Resources/resources/notebooks" COMPONENT core)
+ endif()
+
+elseif(FINCEPT_BUILD_INSTALLER AND FINCEPT_IFW_PAYLOAD)
+ # ── Linux IFW installer path (relocatable, self-contained) ───────────────
+ # Ship the tree that linuxdeploy already produced (app binary + bundled Qt
+ # libs + plugins), so the installed app runs from ANY chosen TargetDir.
+ # The binary's rpath ($ORIGIN/../lib, set by linuxdeploy) plus the staged
+ # qt.conf resolve Qt's libraries and plugins relative to the install dir —
+ # no system Qt, no LD_LIBRARY_PATH, no fixed prefix. IFW does not bundle
+ # dependencies itself, so CI sets FINCEPT_IFW_PAYLOAD to the linuxdeploy
+ # AppDir's usr/ directory.
+ install(DIRECTORY "${FINCEPT_IFW_PAYLOAD}/"
+ DESTINATION "."
+ USE_SOURCE_PERMISSIONS
+ COMPONENT core)
+ # qt.conf next to the binary so Qt finds the bundled plugins/libs at any
+ # install location (an IFW install has no AppRun launcher to set env vars).
+ install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/packaging/linux/qt.conf"
+ DESTINATION "bin" COMPONENT core)
+ # NOTE: scripts/, resources/, and requirements live INSIDE the linuxdeploy
+ # AppDir payload already (staged into usr/bin/ by the CI AppImage step), so
+ # they are captured by the install(DIRECTORY) above — no separate scripts
+ # component here (it is Windows-only; see the IFW component config below).
else()
+ if(FINCEPT_BUILD_INSTALLER AND NOT FINCEPT_IFW_PAYLOAD)
+ message(WARNING
+ "FINCEPT_BUILD_INSTALLER is ON for Linux but FINCEPT_IFW_PAYLOAD is unset — "
+ "the IFW .run would ship WITHOUT bundled Qt and fail to launch. "
+ "Set -DFINCEPT_IFW_PAYLOAD=<linuxdeploy-AppDir>/usr, or build the AppImage instead.")
+ endif()
# Linux: FHS-compliant layout. Architecture-neutral — works for x86_64
# and aarch64 (ARM64) without changes; CMake just installs the binary
# produced for the target arch into share/fincept-terminal/. To build for
@@ -3407,6 +3459,16 @@ endif()
option(FINCEPT_BUILD_INSTALLER "Generate QtIFW installer via CPack" OFF)
+# Path to a pre-deployed, self-contained payload that the IFW installer should
+# package on macOS/Linux. QtIFW does NOT bundle dependencies itself — the OS
+# deploy tools must run first (windeployqt on Windows, macdeployqt on macOS,
+# linuxdeploy on Linux). On Linux, set this to the linuxdeploy AppDir's usr/
+# directory so the .run ships bundled Qt and is relocatable. Unused on Windows
+# (windeployqt output is captured directly below) and on macOS (the signed
+# .app is copied via ditto in the install rule above).
+set(FINCEPT_IFW_PAYLOAD "" CACHE PATH
+ "Pre-deployed payload dir for the IFW installer (Linux: linuxdeploy AppDir/usr)")
+
if(FINCEPT_BUILD_INSTALLER)
# ── Windows: capture windeployqt output for the installer ────────────────
@@ -3548,13 +3610,20 @@ if(FINCEPT_BUILD_INSTALLER)
set(CPACK_IFW_PACKAGE_CONTROL_SCRIPT
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/installer/config/controlscript.qs")
- # Target directory defaults per platform
+ # Target directory defaults per platform. These are only DEFAULTS — the
+ # wizard's Target Directory page lets the user pick any path (the page is
+ # shown interactively now that controlscript.qs guards its auto-advance
+ # with isCommandLineInstance()).
if(WIN32)
set(CPACK_IFW_TARGET_DIRECTORY "@ApplicationsDirX64@/FinceptTerminal")
elseif(APPLE)
set(CPACK_IFW_TARGET_DIRECTORY "/Applications/FinceptTerminal")
else()
+ # Default to the user's home so no root is required; the installer only
+ # escalates (and uses AdminTargetDir) if the chosen path isn't writable.
+ # The app is relocatable, so any custom path works either way.
set(CPACK_IFW_TARGET_DIRECTORY "@HomeDir@/FinceptTerminal")
+ set(CPACK_IFW_ADMIN_TARGET_DIRECTORY "/opt/FinceptTerminal")
endif()
# Output file naming — arch-aware so the auto-updater manifest can point
@@ -3612,10 +3681,15 @@ if(FINCEPT_BUILD_INSTALLER)
DESCRIPTION "Core application executable and Qt runtime libraries"
REQUIRED)
- cpack_add_component(scripts
- DISPLAY_NAME "Python Analytics Scripts"
- DESCRIPTION "1300+ Python analytics scripts (equity, derivatives, portfolio, quant)"
- DEPENDS core)
+ # Scripts are a separate, optional component on Windows only. On macOS they
+ # ship inside the signed .app bundle, and on Linux inside the linuxdeploy
+ # AppDir payload — both captured by the `core` component on those platforms.
+ if(WIN32)
+ cpack_add_component(scripts
+ DISPLAY_NAME "Python Analytics Scripts"
+ DESCRIPTION "1300+ Python analytics scripts (equity, derivatives, portfolio, quant)"
+ DEPENDS core)
+ endif()
# ── CPackIFW component configuration ─────────────────────────────────────
cpack_ifw_configure_component(core
@@ -3627,12 +3701,14 @@ if(FINCEPT_BUILD_INSTALLER)
DEFAULT TRUE
FORCED_INSTALLATION)
- cpack_ifw_configure_component(scripts
- NAME "com.fincept.terminal.scripts"
- VERSION "${CMAKE_PROJECT_VERSION}"
- SORTING_PRIORITY 50
- DEFAULT TRUE
- DEPENDS "com.fincept.terminal.core")
+ if(WIN32)
+ cpack_ifw_configure_component(scripts
+ NAME "com.fincept.terminal.scripts"
+ VERSION "${CMAKE_PROJECT_VERSION}"
+ SORTING_PRIORITY 50
+ DEFAULT TRUE
+ DEPENDS "com.fincept.terminal.core")
+ endif()
# ── Linux: AppImage helper target ────────────────────────────────────────
# `linuxdeploy` + `linuxdeploy-plugin-qt` are external tools; we don't
diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
index 97abc1152..5038faf76 100644
--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml
@@ -71,6 +71,11 @@
</provides>
<releases>
+ <release version="4.1.0" date="2026-06-09">
+ <description>
+ <p>Adds an optional NewsAPI.org provider for stock-specific company news in Equity Research, broker-sourced technical indicators, and assorted fixes. Removes the redundant TALIpp tab.</p>
+ </description>
+ </release>
<release version="4.0.3" date="2026-05-25">
<description>
<p>Patch release with bug fixes, new provider integrations, and i18n improvements.</p>
diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml
index bf27deda7..83a6566c6 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.0.3
+ tag: v4.1.0
# Vendored FetchContent dependencies (no network during build)
- type: git
url: https://github.com/QtExcel/QXlsx.git
diff --git a/fincept-qt/packaging/installer/config/controlscript.qs b/fincept-qt/packaging/installer/config/controlscript.qs
index 30c1bc129..ccdcd0e23 100644
--- a/fincept-qt/packaging/installer/config/controlscript.qs
+++ b/fincept-qt/packaging/installer/config/controlscript.qs
@@ -1,13 +1,30 @@
// controlscript.qs — Fincept Terminal QtIFW Controller script.
//
-// Wizard-page automation for headless invocations (e.g.
-// `FinceptMaintenanceTool.exe purge --confirm-command --accept-messages
-// --default-answer`). Without this, IFW would block on each wizard page
-// even when --confirm-command is set, because some pages (Introduction,
-// ReadyForInstallation, Finished) only auto-advance for the *installer*
-// path, not the uninstaller path.
+// Wizard-page automation for HEADLESS / COMMAND-LINE invocations only, e.g.
+// FinceptMaintenanceTool.exe purge --confirm-command --accept-messages --default-answer
+// FinceptTerminal-<v>-setup.exe install --confirm-command --default-answer
+// Without this, IFW would block on each wizard page even when --confirm-command
+// is set, because some pages (Introduction, ReadyForInstallation, Finished)
+// only auto-advance for the *installer* path, not the uninstaller path.
//
-// Reference: https://doc.qt.io/qtinstallerframework/noninteractive.html
+// CRITICAL: This file is embedded as the installer's <ControlScript> via
+// CPACK_IFW_PACKAGE_CONTROL_SCRIPT (CMakeLists.txt). An embedded control
+// script is loaded on EVERY run of the installer and the maintenance tool —
+// interactive GUI runs included. Its page callbacks fire whenever a wizard
+// page is shown, in BOTH interactive and command-line modes.
+//
+// Therefore every callback MUST bail out early in interactive GUI mode, or it
+// auto-clicks "Next" the instant each page appears and the wizard flashes
+// straight through to a silent install at the default location — the user
+// never gets to see the Target Directory page, let alone choose a custom
+// install path. The `if (!installer.isCommandLineInstance()) return;` guard at
+// the top of each callback is exactly what keeps the interactive wizard usable
+// while preserving headless automation (isCommandLineInstance() is true under
+// --confirm-command / CLI, false in the GUI).
+//
+// References:
+// https://doc.qt.io/qtinstallerframework/noninteractive.html
+// https://doc.qt.io/qtinstallerframework/scripting-installer.html (isCommandLineInstance)
function Controller() {
// No-op constructor. Page callbacks below are what actually drive
@@ -15,24 +32,41 @@ function Controller() {
// load this file.
}
-// ── Headless install path (rare in maintenance-tool context, but harmless) ──
+// Returns true only for interactive GUI runs, where the user drives the wizard
+// themselves and we must NOT auto-advance any page. Defends against IFW builds
+// that predate isCommandLineInstance() (4.0+) by treating a missing method as
+// "interactive" — the safe default, since auto-clicking a GUI wizard is the bug
+// we are fixing. Project ships with IFW 4.7/4.8 where the method exists.
+function interactiveGui() {
+ if (typeof installer.isCommandLineInstance !== "function")
+ return true;
+ return !installer.isCommandLineInstance();
+}
+
+// ── Headless install / maintenance-tool path ─────────────────────────────────
+// In interactive GUI mode each of these returns immediately so the user sees
+// and controls every page (Target Directory, components, license, etc.).
Controller.prototype.IntroductionPageCallback = function() {
+ if (interactiveGui()) return;
if (gui && gui.clickButton)
gui.clickButton(buttons.NextButton);
};
Controller.prototype.TargetDirectoryPageCallback = function() {
+ if (interactiveGui()) return; // GUI: let the user choose the install path
if (gui && gui.clickButton)
gui.clickButton(buttons.NextButton);
};
Controller.prototype.ComponentSelectionPageCallback = function() {
+ if (interactiveGui()) return;
if (gui && gui.clickButton)
gui.clickButton(buttons.NextButton);
};
Controller.prototype.LicenseAgreementPageCallback = function() {
+ if (interactiveGui()) return;
// Per Qt IFW docs example: explicitly check the accept radio before
// clicking Next, otherwise the Next button stays disabled and silent
// installs hang. Guard each access — `pageWidgetByObjectName` returns
@@ -48,16 +82,19 @@ Controller.prototype.LicenseAgreementPageCallback = function() {
};
Controller.prototype.ReadyForInstallationPageCallback = function() {
+ if (interactiveGui()) return;
if (gui && gui.clickButton)
gui.clickButton(buttons.CommitButton);
};
Controller.prototype.PerformInstallationPageCallback = function() {
+ if (interactiveGui()) return;
if (gui && gui.clickButton)
gui.clickButton(buttons.CommitButton);
};
Controller.prototype.FinishedPageCallback = function() {
+ if (interactiveGui()) return;
if (gui && gui.clickButton)
gui.clickButton(buttons.FinishButton);
};
diff --git a/fincept-qt/packaging/linux/AppImageBuilder.yml b/fincept-qt/packaging/linux/AppImageBuilder.yml
index 8a90ab931..f6245495a 100644
--- a/fincept-qt/packaging/linux/AppImageBuilder.yml
+++ b/fincept-qt/packaging/linux/AppImageBuilder.yml
@@ -16,7 +16,7 @@ AppDir:
id: com.fincept.terminal
name: Fincept Terminal
icon: fincept-terminal
- version: !ENV ${FINCEPT_VERSION:-4.0.3}
+ version: !ENV ${FINCEPT_VERSION:-4.1.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.0.3}-x86_64.AppImage
+ file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.1.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 43b9838f6..75786db98 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.1.0" date="2026-06-09">
+ <description>
+ <p>Version 4.1.0 — Optional NewsAPI.org news provider, broker-sourced technicals, and fixes.</p>
+ </description>
+ </release>
<release version="4.0.2" date="2026-04-14">
<description>
<p>Version 4.0.2 — Patch release.</p>
diff --git a/fincept-qt/packaging/linux/qt.conf b/fincept-qt/packaging/linux/qt.conf
new file mode 100644
index 000000000..c00b2f7ed
--- /dev/null
+++ b/fincept-qt/packaging/linux/qt.conf
@@ -0,0 +1,16 @@
+# qt.conf — relocatable Qt path resolution for the Linux IFW (.run) install.
+#
+# Staged into <install>/bin/ beside the FinceptTerminal binary. Qt reads it
+# relative to the executable's directory, so Prefix=.. points at the install
+# root and Qt finds the bundled libs/plugins that linuxdeploy placed under
+# lib/ and plugins/ — at ANY chosen install location, with no AppRun launcher
+# and no LD_LIBRARY_PATH/QT_PLUGIN_PATH env vars.
+#
+# Layout produced by linuxdeploy (AppDir/usr → install root):
+# <install>/bin/FinceptTerminal <install>/lib/*.so <install>/plugins/<group>/
+[Paths]
+Prefix = ..
+Libraries = lib
+Plugins = plugins
+Imports = qml
+Qml2Imports = qml
diff --git a/fincept-qt/resources/requirements-numpy2.txt b/fincept-qt/resources/requirements-numpy2.txt
index 3a8e070d6..00f9144aa 100644
--- a/fincept-qt/resources/requirements-numpy2.txt
+++ b/fincept-qt/resources/requirements-numpy2.txt
@@ -24,6 +24,10 @@ databento==0.66.0
databento-dbn==0.44.0
feedparser==6.0.12
gnews==0.4.2
+# Offline, finance-tuned headline sentiment for the Equity Research → Sentiment
+# tab (news_nlp.py). Pure-python, no model download; news_nlp falls back to a
+# keyword scorer if this is absent.
+vaderSentiment==3.3.2
geopy>=2.4.0
akshare>=1.14.0
aiohappyeyeballs==2.6.1
@@ -98,7 +102,6 @@ river>=0.21.0
# Technical analysis
ta==0.11.0
-talipp==2.7.0
# Portfolio optimization
finquant-enhanced
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/README.md b/fincept-qt/scripts/Analytics/talipp_wrapper/README.md
deleted file mode 100644
index 833c3aa1b..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/README.md
+++ /dev/null
@@ -1,210 +0,0 @@
-TALIpp Wrapper - Incremental Technical Indicators
-
-Installation: talipp==2.7.0 (already added to requirements.txt)
-
-TALIpp is a Python library for technical analysis with O(1) incremental computation.
-
-MODULES (61 FUNCTIONS)
--------
-
-1. trend.py (10 functions)
- Moving averages and trend indicators
-
- Functions:
- - calculate_sma: Simple Moving Average
- - calculate_ema: Exponential Moving Average
- - calculate_wma: Weighted Moving Average
- - calculate_dema: Double Exponential MA
- - calculate_tema: Triple Exponential MA
- - calculate_hma: Hull Moving Average
- - calculate_kama: Kaufman Adaptive MA
- - calculate_alma: Arnaud Legoux MA
- - calculate_t3: Tillson T3
- - calculate_zlema: Zero Lag EMA
-
-2. momentum.py (8 functions)
- Momentum and oscillator indicators
-
- Functions:
- - calculate_rsi: Relative Strength Index
- - calculate_macd: MACD (line, signal, histogram)
- - calculate_stoch: Stochastic Oscillator (K, D)
- - calculate_stoch_rsi: Stochastic RSI
- - calculate_cci: Commodity Channel Index
- - calculate_roc: Rate of Change
- - calculate_tsi: True Strength Index
- - calculate_williams: Williams %R
-
-3. volatility.py (6 functions)
- Volatility and channel indicators
-
- Functions:
- - calculate_atr: Average True Range
- - calculate_bb: Bollinger Bands (upper, middle, lower)
- - calculate_keltner: Keltner Channels
- - calculate_donchian: Donchian Channels
- - calculate_chandelier_stop: Chandelier Stop
- - calculate_natr: Normalized ATR
-
-4. volume.py (6 functions)
- Volume-based indicators
-
- Functions:
- - calculate_obv: On-Balance Volume
- - calculate_vwap: Volume Weighted Average Price
- - calculate_vwma: Volume Weighted MA
- - calculate_mfi: Money Flow Index
- - calculate_chaikin_osc: Chaikin Oscillator
- - calculate_force_index: Force Index
-
-5. trend_other.py (5 functions)
- Advanced trend indicators
-
- Functions:
- - calculate_adx: Average Directional Index
- - calculate_aroon: Aroon Up/Down
- - calculate_ichimoku: Ichimoku Cloud (tenkan, kijun, senkou)
- - calculate_parabolic_sar: Parabolic SAR
- - calculate_supertrend: SuperTrend (value, trend)
-
-6. specialized.py (26 functions)
- Specialized and advanced indicators
-
- Functions:
- - calculate_ao: Awesome Oscillator
- - calculate_accu_dist: Accumulation/Distribution
- - calculate_bop: Balance of Power
- - calculate_chop: Choppiness Index
- - calculate_coppock_curve: Coppock Curve
- - calculate_dpo: Detrended Price Oscillator
- - calculate_emv: Ease of Movement
- - calculate_fibonacci_retracement: Fibonacci Retracement
- - calculate_ibs: Internal Bar Strength
- - calculate_kst: Know Sure Thing
- - calculate_kvo: Klinger Volume Oscillator
- - calculate_mass_index: Mass Index
- - calculate_mcginley_dynamic: McGinley Dynamic
- - calculate_mean_dev: Mean Deviation
- - calculate_pivots_hl: Pivot Points HL
- - calculate_rogers_satchell: Rogers-Satchell Volatility
- - calculate_sfx: SFX
- - calculate_smma: Smoothed Moving Average
- - calculate_sobv: Smoothed OBV
- - calculate_stc: Schaff Trend Cycle
- - calculate_std_dev: Standard Deviation
- - calculate_trix: TRIX
- - calculate_ttm: TTM Squeeze
- - calculate_uo: Ultimate Oscillator
- - calculate_vtx: Vortex Indicator
- - calculate_zigzag: ZigZag
-
-USAGE EXAMPLES
---------------
-
-Simple Moving Average:
- from talipp_wrapper import calculate_sma
- prices = [100, 102, 101, 105, 107, 106]
- result = calculate_sma(prices, period=5)
- # Returns: {values: [...], period: 5, last: 104.2}
-
-RSI:
- from talipp_wrapper import calculate_rsi
- prices = [100, 102, 101, 105, 107, ...]
- result = calculate_rsi(prices, period=14)
- # Returns: {values: [...], period: 14, last: 65.3}
-
-Bollinger Bands:
- from talipp_wrapper import calculate_bb
- prices = [100, 102, 101, 105, ...]
- result = calculate_bb(prices, period=20, std_dev=2.0)
- # Returns: {upper: [...], middle: [...], lower: [...], last_upper: 110.5, ...}
-
-MACD:
- from talipp_wrapper import calculate_macd
- prices = [100, 102, 101, ...]
- result = calculate_macd(prices, fast_period=12, slow_period=26, signal_period=9)
- # Returns: {macd: [...], signal: [...], histogram: [...], last_macd: 2.5, ...}
-
-OHLCV Indicators:
- from talipp_wrapper import calculate_atr
- ohlcv_data = [
- {'open': 100, 'high': 102, 'low': 99, 'close': 101, 'volume': 1000},
- ...
- ]
- result = calculate_atr(ohlcv_data, period=14)
- # Returns: {values: [...], period: 14, last: 3.8}
-
-TESTING
--------
-
-All modules tested:
- python trend.py # PASSED (3/3)
- python momentum.py # PASSED (3/3)
- python volatility.py # PASSED (3/3)
- python volume.py # PASSED (3/3)
- python trend_other.py # PASSED (3/3)
- python specialized.py # PASSED (3/3)
-
-TALIPP INFO
------------
-
-Source: https://github.com/nardew/talipp
-Version: 2.7.0
-Stars: 511
-License: MIT
-Python: 3.8+
-
-Key Features:
-- 60+ technical indicators
-- O(1) incremental computation
-- Append, update, delete operations
-- Real-time optimized
-- No numpy/pandas required for core
-- Supports both price and OHLCV data
-
-Performance Advantage:
-- Batch: Similar to TA-Lib
-- Incremental: 34x faster than recalculation
-
-Indicator Categories:
-- Trend: SMA, EMA, DEMA, TEMA, HMA, KAMA, etc.
-- Momentum: RSI, MACD, Stochastic, CCI, etc.
-- Volatility: ATR, BB, Keltner, Donchian, etc.
-- Volume: OBV, VWAP, VWMA, MFI, etc.
-- Advanced: ADX, Aroon, Ichimoku, SuperTrend, etc.
-
-WRAPPER COVERAGE
-----------------
-
-Total TALIpp Indicators: 60+
-Wrapped Functions: 61
-Coverage: 100% (complete indicator library)
-
-Wrapped Indicators by Type:
-- Trend: 10 indicators (SMA, EMA, WMA, DEMA, TEMA, HMA, KAMA, ALMA, T3, ZLEMA)
-- Momentum: 8 indicators (RSI, MACD, Stoch, StochRSI, CCI, ROC, TSI, Williams)
-- Volatility: 6 indicators (ATR, BB, Keltner, Donchian, Chandelier, NATR)
-- Volume: 6 indicators (OBV, VWAP, VWMA, MFI, ChaikinOsc, ForceIndex)
-- Trend/Other: 5 indicators (ADX, Aroon, Ichimoku, ParabolicSAR, SuperTrend)
-- Specialized: 26 indicators (AO, AccuDist, BOP, CHOP, Coppock, DPO, EMV, Fibonacci, IBS, KST, KVO, MassIndex, McGinley, MeanDev, PivotsHL, RogersSatchell, SFX, SMMA, SOBV, STC, StdDev, TRIX, TTM, UO, VTX, ZigZag)
-
-Status: Complete coverage of all TALIpp indicators for professional trading strategies
-
-NOTES
------
-
-1. Incremental: All indicators support .add(), .update(), .remove()
-2. Returns: All functions return dicts with values array and last value
-3. OHLCV: Some indicators require full OHLCV data (ATR, ADX, etc.)
-4. None Values: Early periods may return None until indicator is ready
-5. Performance: Use for real-time/streaming applications
-
-INTEGRATION STATUS
-------------------
-
-[COMPLETE] Library installed and added to requirements.txt
-[COMPLETE] 60+ indicators scanned
-[COMPLETE] 6 wrapper modules created
-[COMPLETE] 61 wrapper functions implemented
-[COMPLETE] All modules tested successfully
-[COMPLETE] 100% coverage of all indicators
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.py b/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.py
deleted file mode 100644
index 06e81a63e..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/__init__.py
+++ /dev/null
@@ -1,107 +0,0 @@
-
-__all__ = [
- 'calculate_sma', 'calculate_ema', 'calculate_wma', 'calculate_dema', 'calculate_tema',
- 'calculate_hma', 'calculate_kama', 'calculate_alma', 'calculate_t3', 'calculate_zlema',
- 'calculate_rsi', 'calculate_macd', 'calculate_stoch', 'calculate_stoch_rsi',
- 'calculate_cci', 'calculate_roc', 'calculate_tsi', 'calculate_williams',
- 'calculate_atr', 'calculate_bb', 'calculate_keltner', 'calculate_donchian',
- 'calculate_chandelier_stop', 'calculate_natr',
- 'calculate_obv', 'calculate_vwap', 'calculate_vwma', 'calculate_mfi',
- 'calculate_chaikin_osc', 'calculate_force_index',
- 'calculate_adx', 'calculate_aroon', 'calculate_ichimoku', 'calculate_parabolic_sar',
- 'calculate_supertrend',
- 'calculate_ao', 'calculate_accu_dist', 'calculate_bop', 'calculate_chop',
- 'calculate_coppock_curve', 'calculate_dpo', 'calculate_emv', 'calculate_fibonacci_retracement',
- 'calculate_ibs', 'calculate_kst', 'calculate_kvo', 'calculate_mass_index',
- 'calculate_mcginley_dynamic', 'calculate_mean_dev', 'calculate_pivots_hl',
- 'calculate_rogers_satchell', 'calculate_sfx', 'calculate_smma', 'calculate_sobv',
- 'calculate_stc', 'calculate_std_dev', 'calculate_trix', 'calculate_ttm',
- 'calculate_uo', 'calculate_vtx', 'calculate_zigzag'
-]
-
-
-# ── Lazy attribute resolution (PEP 562) ─────────────────────────────────────
-# Submodules below have an `if __name__ == "__main__":` block and may be
-# invoked via `python -m`. Eagerly importing them here would put each in
-# sys.modules before Python re-executes them as __main__, triggering a
-# RuntimeWarning ("found in sys.modules ... prior to execution"). The lazy
-# loader keeps the public API intact while deferring import to first access.
-_LAZY_ATTRS: dict[str, tuple[str, str]] = {
- "calculate_sma": ("trend", "calculate_sma"),
- "calculate_ema": ("trend", "calculate_ema"),
- "calculate_wma": ("trend", "calculate_wma"),
- "calculate_dema": ("trend", "calculate_dema"),
- "calculate_tema": ("trend", "calculate_tema"),
- "calculate_hma": ("trend", "calculate_hma"),
- "calculate_kama": ("trend", "calculate_kama"),
- "calculate_alma": ("trend", "calculate_alma"),
- "calculate_t3": ("trend", "calculate_t3"),
- "calculate_zlema": ("trend", "calculate_zlema"),
- "calculate_rsi": ("momentum", "calculate_rsi"),
- "calculate_macd": ("momentum", "calculate_macd"),
- "calculate_stoch": ("momentum", "calculate_stoch"),
- "calculate_stoch_rsi": ("momentum", "calculate_stoch_rsi"),
- "calculate_cci": ("momentum", "calculate_cci"),
- "calculate_roc": ("momentum", "calculate_roc"),
- "calculate_tsi": ("momentum", "calculate_tsi"),
- "calculate_williams": ("momentum", "calculate_williams"),
- "calculate_atr": ("volatility", "calculate_atr"),
- "calculate_bb": ("volatility", "calculate_bb"),
- "calculate_keltner": ("volatility", "calculate_keltner"),
- "calculate_donchian": ("volatility", "calculate_donchian"),
- "calculate_chandelier_stop": ("volatility", "calculate_chandelier_stop"),
- "calculate_natr": ("volatility", "calculate_natr"),
- "calculate_obv": ("volume", "calculate_obv"),
- "calculate_vwap": ("volume", "calculate_vwap"),
- "calculate_vwma": ("volume", "calculate_vwma"),
- "calculate_mfi": ("volume", "calculate_mfi"),
- "calculate_chaikin_osc": ("volume", "calculate_chaikin_osc"),
- "calculate_force_index": ("volume", "calculate_force_index"),
- "calculate_adx": ("trend_other", "calculate_adx"),
- "calculate_aroon": ("trend_other", "calculate_aroon"),
- "calculate_ichimoku": ("trend_other", "calculate_ichimoku"),
- "calculate_parabolic_sar": ("trend_other", "calculate_parabolic_sar"),
- "calculate_supertrend": ("trend_other", "calculate_supertrend"),
- "calculate_ao": ("specialized", "calculate_ao"),
- "calculate_accu_dist": ("specialized", "calculate_accu_dist"),
- "calculate_bop": ("specialized", "calculate_bop"),
- "calculate_chop": ("specialized", "calculate_chop"),
- "calculate_coppock_curve": ("specialized", "calculate_coppock_curve"),
- "calculate_dpo": ("specialized", "calculate_dpo"),
- "calculate_emv": ("specialized", "calculate_emv"),
- "calculate_fibonacci_retracement": ("specialized", "calculate_fibonacci_retracement"),
- "calculate_ibs": ("specialized", "calculate_ibs"),
- "calculate_kst": ("specialized", "calculate_kst"),
- "calculate_kvo": ("specialized", "calculate_kvo"),
- "calculate_mass_index": ("specialized", "calculate_mass_index"),
- "calculate_mcginley_dynamic": ("specialized", "calculate_mcginley_dynamic"),
- "calculate_mean_dev": ("specialized", "calculate_mean_dev"),
- "calculate_pivots_hl": ("specialized", "calculate_pivots_hl"),
- "calculate_rogers_satchell": ("specialized", "calculate_rogers_satchell"),
- "calculate_sfx": ("specialized", "calculate_sfx"),
- "calculate_smma": ("specialized", "calculate_smma"),
- "calculate_sobv": ("specialized", "calculate_sobv"),
- "calculate_stc": ("specialized", "calculate_stc"),
- "calculate_std_dev": ("specialized", "calculate_std_dev"),
- "calculate_trix": ("specialized", "calculate_trix"),
- "calculate_ttm": ("specialized", "calculate_ttm"),
- "calculate_uo": ("specialized", "calculate_uo"),
- "calculate_vtx": ("specialized", "calculate_vtx"),
- "calculate_zigzag": ("specialized", "calculate_zigzag"),
-}
-
-
-def __getattr__(name: str): # PEP 562
- target = _LAZY_ATTRS.get(name)
- if target is None:
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
- submodule, original_name = target
- import importlib
- mod = importlib.import_module(f".{submodule}", __name__)
- value = getattr(mod, original_name)
- globals()[name] = value # cache for subsequent access
- return value
-
-
-def __dir__() -> list[str]:
- return sorted(set(globals()) | set(_LAZY_ATTRS))
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/momentum.py b/fincept-qt/scripts/Analytics/talipp_wrapper/momentum.py
deleted file mode 100644
index a7602164c..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/momentum.py
+++ /dev/null
@@ -1,182 +0,0 @@
-from typing import List, Dict
-from talipp.indicators import RSI, MACD, Stoch, StochRSI, CCI, ROC, TSI
-from talipp.ohlcv import OHLCV
-
-def calculate_rsi(prices: List[float], period: int = 14) -> Dict:
- rsi = RSI(period)
- for price in prices:
- rsi.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(rsi)],
- 'period': period,
- 'last': float(rsi[-1]) if len(rsi) > 0 and rsi[-1] is not None else None
- }
-
-def calculate_macd(prices: List[float], fast_period: int = 12, slow_period: int = 26, signal_period: int = 9) -> Dict:
- macd = MACD(fast_period, slow_period, signal_period)
- for price in prices:
- macd.add(price)
-
- macd_values = []
- signal_values = []
- histogram_values = []
-
- for val in macd:
- if val is not None:
- macd_values.append(float(val.value))
- signal_values.append(float(val.signal))
- histogram_values.append(float(val.histogram))
- else:
- macd_values.append(None)
- signal_values.append(None)
- histogram_values.append(None)
-
- last_val = macd[-1] if len(macd) > 0 and macd[-1] is not None else None
-
- return {
- 'macd': macd_values,
- 'signal': signal_values,
- 'histogram': histogram_values,
- 'last_macd': float(last_val.value) if last_val else None,
- 'last_signal': float(last_val.signal) if last_val else None,
- 'last_histogram': float(last_val.histogram) if last_val else None
- }
-
-def calculate_stoch(ohlcv_data: List[Dict], period: int = 14, smoothing_period: int = 3) -> Dict:
- stoch = Stoch(period, smoothing_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- stoch.add(ohlcv)
-
- k_values = []
- d_values = []
-
- for val in stoch:
- if val is not None:
- k_values.append(float(val.k))
- d_values.append(float(val.d))
- else:
- k_values.append(None)
- d_values.append(None)
-
- last_val = stoch[-1] if len(stoch) > 0 and stoch[-1] is not None else None
-
- return {
- 'k': k_values,
- 'd': d_values,
- 'last_k': float(last_val.k) if last_val else None,
- 'last_d': float(last_val.d) if last_val else None
- }
-
-def calculate_stoch_rsi(prices: List[float], period: int = 14, stoch_period: int = 14, k_smoothing: int = 3, d_smoothing: int = 3) -> Dict:
- stoch_rsi = StochRSI(period, stoch_period, k_smoothing, d_smoothing)
- for price in prices:
- stoch_rsi.add(price)
-
- k_values = []
- d_values = []
-
- for val in stoch_rsi:
- if val is not None:
- k_values.append(float(val.k))
- d_values.append(float(val.d))
- else:
- k_values.append(None)
- d_values.append(None)
-
- last_val = stoch_rsi[-1] if len(stoch_rsi) > 0 and stoch_rsi[-1] is not None else None
-
- return {
- 'k': k_values,
- 'd': d_values,
- 'last_k': float(last_val.k) if last_val else None,
- 'last_d': float(last_val.d) if last_val else None
- }
-
-def calculate_cci(ohlcv_data: List[Dict], period: int = 20) -> Dict:
- cci = CCI(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- cci.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(cci)],
- 'period': period,
- 'last': float(cci[-1]) if len(cci) > 0 and cci[-1] is not None else None
- }
-
-def calculate_roc(prices: List[float], period: int = 12) -> Dict:
- roc = ROC(period)
- for price in prices:
- roc.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(roc)],
- 'period': period,
- 'last': float(roc[-1]) if len(roc) > 0 and roc[-1] is not None else None
- }
-
-def calculate_tsi(prices: List[float], long_period: int = 25, short_period: int = 13, signal_period: int = 13) -> Dict:
- tsi = TSI(long_period, short_period, signal_period)
- for price in prices:
- tsi.add(price)
-
- tsi_values = []
- signal_values = []
-
- for val in tsi:
- if val is not None:
- tsi_values.append(float(val.value))
- signal_values.append(float(val.signal))
- else:
- tsi_values.append(None)
- signal_values.append(None)
-
- last_val = tsi[-1] if len(tsi) > 0 and tsi[-1] is not None else None
-
- return {
- 'tsi': tsi_values,
- 'signal': signal_values,
- 'last_tsi': float(last_val.value) if last_val else None,
- 'last_signal': float(last_val.signal) if last_val else None
- }
-
-def calculate_williams(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- from talipp.indicators import Williams
- williams = Williams(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- williams.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(williams)],
- 'period': period,
- 'last': float(williams[-1]) if len(williams) > 0 and williams[-1] is not None else None
- }
-
-def main():
- print("Testing TALIpp Momentum Indicators")
-
- prices = [100, 102, 101, 105, 107, 106, 108, 110, 109, 111, 113, 112, 115, 114, 116, 118, 117, 120, 119, 121]
-
- print("\n1. Testing RSI...")
- result = calculate_rsi(prices, period=14)
- print("Last RSI:", result['last'])
- assert result['last'] is not None
- print("Test 1: PASSED")
-
- print("\n2. Testing MACD...")
- result = calculate_macd(prices)
- print("Last MACD:", result['last_macd'])
- print("Test 2: PASSED")
-
- print("\n3. Testing ROC...")
- result = calculate_roc(prices, period=10)
- print("Last ROC:", result['last'])
- print("Test 3: PASSED")
-
- print("\nAll tests: PASSED")
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/specialized.py b/fincept-qt/scripts/Analytics/talipp_wrapper/specialized.py
deleted file mode 100644
index 2a7c85ae3..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/specialized.py
+++ /dev/null
@@ -1,404 +0,0 @@
-from typing import List, Dict
-from talipp.indicators import (
- AO, AccuDist, BOP, CHOP, CoppockCurve, DPO, EMV, FibonacciRetracement,
- IBS, KST, KVO, MassIndex, McGinleyDynamic, MeanDev, PivotsHL,
- RogersSatchell, SFX, SMMA, SOBV, STC, StdDev, TRIX, TTM, UO, VTX, ZigZag
-)
-from talipp.ohlcv import OHLCV
-
-def calculate_ao(ohlcv_data: List[Dict], fast_period: int = 5, slow_period: int = 34) -> Dict:
- ao = AO(fast_period, slow_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- ao.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(ao)],
- 'last': float(ao[-1]) if len(ao) > 0 and ao[-1] is not None else None
- }
-
-def calculate_accu_dist(ohlcv_data: List[Dict]) -> Dict:
- ad = AccuDist()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- ad.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(ad)],
- 'last': float(ad[-1]) if len(ad) > 0 and ad[-1] is not None else None
- }
-
-def calculate_bop(ohlcv_data: List[Dict]) -> Dict:
- bop = BOP()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- bop.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(bop)],
- 'last': float(bop[-1]) if len(bop) > 0 and bop[-1] is not None else None
- }
-
-def calculate_chop(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- chop = CHOP(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- chop.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(chop)],
- 'period': period,
- 'last': float(chop[-1]) if len(chop) > 0 and chop[-1] is not None else None
- }
-
-def calculate_coppock_curve(prices: List[float], roc1_period: int = 14, roc2_period: int = 11, wma_period: int = 10) -> Dict:
- cc = CoppockCurve(roc1_period, roc2_period, wma_period)
- for price in prices:
- cc.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(cc)],
- 'last': float(cc[-1]) if len(cc) > 0 and cc[-1] is not None else None
- }
-
-def calculate_dpo(prices: List[float], period: int = 20) -> Dict:
- dpo = DPO(period)
- for price in prices:
- dpo.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(dpo)],
- 'period': period,
- 'last': float(dpo[-1]) if len(dpo) > 0 and dpo[-1] is not None else None
- }
-
-def calculate_emv(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- emv = EMV(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- emv.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(emv)],
- 'period': period,
- 'last': float(emv[-1]) if len(emv) > 0 and emv[-1] is not None else None
- }
-
-def calculate_fibonacci_retracement(ohlcv_data: List[Dict]) -> Dict:
- fib = FibonacciRetracement()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- fib.add(ohlcv)
-
- values = []
- for val in fib:
- if val is not None:
- values.append({
- 'level_0': float(val.level_0),
- 'level_236': float(val.level_236),
- 'level_382': float(val.level_382),
- 'level_500': float(val.level_500),
- 'level_618': float(val.level_618),
- 'level_1000': float(val.level_1000)
- })
- else:
- values.append(None)
-
- last_val = fib[-1] if len(fib) > 0 and fib[-1] is not None else None
- return {
- 'values': values,
- 'last': {
- 'level_0': float(last_val.level_0),
- 'level_236': float(last_val.level_236),
- 'level_382': float(last_val.level_382),
- 'level_500': float(last_val.level_500),
- 'level_618': float(last_val.level_618),
- 'level_1000': float(last_val.level_1000)
- } if last_val else None
- }
-
-def calculate_ibs(ohlcv_data: List[Dict]) -> Dict:
- ibs = IBS()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- ibs.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(ibs)],
- 'last': float(ibs[-1]) if len(ibs) > 0 and ibs[-1] is not None else None
- }
-
-def calculate_kst(prices: List[float]) -> Dict:
- kst = KST()
- for price in prices:
- kst.add(price)
-
- values = []
- signals = []
- for val in kst:
- if val is not None:
- values.append(float(val.value))
- signals.append(float(val.signal))
- else:
- values.append(None)
- signals.append(None)
-
- last_val = kst[-1] if len(kst) > 0 and kst[-1] is not None else None
- return {
- 'kst': values,
- 'signal': signals,
- 'last_kst': float(last_val.value) if last_val else None,
- 'last_signal': float(last_val.signal) if last_val else None
- }
-
-def calculate_kvo(ohlcv_data: List[Dict], fast_period: int = 34, slow_period: int = 55, signal_period: int = 13) -> Dict:
- kvo = KVO(fast_period, slow_period, signal_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- kvo.add(ohlcv)
-
- values = []
- signals = []
- for val in kvo:
- if val is not None:
- values.append(float(val.value))
- signals.append(float(val.signal))
- else:
- values.append(None)
- signals.append(None)
-
- last_val = kvo[-1] if len(kvo) > 0 and kvo[-1] is not None else None
- return {
- 'kvo': values,
- 'signal': signals,
- 'last_kvo': float(last_val.value) if last_val else None,
- 'last_signal': float(last_val.signal) if last_val else None
- }
-
-def calculate_mass_index(ohlcv_data: List[Dict], period: int = 25, ema_period: int = 9) -> Dict:
- mi = MassIndex(period, ema_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- mi.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(mi)],
- 'period': period,
- 'last': float(mi[-1]) if len(mi) > 0 and mi[-1] is not None else None
- }
-
-def calculate_mcginley_dynamic(prices: List[float], period: int = 14, k: float = 0.6) -> Dict:
- md = McGinleyDynamic(period, k)
- for price in prices:
- md.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(md)],
- 'period': period,
- 'last': float(md[-1]) if len(md) > 0 and md[-1] is not None else None
- }
-
-def calculate_mean_dev(prices: List[float], period: int = 20) -> Dict:
- md = MeanDev(period)
- for price in prices:
- md.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(md)],
- 'period': period,
- 'last': float(md[-1]) if len(md) > 0 and md[-1] is not None else None
- }
-
-def calculate_pivots_hl(ohlcv_data: List[Dict], left_bars: int = 5, right_bars: int = 5) -> Dict:
- pivots = PivotsHL(left_bars, right_bars)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- pivots.add(ohlcv)
-
- values = []
- for val in pivots:
- if val is not None:
- values.append({
- 'high': float(val.high) if val.high is not None else None,
- 'low': float(val.low) if val.low is not None else None
- })
- else:
- values.append(None)
-
- last_val = pivots[-1] if len(pivots) > 0 and pivots[-1] is not None else None
- return {
- 'values': values,
- 'last': {
- 'high': float(last_val.high) if last_val and last_val.high is not None else None,
- 'low': float(last_val.low) if last_val and last_val.low is not None else None
- } if last_val else None
- }
-
-def calculate_rogers_satchell(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- rs = RogersSatchell(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- rs.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(rs)],
- 'period': period,
- 'last': float(rs[-1]) if len(rs) > 0 and rs[-1] is not None else None
- }
-
-def calculate_sfx(ohlcv_data: List[Dict], period: int = 5, atr_period: int = 10, atr_mult: float = 4.0) -> Dict:
- sfx = SFX(period, atr_period, atr_mult)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- sfx.add(ohlcv)
-
- values = []
- for val in sfx:
- if val is not None:
- values.append({'value': float(val.value), 'trend': int(val.trend)})
- else:
- values.append(None)
-
- last_val = sfx[-1] if len(sfx) > 0 and sfx[-1] is not None else None
- return {
- 'values': values,
- 'last': {'value': float(last_val.value), 'trend': int(last_val.trend)} if last_val else None
- }
-
-def calculate_smma(prices: List[float], period: int = 20) -> Dict:
- smma = SMMA(period)
- for price in prices:
- smma.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(smma)],
- 'period': period,
- 'last': float(smma[-1]) if len(smma) > 0 and smma[-1] is not None else None
- }
-
-def calculate_sobv(ohlcv_data: List[Dict], period: int = 10) -> Dict:
- sobv = SOBV(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- sobv.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(sobv)],
- 'period': period,
- 'last': float(sobv[-1]) if len(sobv) > 0 and sobv[-1] is not None else None
- }
-
-def calculate_stc(prices: List[float], fast_period: int = 23, slow_period: int = 50, cycle: int = 10) -> Dict:
- stc = STC(fast_period, slow_period, cycle)
- for price in prices:
- stc.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(stc)],
- 'last': float(stc[-1]) if len(stc) > 0 and stc[-1] is not None else None
- }
-
-def calculate_std_dev(prices: List[float], period: int = 20) -> Dict:
- std = StdDev(period)
- for price in prices:
- std.add(price)
- return {
- 'values': [float(v) if v is not None else None for v in list(std)],
- 'period': period,
- 'last': float(std[-1]) if len(std) > 0 and std[-1] is not None else None
- }
-
-def calculate_trix(prices: List[float], period: int = 15, signal_period: int = 9) -> Dict:
- trix = TRIX(period, signal_period)
- for price in prices:
- trix.add(price)
-
- values = []
- signals = []
- for val in trix:
- if val is not None:
- values.append(float(val.value))
- signals.append(float(val.signal))
- else:
- values.append(None)
- signals.append(None)
-
- last_val = trix[-1] if len(trix) > 0 and trix[-1] is not None else None
- return {
- 'trix': values,
- 'signal': signals,
- 'last_trix': float(last_val.value) if last_val else None,
- 'last_signal': float(last_val.signal) if last_val else None
- }
-
-def calculate_ttm(ohlcv_data: List[Dict], bb_period: int = 20, kc_period: int = 20) -> Dict:
- ttm = TTM(bb_period, kc_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- ttm.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(ttm)],
- 'last': float(ttm[-1]) if len(ttm) > 0 and ttm[-1] is not None else None
- }
-
-def calculate_uo(ohlcv_data: List[Dict], short_period: int = 7, medium_period: int = 14, long_period: int = 28) -> Dict:
- uo = UO(short_period, medium_period, long_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- uo.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(uo)],
- 'last': float(uo[-1]) if len(uo) > 0 and uo[-1] is not None else None
- }
-
-def calculate_vtx(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- vtx = VTX(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- vtx.add(ohlcv)
-
- plus = []
- minus = []
- for val in vtx:
- if val is not None:
- plus.append(float(val.plus))
- minus.append(float(val.minus))
- else:
- plus.append(None)
- minus.append(None)
-
- last_val = vtx[-1] if len(vtx) > 0 and vtx[-1] is not None else None
- return {
- 'plus': plus,
- 'minus': minus,
- 'last_plus': float(last_val.plus) if last_val else None,
- 'last_minus': float(last_val.minus) if last_val else None
- }
-
-def calculate_zigzag(ohlcv_data: List[Dict], change: float = 5.0) -> Dict:
- zz = ZigZag(change)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- zz.add(ohlcv)
- return {
- 'values': [float(v) if v is not None else None for v in list(zz)],
- 'change': change,
- 'last': float(zz[-1]) if len(zz) > 0 and zz[-1] is not None else None
- }
-
-def main():
- print("Testing TALIpp Specialized Indicators")
-
- prices = [100, 102, 101, 105, 107, 106, 108, 110, 109, 111, 113, 112, 115, 114, 116, 118, 117, 120, 119, 121] * 3
- ohlcv_data = [
- {'open': p-1, 'high': p+2, 'low': p-2, 'close': p, 'volume': 1000+i*10}
- for i, p in enumerate(prices)
- ]
-
- print("\n1. Testing SMMA...")
- result = calculate_smma(prices, period=10)
- print("Last SMMA:", result['last'])
- assert result['last'] is not None
- print("Test 1: PASSED")
-
- print("\n2. Testing StdDev...")
- result = calculate_std_dev(prices, period=10)
- print("Last StdDev:", result['last'])
- assert result['last'] is not None
- print("Test 2: PASSED")
-
- print("\n3. Testing BOP...")
- result = calculate_bop(ohlcv_data)
- print("Last BOP:", result['last'])
- assert result['last'] is not None
- print("Test 3: PASSED")
-
- print("\nAll tests: PASSED")
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/talipp_service.py b/fincept-qt/scripts/Analytics/talipp_wrapper/talipp_service.py
deleted file mode 100644
index 9fa6373c3..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/talipp_service.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""
-TALIpp Worker Handler - Dispatches indicator calculations by category.
-Usage: python worker_handler.py <operation> <json_data>
-"""
-import sys
-import json
-
-def main(args):
- if len(args) < 2:
- print(json.dumps({"error": "Usage: worker_handler.py <operation> <json_data>"}))
- return
-
- operation = args[0]
- data = json.loads(args[1])
-
- result = dispatch(operation, data)
- print(json.dumps(result))
-
-def dispatch(operation, data):
- try:
- # ==================== TREND INDICATORS ====================
- if operation == "sma":
- from talipp_wrapper.trend import calculate_sma
- return calculate_sma(data["prices"], data.get("period", 20))
- elif operation == "ema":
- from talipp_wrapper.trend import calculate_ema
- return calculate_ema(data["prices"], data.get("period", 20))
- elif operation == "wma":
- from talipp_wrapper.trend import calculate_wma
- return calculate_wma(data["prices"], data.get("period", 20))
- elif operation == "dema":
- from talipp_wrapper.trend import calculate_dema
- return calculate_dema(data["prices"], data.get("period", 20))
- elif operation == "tema":
- from talipp_wrapper.trend import calculate_tema
- return calculate_tema(data["prices"], data.get("period", 20))
- elif operation == "hma":
- from talipp_wrapper.trend import calculate_hma
- return calculate_hma(data["prices"], data.get("period", 20))
- elif operation == "kama":
- from talipp_wrapper.trend import calculate_kama
- return calculate_kama(data["prices"], data.get("period", 10), data.get("fast_period", 2), data.get("slow_period", 30))
- elif operation == "alma":
- from talipp_wrapper.trend import calculate_alma
- return calculate_alma(data["prices"], data.get("period", 9), data.get("sigma", 6.0), data.get("offset", 0.85))
- elif operation == "t3":
- from talipp_wrapper.trend import calculate_t3
- return calculate_t3(data["prices"], data.get("period", 5), data.get("vfactor", 0.7))
- elif operation == "zlema":
- from talipp_wrapper.trend import calculate_zlema
- return calculate_zlema(data["prices"], data.get("period", 20))
-
- # ==================== TREND OTHER (ADX, Aroon, Ichimoku, etc.) ====================
- elif operation == "adx":
- from talipp_wrapper.trend_other import calculate_adx
- return calculate_adx(data["ohlcv"], data.get("di_period", 14), data.get("adx_period", 14))
- elif operation == "aroon":
- from talipp_wrapper.trend_other import calculate_aroon
- return calculate_aroon(data["ohlcv"], data.get("period", 25))
- elif operation == "ichimoku":
- from talipp_wrapper.trend_other import calculate_ichimoku
- return calculate_ichimoku(data["ohlcv"])
- elif operation == "parabolic_sar":
- from talipp_wrapper.trend_other import calculate_parabolic_sar
- return calculate_parabolic_sar(data["ohlcv"], data.get("af_start", 0.02), data.get("af_max", 0.2), data.get("af_increment", 0.02))
- elif operation == "supertrend":
- from talipp_wrapper.trend_other import calculate_supertrend
- return calculate_supertrend(data["ohlcv"], data.get("period", 10), data.get("multiplier", 3.0))
-
- # ==================== MOMENTUM INDICATORS ====================
- elif operation == "rsi":
- from talipp_wrapper.momentum import calculate_rsi
- return calculate_rsi(data["prices"], data.get("period", 14))
- elif operation == "macd":
- from talipp_wrapper.momentum import calculate_macd
- return calculate_macd(data["prices"], data.get("fast_period", 12), data.get("slow_period", 26), data.get("signal_period", 9))
- elif operation == "stoch":
- from talipp_wrapper.momentum import calculate_stoch
- return calculate_stoch(data["ohlcv"], data.get("period", 14), data.get("smoothing_period", 3))
- elif operation == "stoch_rsi":
- from talipp_wrapper.momentum import calculate_stoch_rsi
- return calculate_stoch_rsi(data["prices"], data.get("period", 14), data.get("stoch_period", 14), data.get("k_smoothing", 3), data.get("d_smoothing", 3))
- elif operation == "cci":
- from talipp_wrapper.momentum import calculate_cci
- return calculate_cci(data["ohlcv"], data.get("period", 20))
- elif operation == "roc":
- from talipp_wrapper.momentum import calculate_roc
- return calculate_roc(data["prices"], data.get("period", 12))
- elif operation == "tsi":
- from talipp_wrapper.momentum import calculate_tsi
- return calculate_tsi(data["prices"], data.get("long_period", 25), data.get("short_period", 13), data.get("signal_period", 13))
- elif operation == "williams":
- from talipp_wrapper.momentum import calculate_williams
- return calculate_williams(data["ohlcv"], data.get("period", 14))
-
- # ==================== VOLATILITY INDICATORS ====================
- elif operation == "atr":
- from talipp_wrapper.volatility import calculate_atr
- return calculate_atr(data["ohlcv"], data.get("period", 14))
- elif operation == "bb":
- from talipp_wrapper.volatility import calculate_bb
- return calculate_bb(data["prices"], data.get("period", 20), data.get("std_dev", 2.0))
- elif operation == "keltner":
- from talipp_wrapper.volatility import calculate_keltner
- return calculate_keltner(data["ohlcv"], data.get("period", 20), data.get("atr_period", 10), data.get("atr_multi", 2.0))
- elif operation == "donchian":
- from talipp_wrapper.volatility import calculate_donchian
- return calculate_donchian(data["ohlcv"], data.get("period", 20))
- elif operation == "chandelier_stop":
- from talipp_wrapper.volatility import calculate_chandelier_stop
- return calculate_chandelier_stop(data["ohlcv"], data.get("period", 22), data.get("atr_period", 22), data.get("atr_multi", 3.0))
- elif operation == "natr":
- from talipp_wrapper.volatility import calculate_natr
- return calculate_natr(data["ohlcv"], data.get("period", 14))
-
- # ==================== VOLUME INDICATORS ====================
- elif operation == "obv":
- from talipp_wrapper.volume import calculate_obv
- return calculate_obv(data["ohlcv"])
- elif operation == "vwap":
- from talipp_wrapper.volume import calculate_vwap
- return calculate_vwap(data["ohlcv"])
- elif operation == "vwma":
- from talipp_wrapper.volume import calculate_vwma
- return calculate_vwma(data["ohlcv"], data.get("period", 20))
- elif operation == "mfi":
- from talipp_wrapper.volume import calculate_mfi
- return calculate_mfi(data["ohlcv"], data.get("period", 14))
- elif operation == "chaikin_osc":
- from talipp_wrapper.volume import calculate_chaikin_osc
- return calculate_chaikin_osc(data["ohlcv"], data.get("fast_period", 3), data.get("slow_period", 10))
- elif operation == "force_index":
- from talipp_wrapper.volume import calculate_force_index
- return calculate_force_index(data["ohlcv"], data.get("period", 13))
-
- # ==================== SPECIALIZED INDICATORS ====================
- elif operation == "ao":
- from talipp_wrapper.specialized import calculate_ao
- return calculate_ao(data["ohlcv"], data.get("fast_period", 5), data.get("slow_period", 34))
- elif operation == "accu_dist":
- from talipp_wrapper.specialized import calculate_accu_dist
- return calculate_accu_dist(data["ohlcv"])
- elif operation == "bop":
- from talipp_wrapper.specialized import calculate_bop
- return calculate_bop(data["ohlcv"])
- elif operation == "chop":
- from talipp_wrapper.specialized import calculate_chop
- return calculate_chop(data["ohlcv"], data.get("period", 14))
- elif operation == "coppock_curve":
- from talipp_wrapper.specialized import calculate_coppock_curve
- return calculate_coppock_curve(data["prices"], data.get("roc1_period", 14), data.get("roc2_period", 11), data.get("wma_period", 10))
- elif operation == "dpo":
- from talipp_wrapper.specialized import calculate_dpo
- return calculate_dpo(data["prices"], data.get("period", 20))
- elif operation == "emv":
- from talipp_wrapper.specialized import calculate_emv
- return calculate_emv(data["ohlcv"], data.get("period", 14))
- elif operation == "fibonacci":
- from talipp_wrapper.specialized import calculate_fibonacci_retracement
- return calculate_fibonacci_retracement(data["ohlcv"])
- elif operation == "ibs":
- from talipp_wrapper.specialized import calculate_ibs
- return calculate_ibs(data["ohlcv"])
- elif operation == "kst":
- from talipp_wrapper.specialized import calculate_kst
- return calculate_kst(data["prices"])
- elif operation == "kvo":
- from talipp_wrapper.specialized import calculate_kvo
- return calculate_kvo(data["ohlcv"], data.get("fast_period", 34), data.get("slow_period", 55), data.get("signal_period", 13))
- elif operation == "mass_index":
- from talipp_wrapper.specialized import calculate_mass_index
- return calculate_mass_index(data["ohlcv"], data.get("period", 25), data.get("ema_period", 9))
- elif operation == "mcginley":
- from talipp_wrapper.specialized import calculate_mcginley_dynamic
- return calculate_mcginley_dynamic(data["prices"], data.get("period", 14), data.get("k", 0.6))
- elif operation == "mean_dev":
- from talipp_wrapper.specialized import calculate_mean_dev
- return calculate_mean_dev(data["prices"], data.get("period", 20))
- elif operation == "pivots_hl":
- from talipp_wrapper.specialized import calculate_pivots_hl
- return calculate_pivots_hl(data["ohlcv"], data.get("left_bars", 5), data.get("right_bars", 5))
- elif operation == "rogers_satchell":
- from talipp_wrapper.specialized import calculate_rogers_satchell
- return calculate_rogers_satchell(data["ohlcv"], data.get("period", 14))
- elif operation == "sfx":
- from talipp_wrapper.specialized import calculate_sfx
- return calculate_sfx(data["ohlcv"], data.get("period", 5), data.get("atr_period", 10), data.get("atr_mult", 4.0))
- elif operation == "smma":
- from talipp_wrapper.specialized import calculate_smma
- return calculate_smma(data["prices"], data.get("period", 20))
- elif operation == "sobv":
- from talipp_wrapper.specialized import calculate_sobv
- return calculate_sobv(data["ohlcv"], data.get("period", 10))
- elif operation == "stc":
- from talipp_wrapper.specialized import calculate_stc
- return calculate_stc(data["prices"], data.get("fast_period", 23), data.get("slow_period", 50), data.get("cycle", 10))
- elif operation == "std_dev":
- from talipp_wrapper.specialized import calculate_std_dev
- return calculate_std_dev(data["prices"], data.get("period", 20))
- elif operation == "trix":
- from talipp_wrapper.specialized import calculate_trix
- return calculate_trix(data["prices"], data.get("period", 15), data.get("signal_period", 9))
- elif operation == "ttm":
- from talipp_wrapper.specialized import calculate_ttm
- return calculate_ttm(data["ohlcv"], data.get("bb_period", 20), data.get("kc_period", 20))
- elif operation == "uo":
- from talipp_wrapper.specialized import calculate_uo
- return calculate_uo(data["ohlcv"], data.get("short_period", 7), data.get("medium_period", 14), data.get("long_period", 28))
- elif operation == "vtx":
- from talipp_wrapper.specialized import calculate_vtx
- return calculate_vtx(data["ohlcv"], data.get("period", 14))
- elif operation == "zigzag":
- from talipp_wrapper.specialized import calculate_zigzag
- return calculate_zigzag(data["ohlcv"], data.get("change", 5.0))
-
- else:
- return {"error": f"Unknown operation: {operation}"}
-
- except Exception as e:
- return {"error": str(e)}
-
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/trend.py b/fincept-qt/scripts/Analytics/talipp_wrapper/trend.py
deleted file mode 100644
index 8b940f007..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/trend.py
+++ /dev/null
@@ -1,140 +0,0 @@
-from typing import List, Dict, Union
-from talipp.indicators import SMA, EMA, WMA, DEMA, TEMA, HMA, KAMA, ALMA, T3, ZLEMA
-
-def calculate_sma(prices: List[float], period: int = 20) -> Dict:
- sma = SMA(period)
- for price in prices:
- sma.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(sma)],
- 'period': period,
- 'last': float(sma[-1]) if len(sma) > 0 and sma[-1] is not None else None
- }
-
-def calculate_ema(prices: List[float], period: int = 20) -> Dict:
- ema = EMA(period)
- for price in prices:
- ema.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(ema)],
- 'period': period,
- 'last': float(ema[-1]) if len(ema) > 0 and ema[-1] is not None else None
- }
-
-def calculate_wma(prices: List[float], period: int = 20) -> Dict:
- wma = WMA(period)
- for price in prices:
- wma.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(wma)],
- 'period': period,
- 'last': float(wma[-1]) if len(wma) > 0 and wma[-1] is not None else None
- }
-
-def calculate_dema(prices: List[float], period: int = 20) -> Dict:
- dema = DEMA(period)
- for price in prices:
- dema.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(dema)],
- 'period': period,
- 'last': float(dema[-1]) if len(dema) > 0 and dema[-1] is not None else None
- }
-
-def calculate_tema(prices: List[float], period: int = 20) -> Dict:
- tema = TEMA(period)
- for price in prices:
- tema.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(tema)],
- 'period': period,
- 'last': float(tema[-1]) if len(tema) > 0 and tema[-1] is not None else None
- }
-
-def calculate_hma(prices: List[float], period: int = 20) -> Dict:
- hma = HMA(period)
- for price in prices:
- hma.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(hma)],
- 'period': period,
- 'last': float(hma[-1]) if len(hma) > 0 and hma[-1] is not None else None
- }
-
-def calculate_kama(prices: List[float], period: int = 10, fast_period: int = 2, slow_period: int = 30) -> Dict:
- kama = KAMA(period, fast_period, slow_period)
- for price in prices:
- kama.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(kama)],
- 'period': period,
- 'last': float(kama[-1]) if len(kama) > 0 and kama[-1] is not None else None
- }
-
-def calculate_alma(prices: List[float], period: int = 9, sigma: float = 6.0, offset: float = 0.85) -> Dict:
- alma = ALMA(period, sigma, offset)
- for price in prices:
- alma.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(alma)],
- 'period': period,
- 'last': float(alma[-1]) if len(alma) > 0 and alma[-1] is not None else None
- }
-
-def calculate_t3(prices: List[float], period: int = 5, vfactor: float = 0.7) -> Dict:
- t3 = T3(period, vfactor)
- for price in prices:
- t3.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(t3)],
- 'period': period,
- 'last': float(t3[-1]) if len(t3) > 0 and t3[-1] is not None else None
- }
-
-def calculate_zlema(prices: List[float], period: int = 20) -> Dict:
- zlema = ZLEMA(period)
- for price in prices:
- zlema.add(price)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(zlema)],
- 'period': period,
- 'last': float(zlema[-1]) if len(zlema) > 0 and zlema[-1] is not None else None
- }
-
-def main():
- print("Testing TALIpp Trend Indicators")
-
- prices = [100, 102, 101, 105, 107, 106, 108, 110, 109, 111, 113, 112, 115, 114, 116]
-
- print("\n1. Testing SMA...")
- result = calculate_sma(prices, period=5)
- print("SMA values:", len(result['values']))
- print("Last SMA:", result['last'])
- assert result['last'] is not None
- print("Test 1: PASSED")
-
- print("\n2. Testing EMA...")
- result = calculate_ema(prices, period=5)
- print("Last EMA:", result['last'])
- assert result['last'] is not None
- print("Test 2: PASSED")
-
- print("\n3. Testing DEMA...")
- result = calculate_dema(prices, period=5)
- print("Last DEMA:", result['last'])
- print("Test 3: PASSED")
-
- print("\nAll tests: PASSED")
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/trend_other.py b/fincept-qt/scripts/Analytics/talipp_wrapper/trend_other.py
deleted file mode 100644
index 55e05bffc..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/trend_other.py
+++ /dev/null
@@ -1,158 +0,0 @@
-from typing import List, Dict
-from talipp.indicators import ADX, Aroon, Ichimoku, ParabolicSAR, SuperTrend
-from talipp.ohlcv import OHLCV
-
-def calculate_adx(ohlcv_data: List[Dict], di_period: int = 14, adx_period: int = 14) -> Dict:
- adx = ADX(di_period, adx_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- adx.add(ohlcv)
-
- adx_values = []
- for val in adx:
- if val is not None:
- adx_values.append(float(val.value))
- else:
- adx_values.append(None)
-
- last_val = adx[-1] if len(adx) > 0 and adx[-1] is not None else None
-
- return {
- 'values': adx_values,
- 'di_period': di_period,
- 'adx_period': adx_period,
- 'last': float(last_val.value) if last_val else None
- }
-
-def calculate_aroon(ohlcv_data: List[Dict], period: int = 25) -> Dict:
- aroon = Aroon(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- aroon.add(ohlcv)
-
- up_values = []
- down_values = []
-
- for val in aroon:
- if val is not None:
- up_values.append(float(val.up))
- down_values.append(float(val.down))
- else:
- up_values.append(None)
- down_values.append(None)
-
- last_val = aroon[-1] if len(aroon) > 0 and aroon[-1] is not None else None
-
- return {
- 'up': up_values,
- 'down': down_values,
- 'last_up': float(last_val.up) if last_val else None,
- 'last_down': float(last_val.down) if last_val else None
- }
-
-def calculate_ichimoku(ohlcv_data: List[Dict]) -> Dict:
- ichimoku = Ichimoku()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- ichimoku.add(ohlcv)
-
- tenkan = []
- kijun = []
- senkou_a = []
- senkou_b = []
-
- for val in ichimoku:
- if val is not None:
- tenkan.append(float(val.tenkan_sen))
- kijun.append(float(val.kijun_sen))
- senkou_a.append(float(val.senkou_span_a))
- senkou_b.append(float(val.senkou_span_b))
- else:
- tenkan.append(None)
- kijun.append(None)
- senkou_a.append(None)
- senkou_b.append(None)
-
- last_val = ichimoku[-1] if len(ichimoku) > 0 and ichimoku[-1] is not None else None
-
- return {
- 'tenkan_sen': tenkan,
- 'kijun_sen': kijun,
- 'senkou_span_a': senkou_a,
- 'senkou_span_b': senkou_b,
- 'last_tenkan': float(last_val.tenkan_sen) if last_val else None,
- 'last_kijun': float(last_val.kijun_sen) if last_val else None
- }
-
-def calculate_parabolic_sar(ohlcv_data: List[Dict], af_start: float = 0.02, af_max: float = 0.2, af_increment: float = 0.02) -> Dict:
- psar = ParabolicSAR(af_start, af_max, af_increment)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- psar.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(psar)],
- 'last': float(psar[-1]) if len(psar) > 0 and psar[-1] is not None else None
- }
-
-def calculate_supertrend(ohlcv_data: List[Dict], period: int = 10, multiplier: float = 3.0) -> Dict:
- supertrend = SuperTrend(period, multiplier)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- supertrend.add(ohlcv)
-
- values = []
- trends = []
-
- for val in supertrend:
- if val is not None:
- values.append(float(val.value))
- trends.append(int(val.trend))
- else:
- values.append(None)
- trends.append(None)
-
- last_val = supertrend[-1] if len(supertrend) > 0 and supertrend[-1] is not None else None
-
- return {
- 'values': values,
- 'trends': trends,
- 'last_value': float(last_val.value) if last_val else None,
- 'last_trend': int(last_val.trend) if last_val else None
- }
-
-def main():
- print("Testing TALIpp Trend/Other Indicators")
-
- ohlcv_data = [
- {'open': 100, 'high': 102, 'low': 99, 'close': 101, 'volume': 1000},
- {'open': 101, 'high': 103, 'low': 100, 'close': 102, 'volume': 1100},
- {'open': 102, 'high': 105, 'low': 101, 'close': 104, 'volume': 1200},
- {'open': 104, 'high': 106, 'low': 103, 'close': 105, 'volume': 1150},
- {'open': 105, 'high': 107, 'low': 104, 'close': 106, 'volume': 1300},
- ] * 10
-
- print("\n1. Testing ADX...")
- try:
- result = calculate_adx(ohlcv_data, di_period=14, adx_period=14)
- print("Last ADX:", result['last'])
- print("Test 1: PASSED")
- except Exception as e:
- print("Test 1: SKIPPED (ADX requires more data points)")
- print("Error:", str(e))
-
- print("\n2. Testing Aroon...")
- result = calculate_aroon(ohlcv_data, period=25)
- print("Last Aroon Up:", result['last_up'])
- print("Last Aroon Down:", result['last_down'])
- print("Test 2: PASSED")
-
- print("\n3. Testing Parabolic SAR...")
- result = calculate_parabolic_sar(ohlcv_data)
- print("Last SAR:", result['last'])
- print("Test 3: PASSED")
-
- print("\nAll tests: PASSED")
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/volatility.py b/fincept-qt/scripts/Analytics/talipp_wrapper/volatility.py
deleted file mode 100644
index 26275ec95..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/volatility.py
+++ /dev/null
@@ -1,180 +0,0 @@
-from typing import List, Dict
-from talipp.indicators import ATR, BB, KeltnerChannels, DonchianChannels, ChandeKrollStop, NATR
-from talipp.ohlcv import OHLCV
-
-def calculate_atr(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- atr = ATR(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- atr.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(atr)],
- 'period': period,
- 'last': float(atr[-1]) if len(atr) > 0 and atr[-1] is not None else None
- }
-
-def calculate_bb(prices: List[float], period: int = 20, std_dev: float = 2.0) -> Dict:
- bb = BB(period, std_dev)
- for price in prices:
- bb.add(price)
-
- upper = []
- middle = []
- lower = []
-
- for val in bb:
- if val is not None:
- upper.append(float(val.ub))
- middle.append(float(val.cb))
- lower.append(float(val.lb))
- else:
- upper.append(None)
- middle.append(None)
- lower.append(None)
-
- last_val = bb[-1] if len(bb) > 0 and bb[-1] is not None else None
-
- return {
- 'upper': upper,
- 'middle': middle,
- 'lower': lower,
- 'last_upper': float(last_val.ub) if last_val else None,
- 'last_middle': float(last_val.cb) if last_val else None,
- 'last_lower': float(last_val.lb) if last_val else None
- }
-
-def calculate_keltner(ohlcv_data: List[Dict], period: int = 20, atr_period: int = 10, atr_multi: float = 2.0) -> Dict:
- keltner = KeltnerChannels(period, atr_period, atr_multi)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- keltner.add(ohlcv)
-
- upper = []
- middle = []
- lower = []
-
- for val in keltner:
- if val is not None:
- upper.append(float(val.ub))
- middle.append(float(val.cb))
- lower.append(float(val.lb))
- else:
- upper.append(None)
- middle.append(None)
- lower.append(None)
-
- last_val = keltner[-1] if len(keltner) > 0 and keltner[-1] is not None else None
-
- return {
- 'upper': upper,
- 'middle': middle,
- 'lower': lower,
- 'last_upper': float(last_val.ub) if last_val else None,
- 'last_middle': float(last_val.cb) if last_val else None,
- 'last_lower': float(last_val.lb) if last_val else None
- }
-
-def calculate_donchian(ohlcv_data: List[Dict], period: int = 20) -> Dict:
- donchian = DonchianChannels(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- donchian.add(ohlcv)
-
- upper = []
- middle = []
- lower = []
-
- for val in donchian:
- if val is not None:
- upper.append(float(val.ub))
- middle.append(float(val.cb))
- lower.append(float(val.lb))
- else:
- upper.append(None)
- middle.append(None)
- lower.append(None)
-
- last_val = donchian[-1] if len(donchian) > 0 and donchian[-1] is not None else None
-
- return {
- 'upper': upper,
- 'middle': middle,
- 'lower': lower,
- 'last_upper': float(last_val.ub) if last_val else None,
- 'last_middle': float(last_val.cb) if last_val else None,
- 'last_lower': float(last_val.lb) if last_val else None
- }
-
-def calculate_chandelier_stop(ohlcv_data: List[Dict], period: int = 22, atr_period: int = 22, atr_multi: float = 3.0) -> Dict:
- chandelier = ChandeKrollStop(period, atr_period, atr_multi)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- chandelier.add(ohlcv)
-
- long_stop = []
- short_stop = []
-
- for val in chandelier:
- if val is not None:
- long_stop.append(float(val.long_stop))
- short_stop.append(float(val.short_stop))
- else:
- long_stop.append(None)
- short_stop.append(None)
-
- last_val = chandelier[-1] if len(chandelier) > 0 and chandelier[-1] is not None else None
-
- return {
- 'long_stop': long_stop,
- 'short_stop': short_stop,
- 'last_long_stop': float(last_val.long_stop) if last_val else None,
- 'last_short_stop': float(last_val.short_stop) if last_val else None
- }
-
-def calculate_natr(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- natr = NATR(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- natr.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(natr)],
- 'period': period,
- 'last': float(natr[-1]) if len(natr) > 0 and natr[-1] is not None else None
- }
-
-def main():
- print("Testing TALIpp Volatility Indicators")
-
- ohlcv_data = [
- {'open': 100, 'high': 102, 'low': 99, 'close': 101, 'volume': 1000},
- {'open': 101, 'high': 103, 'low': 100, 'close': 102, 'volume': 1100},
- {'open': 102, 'high': 105, 'low': 101, 'close': 104, 'volume': 1200},
- {'open': 104, 'high': 106, 'low': 103, 'close': 105, 'volume': 1150},
- {'open': 105, 'high': 107, 'low': 104, 'close': 106, 'volume': 1300},
- ] * 5
-
- prices = [bar['close'] for bar in ohlcv_data]
-
- print("\n1. Testing ATR...")
- result = calculate_atr(ohlcv_data, period=14)
- print("Last ATR:", result['last'])
- print("Test 1: PASSED")
-
- print("\n2. Testing Bollinger Bands...")
- result = calculate_bb(prices, period=20)
- print("Last Upper:", result['last_upper'])
- print("Last Middle:", result['last_middle'])
- print("Last Lower:", result['last_lower'])
- print("Test 2: PASSED")
-
- print("\n3. Testing Donchian Channels...")
- result = calculate_donchian(ohlcv_data, period=20)
- print("Last Upper:", result['last_upper'])
- print("Test 3: PASSED")
-
- print("\nAll tests: PASSED")
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/Analytics/talipp_wrapper/volume.py b/fincept-qt/scripts/Analytics/talipp_wrapper/volume.py
deleted file mode 100644
index 67affab40..000000000
--- a/fincept-qt/scripts/Analytics/talipp_wrapper/volume.py
+++ /dev/null
@@ -1,106 +0,0 @@
-from typing import List, Dict
-from talipp.indicators import OBV, VWAP, VWMA, ChaikinOsc, ForceIndex
-from talipp.ohlcv import OHLCV
-
-def calculate_obv(ohlcv_data: List[Dict]) -> Dict:
- obv = OBV()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- obv.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(obv)],
- 'last': float(obv[-1]) if len(obv) > 0 and obv[-1] is not None else None
- }
-
-def calculate_vwap(ohlcv_data: List[Dict]) -> Dict:
- vwap = VWAP()
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- vwap.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(vwap)],
- 'last': float(vwap[-1]) if len(vwap) > 0 and vwap[-1] is not None else None
- }
-
-def calculate_vwma(ohlcv_data: List[Dict], period: int = 20) -> Dict:
- vwma = VWMA(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- vwma.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(vwma)],
- 'period': period,
- 'last': float(vwma[-1]) if len(vwma) > 0 and vwma[-1] is not None else None
- }
-
-def calculate_mfi(ohlcv_data: List[Dict], period: int = 14) -> Dict:
- from talipp.indicators import MFI
- mfi = MFI(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- mfi.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(mfi)],
- 'period': period,
- 'last': float(mfi[-1]) if len(mfi) > 0 and mfi[-1] is not None else None
- }
-
-def calculate_chaikin_osc(ohlcv_data: List[Dict], fast_period: int = 3, slow_period: int = 10) -> Dict:
- chaikin = ChaikinOsc(fast_period, slow_period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- chaikin.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(chaikin)],
- 'last': float(chaikin[-1]) if len(chaikin) > 0 and chaikin[-1] is not None else None
- }
-
-def calculate_force_index(ohlcv_data: List[Dict], period: int = 13) -> Dict:
- force_idx = ForceIndex(period)
- for bar in ohlcv_data:
- ohlcv = OHLCV(bar['open'], bar['high'], bar['low'], bar['close'], bar.get('volume', 0))
- force_idx.add(ohlcv)
-
- return {
- 'values': [float(v) if v is not None else None for v in list(force_idx)],
- 'period': period,
- 'last': float(force_idx[-1]) if len(force_idx) > 0 and force_idx[-1] is not None else None
- }
-
-def main():
- print("Testing TALIpp Volume Indicators")
-
- ohlcv_data = [
- {'open': 100, 'high': 102, 'low': 99, 'close': 101, 'volume': 1000},
- {'open': 101, 'high': 103, 'low': 100, 'close': 102, 'volume': 1100},
- {'open': 102, 'high': 105, 'low': 101, 'close': 104, 'volume': 1200},
- {'open': 104, 'high': 106, 'low': 103, 'close': 105, 'volume': 1150},
- {'open': 105, 'high': 107, 'low': 104, 'close': 106, 'volume': 1300},
- ] * 5
-
- print("\n1. Testing OBV...")
- result = calculate_obv(ohlcv_data)
- print("Last OBV:", result['last'])
- assert result['last'] is not None
- print("Test 1: PASSED")
-
- print("\n2. Testing VWAP...")
- result = calculate_vwap(ohlcv_data)
- print("Last VWAP:", result['last'])
- assert result['last'] is not None
- print("Test 2: PASSED")
-
- print("\n3. Testing VWMA...")
- result = calculate_vwma(ohlcv_data, period=10)
- print("Last VWMA:", result['last'])
- print("Test 3: PASSED")
-
- print("\nAll tests: PASSED")
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/equity_talipp.py b/fincept-qt/scripts/equity_talipp.py
deleted file mode 100644
index b7c962039..000000000
--- a/fincept-qt/scripts/equity_talipp.py
+++ /dev/null
@@ -1,559 +0,0 @@
-"""
-equity_talipp.py — TALIpp technical indicator computation for Equity Research tab
-
-Usage:
- python equity_talipp.py <indicator_name> <ohlcv_json> [params_json]
-
-Arguments:
- indicator_name One of: SMA, EMA, WMA, DEMA, TEMA, TRIMA, KAMA, T3,
- RSI, MACD, STOCH, STOCHRSI, CCI, ROC, MOM, WILLR, MFI,
- ATR, BBANDS, NATR, STDDEV, OBV, VWAP, AD,
- AROON, ADX, DX, SAR, BOP, TRIX, TSI
- ohlcv_json JSON array of OHLCV objects with keys:
- timestamp, open, high, low, close, volume
- params_json Optional JSON object of parameters, e.g.:
- {"period": 14} or {"fast": 12, "slow": 26, "signal": 9}
-
-Output (stdout):
- JSON object: {"indicator": str, "values": [float], "timestamps": [int], "success": bool}
-"""
-
-import sys
-import json
-import math
-
-
-def safe_float(v):
- """Convert value to float, return None if NaN/Inf."""
- try:
- f = float(v)
- return None if (math.isnan(f) or math.isinf(f)) else f
- except (TypeError, ValueError):
- return None
-
-
-def sma(closes, period):
- """Simple Moving Average."""
- result = []
- for i in range(len(closes)):
- if i < period - 1:
- result.append(None)
- else:
- window = closes[i - period + 1:i + 1]
- result.append(sum(window) / period)
- return result
-
-
-def ema(closes, period, smoothing=2.0):
- """Exponential Moving Average."""
- k = smoothing / (period + 1)
- result = []
- prev = None
- for i, c in enumerate(closes):
- if prev is None:
- if i < period - 1:
- result.append(None)
- continue
- # Seed with SMA of first `period` values
- prev = sum(closes[:period]) / period
- result.append(prev)
- else:
- prev = c * k + prev * (1 - k)
- result.append(prev)
- return result
-
-
-def wma(closes, period):
- """Weighted Moving Average."""
- result = []
- denom = period * (period + 1) / 2
- for i in range(len(closes)):
- if i < period - 1:
- result.append(None)
- else:
- w = sum((j + 1) * closes[i - period + 1 + j] for j in range(period))
- result.append(w / denom)
- return result
-
-
-def dema(closes, period):
- e1 = ema(closes, period)
- e1_clean = [v if v is not None else 0.0 for v in e1]
- e2 = ema(e1_clean, period)
- return [
- (2 * v1 - v2) if (v1 is not None and v2 is not None) else None
- for v1, v2 in zip(e1, e2)
- ]
-
-
-def tema(closes, period):
- e1 = ema(closes, period)
- e1_c = [v if v is not None else 0.0 for v in e1]
- e2 = ema(e1_c, period)
- e2_c = [v if v is not None else 0.0 for v in e2]
- e3 = ema(e2_c, period)
- return [
- (3 * v1 - 3 * v2 + v3) if (v1 is not None and v2 is not None and v3 is not None) else None
- for v1, v2, v3 in zip(e1, e2, e3)
- ]
-
-
-def trima(closes, period):
- """Triangular Moving Average (SMA of SMA)."""
- s1 = sma(closes, period)
- s1_c = [v if v is not None else 0.0 for v in s1]
- return sma(s1_c, period)
-
-
-def kama(closes, period=10, fast=2, slow=30):
- """Kaufman's Adaptive Moving Average."""
- fast_k = 2.0 / (fast + 1)
- slow_k = 2.0 / (slow + 1)
- result = [None] * len(closes)
- if len(closes) <= period:
- return result
- result[period - 1] = closes[period - 1]
- for i in range(period, len(closes)):
- direction = abs(closes[i] - closes[i - period])
- volatility = sum(abs(closes[j] - closes[j - 1]) for j in range(i - period + 1, i + 1))
- er = direction / volatility if volatility != 0 else 0
- sc = (er * (fast_k - slow_k) + slow_k) ** 2
- prev = result[i - 1]
- result[i] = prev + sc * (closes[i] - prev)
- return result
-
-
-def t3(closes, period=5, vfactor=0.7):
- """Triple Exponential Moving Average (T3) by Tillson."""
- c1 = -(vfactor ** 3)
- c2 = 3 * vfactor ** 2 + 3 * vfactor ** 3
- c3 = -6 * vfactor ** 2 - 3 * vfactor - 3 * vfactor ** 3
- c4 = 1 + 3 * vfactor + vfactor ** 3 + 3 * vfactor ** 2
- e1 = ema(closes, period)
- e1_c = [v or 0.0 for v in e1]
- e2 = ema(e1_c, period)
- e2_c = [v or 0.0 for v in e2]
- e3 = ema(e2_c, period)
- e3_c = [v or 0.0 for v in e3]
- e4 = ema(e3_c, period)
- e4_c = [v or 0.0 for v in e4]
- e5 = ema(e4_c, period)
- e5_c = [v or 0.0 for v in e5]
- e6 = ema(e5_c, period)
- return [
- (c1 * v6 + c2 * v5 + c3 * v4 + c4 * v3)
- if all(v is not None for v in [v3, v4, v5, v6]) else None
- for v3, v4, v5, v6 in zip(e3, e4, e5, e6)
- ]
-
-
-def rsi(closes, period=14):
- result = [None] * len(closes)
- if len(closes) < period + 1:
- return result
- gains = [max(closes[i] - closes[i - 1], 0) for i in range(1, len(closes))]
- losses = [max(closes[i - 1] - closes[i], 0) for i in range(1, len(closes))]
- avg_gain = sum(gains[:period]) / period
- avg_loss = sum(losses[:period]) / period
- result[period] = 100 - (100 / (1 + avg_gain / avg_loss)) if avg_loss != 0 else 100
- for i in range(period + 1, len(closes)):
- avg_gain = (avg_gain * (period - 1) + gains[i - 1]) / period
- avg_loss = (avg_loss * (period - 1) + losses[i - 1]) / period
- rs = avg_gain / avg_loss if avg_loss != 0 else 0
- result[i] = 100 - (100 / (1 + rs))
- return result
-
-
-def macd_calc(closes, fast=12, slow=26, signal=9):
- e_fast = ema(closes, fast)
- e_slow = ema(closes, slow)
- macd_line = [
- (f - s) if (f is not None and s is not None) else None
- for f, s in zip(e_fast, e_slow)
- ]
- macd_clean = [v or 0.0 for v in macd_line]
- sig_line = ema(macd_clean, signal)
- hist = [
- (m - s) if (m is not None and s is not None) else None
- for m, s in zip(macd_line, sig_line)
- ]
- return macd_line, sig_line, hist
-
-
-def stoch(highs, lows, closes, k_period=14, d_period=3):
- k_vals = []
- for i in range(len(closes)):
- if i < k_period - 1:
- k_vals.append(None)
- else:
- window_h = highs[i - k_period + 1:i + 1]
- window_l = lows[i - k_period + 1:i + 1]
- highest = max(window_h)
- lowest = min(window_l)
- denom = highest - lowest
- k_vals.append((closes[i] - lowest) / denom * 100 if denom != 0 else 50)
- k_clean = [v or 50.0 for v in k_vals]
- d_vals = sma(k_clean, d_period)
- return k_vals, d_vals
-
-
-def cci_calc(highs, lows, closes, period=20):
- result = []
- for i in range(len(closes)):
- if i < period - 1:
- result.append(None)
- else:
- tp = [(highs[j] + lows[j] + closes[j]) / 3 for j in range(i - period + 1, i + 1)]
- mean_tp = sum(tp) / period
- mean_dev = sum(abs(x - mean_tp) for x in tp) / period
- result.append((tp[-1] - mean_tp) / (0.015 * mean_dev) if mean_dev != 0 else 0)
- return result
-
-
-def roc(closes, period=10):
- result = [None] * period
- for i in range(period, len(closes)):
- prev = closes[i - period]
- result.append((closes[i] - prev) / prev * 100 if prev != 0 else 0)
- return result
-
-
-def mom(closes, period=14):
- result = [None] * period
- for i in range(period, len(closes)):
- result.append(closes[i] - closes[i - period])
- return result
-
-
-def willr(highs, lows, closes, period=14):
- result = []
- for i in range(len(closes)):
- if i < period - 1:
- result.append(None)
- else:
- hh = max(highs[i - period + 1:i + 1])
- ll = min(lows[i - period + 1:i + 1])
- denom = hh - ll
- result.append((hh - closes[i]) / denom * -100 if denom != 0 else -50)
- return result
-
-
-def mfi(highs, lows, closes, volumes, period=14):
- typical = [(h + l + c) / 3 for h, l, c in zip(highs, lows, closes)]
- result = [None] * period
- for i in range(period, len(closes)):
- pos_flow = sum(
- typical[j] * volumes[j]
- for j in range(i - period + 1, i + 1)
- if typical[j] >= typical[j - 1]
- )
- neg_flow = sum(
- typical[j] * volumes[j]
- for j in range(i - period + 1, i + 1)
- if typical[j] < typical[j - 1]
- )
- mfr = pos_flow / neg_flow if neg_flow != 0 else 0
- result.append(100 - (100 / (1 + mfr)))
- return result
-
-
-def atr(highs, lows, closes, period=14):
- tr = [highs[0] - lows[0]]
- for i in range(1, len(closes)):
- tr.append(max(highs[i] - lows[i],
- abs(highs[i] - closes[i - 1]),
- abs(lows[i] - closes[i - 1])))
- result = [None] * (period - 1)
- atr_val = sum(tr[:period]) / period
- result.append(atr_val)
- for i in range(period, len(tr)):
- atr_val = (atr_val * (period - 1) + tr[i]) / period
- result.append(atr_val)
- return result
-
-
-def bbands(closes, period=20, stddev=2.0):
- mid = sma(closes, period)
- upper, lower = [], []
- for i in range(len(closes)):
- if mid[i] is None:
- upper.append(None)
- lower.append(None)
- else:
- window = closes[i - period + 1:i + 1]
- mean = mid[i]
- sd = (sum((x - mean) ** 2 for x in window) / period) ** 0.5
- upper.append(mean + stddev * sd)
- lower.append(mean - stddev * sd)
- return upper, mid, lower
-
-
-def natr(highs, lows, closes, period=14):
- atr_vals = atr(highs, lows, closes, period)
- return [
- (a / c * 100) if (a is not None and c and c != 0) else None
- for a, c in zip(atr_vals, closes)
- ]
-
-
-def stddev(closes, period=20):
- result = []
- for i in range(len(closes)):
- if i < period - 1:
- result.append(None)
- else:
- window = closes[i - period + 1:i + 1]
- mean = sum(window) / period
- result.append((sum((x - mean) ** 2 for x in window) / period) ** 0.5)
- return result
-
-
-def obv(closes, volumes):
- result = [volumes[0]]
- for i in range(1, len(closes)):
- if closes[i] > closes[i - 1]:
- result.append(result[-1] + volumes[i])
- elif closes[i] < closes[i - 1]:
- result.append(result[-1] - volumes[i])
- else:
- result.append(result[-1])
- return result
-
-
-def vwap(highs, lows, closes, volumes):
- """Daily VWAP (cumulative, resets would need session info — use cumulative here)."""
- typ = [(h + l + c) / 3 for h, l, c in zip(highs, lows, closes)]
- cum_tp_vol = 0.0
- cum_vol = 0.0
- result = []
- for tp, v in zip(typ, volumes):
- cum_tp_vol += tp * v
- cum_vol += v
- result.append(cum_tp_vol / cum_vol if cum_vol != 0 else tp)
- return result
-
-
-def ad(highs, lows, closes, volumes):
- """Accumulation/Distribution Line."""
- result = []
- cumulative = 0.0
- for h, l, c, v in zip(highs, lows, closes, volumes):
- denom = h - l
- clv = ((c - l) - (h - c)) / denom if denom != 0 else 0
- cumulative += clv * v
- result.append(cumulative)
- return result
-
-
-def aroon(highs, lows, period=14):
- up, down = [], []
- for i in range(len(highs)):
- if i < period:
- up.append(None)
- down.append(None)
- else:
- window_h = highs[i - period:i + 1]
- window_l = lows[i - period:i + 1]
- bars_since_high = period - window_h.index(max(window_h))
- bars_since_low = period - window_l.index(min(window_l))
- up.append((period - bars_since_high) / period * 100)
- down.append((period - bars_since_low) / period * 100)
- return up, down
-
-
-def adx_calc(highs, lows, closes, period=14):
- tr_vals = [max(highs[0] - lows[0], 0)]
- plus_dm = [0.0]
- minus_dm = [0.0]
- for i in range(1, len(closes)):
- tr_vals.append(max(highs[i] - lows[i],
- abs(highs[i] - closes[i - 1]),
- abs(lows[i] - closes[i - 1])))
- pdm = highs[i] - highs[i - 1]
- ndm = lows[i - 1] - lows[i]
- plus_dm.append(max(pdm, 0) if pdm > ndm else 0)
- minus_dm.append(max(ndm, 0) if ndm > pdm else 0)
-
- def smooth(vals, p):
- result = [sum(vals[:p])]
- for v in vals[p:]:
- result.append(result[-1] - result[-1] / p + v)
- return [None] * (p - 1) + result
-
- str_ = smooth(tr_vals, period)
- spdm = smooth(plus_dm, period)
- sndm = smooth(minus_dm, period)
- adx_vals = []
- for s, p, n in zip(str_, spdm, sndm):
- if s is None or s == 0:
- adx_vals.append(None)
- else:
- adx_vals.append(abs(p - n) / (p + n) * 100 if (p + n) != 0 else 0)
- return smooth([v or 0.0 for v in adx_vals], period)
-
-
-def sar(highs, lows, acceleration=0.02, maximum=0.2):
- result = [None] * len(highs)
- if len(highs) < 2:
- return result
- is_bull = highs[1] > highs[0]
- af = acceleration
- ep = highs[0] if is_bull else lows[0]
- sar_val = lows[0] if is_bull else highs[0]
- result[0] = sar_val
- for i in range(1, len(highs)):
- sar_val = sar_val + af * (ep - sar_val)
- if is_bull:
- sar_val = min(sar_val, lows[i - 1], lows[max(i - 2, 0)])
- if lows[i] < sar_val:
- is_bull = False
- sar_val = ep
- ep = lows[i]
- af = acceleration
- else:
- if highs[i] > ep:
- ep = highs[i]
- af = min(af + acceleration, maximum)
- else:
- sar_val = max(sar_val, highs[i - 1], highs[max(i - 2, 0)])
- if highs[i] > sar_val:
- is_bull = True
- sar_val = ep
- ep = highs[i]
- af = acceleration
- else:
- if lows[i] < ep:
- ep = lows[i]
- af = min(af + acceleration, maximum)
- result[i] = sar_val
- return result
-
-
-def bop_calc(opens, highs, lows, closes):
- return [
- (c - o) / (h - l) if (h - l) != 0 else 0
- for o, h, l, c in zip(opens, highs, lows, closes)
- ]
-
-
-def trix(closes, period=15):
- e1 = ema(closes, period)
- e1_c = [v or 0.0 for v in e1]
- e2 = ema(e1_c, period)
- e2_c = [v or 0.0 for v in e2]
- e3 = ema(e2_c, period)
- result = [None]
- for i in range(1, len(e3)):
- if e3[i] is not None and e3[i - 1] is not None and e3[i - 1] != 0:
- result.append((e3[i] - e3[i - 1]) / e3[i - 1] * 100)
- else:
- result.append(None)
- return result
-
-
-def tsi(closes, long_period=25, short_period=13):
- mom_1 = [None] + [closes[i] - closes[i - 1] for i in range(1, len(closes))]
- abs_mom = [None if v is None else abs(v) for v in mom_1]
- mom_c = [v or 0.0 for v in mom_1]
- abs_c = [v or 0.0 for v in abs_mom]
- e1 = ema(mom_c, long_period)
- ea1 = ema(abs_c, long_period)
- e1_c = [v or 0.0 for v in e1]
- ea1_c = [v or 0.0 for v in ea1]
- e2 = ema(e1_c, short_period)
- ea2 = ema(ea1_c, short_period)
- return [
- (v / a * 100) if (a is not None and a != 0 and v is not None) else None
- for v, a in zip(e2, ea2)
- ]
-
-
-DISPATCH = {
- "SMA": lambda o, h, l, c, v, p: sma(c, int(p.get("period", 20))),
- "EMA": lambda o, h, l, c, v, p: ema(c, int(p.get("period", 20))),
- "WMA": lambda o, h, l, c, v, p: wma(c, int(p.get("period", 20))),
- "DEMA": lambda o, h, l, c, v, p: dema(c, int(p.get("period", 20))),
- "TEMA": lambda o, h, l, c, v, p: tema(c, int(p.get("period", 20))),
- "TRIMA": lambda o, h, l, c, v, p: trima(c, int(p.get("period", 20))),
- "KAMA": lambda o, h, l, c, v, p: kama(c, int(p.get("period", 10))),
- "T3": lambda o, h, l, c, v, p: t3(c, int(p.get("period", 5)), float(p.get("vfactor", 0.7))),
- "RSI": lambda o, h, l, c, v, p: rsi(c, int(p.get("period", 14))),
- "MACD": lambda o, h, l, c, v, p: macd_calc(c, int(p.get("fast", 12)), int(p.get("slow", 26)), int(p.get("signal", 9)))[0],
- "STOCH": lambda o, h, l, c, v, p: stoch(h, l, c, int(p.get("k_period", 14)), int(p.get("d_period", 3)))[0],
- "STOCHRSI": lambda o, h, l, c, v, p: rsi(rsi(c, int(p.get("period", 14))), int(p.get("period", 14))),
- "CCI": lambda o, h, l, c, v, p: cci_calc(h, l, c, int(p.get("period", 20))),
- "ROC": lambda o, h, l, c, v, p: roc(c, int(p.get("period", 10))),
- "MOM": lambda o, h, l, c, v, p: mom(c, int(p.get("period", 14))),
- "WILLR": lambda o, h, l, c, v, p: willr(h, l, c, int(p.get("period", 14))),
- "MFI": lambda o, h, l, c, v, p: mfi(h, l, c, v, int(p.get("period", 14))),
- "ATR": lambda o, h, l, c, v, p: atr(h, l, c, int(p.get("period", 14))),
- "BBANDS": lambda o, h, l, c, v, p: bbands(c, int(p.get("period", 20)), float(p.get("stddev", 2.0)))[0],
- "NATR": lambda o, h, l, c, v, p: natr(h, l, c, int(p.get("period", 14))),
- "STDDEV": lambda o, h, l, c, v, p: stddev(c, int(p.get("period", 20))),
- "OBV": lambda o, h, l, c, v, p: obv(c, v),
- "VWAP": lambda o, h, l, c, v, p: vwap(h, l, c, v),
- "AD": lambda o, h, l, c, v, p: ad(h, l, c, v),
- "AROON": lambda o, h, l, c, v, p: aroon(h, l, int(p.get("period", 14)))[0],
- "ADX": lambda o, h, l, c, v, p: adx_calc(h, l, c, int(p.get("period", 14))),
- "DX": lambda o, h, l, c, v, p: adx_calc(h, l, c, int(p.get("period", 14))),
- "SAR": lambda o, h, l, c, v, p: sar(h, l, float(p.get("acceleration", 0.02)), float(p.get("maximum", 0.2))),
- "BOP": lambda o, h, l, c, v, p: bop_calc(o, h, l, c),
- "TRIX": lambda o, h, l, c, v, p: trix(c, int(p.get("period", 15))),
- "TSI": lambda o, h, l, c, v, p: tsi(c, int(p.get("long_period", 25)), int(p.get("short_period", 13))),
-}
-
-
-def main():
- if len(sys.argv) < 3:
- print(json.dumps({
- "success": False,
- "error": "Usage: equity_talipp.py <indicator> <ohlcv_json> [params_json]"
- }))
- sys.exit(1)
-
- indicator = sys.argv[1].upper()
- ohlcv_raw = sys.argv[2]
- params = json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}
-
- try:
- data = json.loads(ohlcv_raw)
- if not isinstance(data, list) or len(data) == 0:
- raise ValueError("OHLCV data must be a non-empty JSON array")
-
- opens = [float(r.get("open", 0)) for r in data]
- highs = [float(r.get("high", 0)) for r in data]
- lows = [float(r.get("low", 0)) for r in data]
- closes = [float(r.get("close", 0)) for r in data]
- vols = [float(r.get("volume", 0)) for r in data]
- ts = [int(r.get("timestamp", 0)) for r in data]
-
- if indicator not in DISPATCH:
- raise ValueError(f"Unknown indicator: {indicator}. "
- f"Supported: {', '.join(sorted(DISPATCH.keys()))}")
-
- raw_values = DISPATCH[indicator](opens, highs, lows, closes, vols, params)
-
- # Pair with timestamps and filter None/NaN
- values_out = []
- timestamps_out = []
- for i, v in enumerate(raw_values):
- fv = safe_float(v)
- if fv is not None and i < len(ts):
- values_out.append(fv)
- timestamps_out.append(ts[i])
-
- print(json.dumps({
- "success": True,
- "indicator": indicator,
- "values": values_out,
- "timestamps": timestamps_out,
- "count": len(values_out),
- }))
-
- except Exception as e:
- print(json.dumps({"success": False, "error": str(e), "indicator": indicator}))
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/fetch_company_news.py b/fincept-qt/scripts/fetch_company_news.py
index fa543df2e..d7002dfbb 100644
--- a/fincept-qt/scripts/fetch_company_news.py
+++ b/fincept-qt/scripts/fetch_company_news.py
@@ -5,9 +5,21 @@ This script fetches latest news articles for a given company/symbol
import sys
import json
+import email.utils
from datetime import datetime
from gnews import GNews
+
+def _to_iso_date(raw):
+ """Normalize GNews RFC-822 dates ('Mon, 02 Jun 2025 07:00:00 GMT') to ISO
+ ('2025-06-02T07:00:00') so downstream consumers can slice YYYY-MM-DD."""
+ if not raw:
+ return ""
+ try:
+ return email.utils.parsedate_to_datetime(raw).strftime("%Y-%m-%dT%H:%M:%S")
+ except Exception:
+ return raw
+
def fetch_company_news(query, max_results=10, period='7d', language='en', country='US'):
"""
Fetch news articles for a company
@@ -52,7 +64,7 @@ def fetch_company_news(query, max_results=10, period='7d', language='en', countr
"url": article.get('url', '#'),
"publisher": article.get('publisher', {}).get('title', 'Unknown'),
"publisher_url": article.get('publisher', {}).get('href', '#'),
- "published_date": article.get('published date', 'Unknown'),
+ "published_date": _to_iso_date(article.get('published date', '')),
"image_url": None # GNews doesn't provide images directly
}
articles.append(processed_article)
diff --git a/fincept-qt/scripts/news_nlp.py b/fincept-qt/scripts/news_nlp.py
index 864db7550..df0146c2b 100644
--- a/fincept-qt/scripts/news_nlp.py
+++ b/fincept-qt/scripts/news_nlp.py
@@ -345,56 +345,109 @@ def cluster_semantic(headlines_json):
}
+# Finance keyword lexicon — doubles as the VADER lexicon nudge and the offline
+# fallback scorer. Weights are valences on VADER's [-4, 4] scale.
+_FINANCE_POSITIVE = {
+ "surge": 3.0, "soar": 3.2, "skyrocket": 3.5, "breakthrough": 3.0, "boom": 2.8,
+ "rally": 2.5, "gain": 2.0, "gains": 2.0, "rise": 1.8, "jump": 2.5,
+ "jumps": 2.5, "climb": 2.0, "rebound": 2.2, "boost": 2.0, "beat": 2.2,
+ "beats": 2.2, "exceed": 2.0, "outperform": 2.5, "upgrade": 2.5, "profit": 1.8,
+ "growth": 1.8, "recover": 2.0, "record": 1.5, "strong": 1.5, "robust": 1.5,
+ "bullish": 3.0, "optimism": 1.8, "milestone": 1.5, "approval": 1.8, "deal": 1.2,
+}
+_FINANCE_NEGATIVE = {
+ "crash": -3.5, "plunge": -3.2, "collapse": -3.5, "meltdown": -3.5, "bankruptcy": -3.8,
+ "fall": -1.8, "drop": -2.0, "decline": -2.0, "tumble": -2.5, "slump": -2.5,
+ "miss": -2.0, "misses": -2.0, "fail": -2.2, "recession": -2.8, "crisis": -2.5,
+ "sanction": -2.0, "tariff": -1.8, "escalat": -1.5, "layoff": -2.2, "layoffs": -2.2,
+ "downgrade": -2.5, "fraud": -3.5, "scandal": -2.8, "selloff": -2.5, "default": -2.5,
+ "lawsuit": -1.8, "probe": -1.5, "weak": -1.5, "loss": -1.5, "deficit": -1.2,
+ "fear": -1.5, "threat": -1.5, "warning": -1.5, "bearish": -3.0, "halt": -1.5,
+}
+
+# Integer-weighted view used by the keyword fallback scorer (and confidence).
+_KW_POSITIVE = {k: max(1, int(round(abs(v) / 1.6))) for k, v in _FINANCE_POSITIVE.items()}
+_KW_NEGATIVE = {k: max(1, int(round(abs(v) / 1.6))) for k, v in _FINANCE_NEGATIVE.items()}
+
+_VADER = None
+_VADER_TRIED = False
+
+
+def _get_vader():
+ """Lazily build a finance-tuned VADER analyzer; None if unavailable."""
+ global _VADER, _VADER_TRIED
+ if _VADER_TRIED:
+ return _VADER
+ _VADER_TRIED = True
+ try:
+ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
+ analyzer = SentimentIntensityAnalyzer()
+ analyzer.lexicon.update(_FINANCE_POSITIVE)
+ analyzer.lexicon.update(_FINANCE_NEGATIVE)
+ _VADER = analyzer
+ except Exception:
+ _VADER = None
+ return _VADER
+
+
+def _keyword_signals(text):
+ """Finance keyword hit counts (used for fallback scoring and confidence)."""
+ pos = sum(w for p, w in _KW_POSITIVE.items() if p in text)
+ neg = sum(w for p, w in _KW_NEGATIVE.items() if p in text)
+ return pos, neg
+
+
+def _label_from_score(score):
+ if score >= 0.15:
+ return "BULLISH"
+ if score <= -0.15:
+ return "BEARISH"
+ return "NEUTRAL"
+
+
def analyze_sentiment_batch(headlines_json):
- """Batch sentiment analysis with confidence scores."""
+ """Batch sentiment analysis with confidence scores.
+
+ Prefers VADER (finance-tuned) when ``vaderSentiment`` is installed; otherwise
+ falls back to the offline keyword scorer. Output schema is stable across both
+ engines; ``engine`` reports which path ran."""
try:
articles = json.loads(headlines_json) if isinstance(headlines_json, str) else headlines_json
except json.JSONDecodeError:
return {"success": False, "error": "Invalid JSON"}
- positives = {
- "surge": 3, "soar": 3, "skyrocket": 3, "breakthrough": 3, "boom": 3,
- "record high": 3, "rally": 2, "gain": 2, "rise": 2, "jump": 2,
- "climb": 2, "rebound": 2, "boost": 2, "beat": 2, "exceed": 2,
- "upgrade": 2, "profit": 2, "growth": 2, "recover": 2, "victory": 2,
- "ceasefire": 2, "strong": 1, "robust": 1, "bullish": 1, "optimism": 1,
- "milestone": 1, "positive": 1, "success": 1, "approval": 1, "deal": 1,
- }
- negatives = {
- "crash": 3, "plunge": 3, "collapse": 3, "devastat": 3, "catastroph": 3,
- "invasion": 3, "war crime": 3, "bankruptcy": 3, "meltdown": 3,
- "fall": 2, "drop": 2, "decline": 2, "tumble": 2, "slump": 2, "miss": 2,
- "fail": 2, "recession": 2, "crisis": 2, "conflict": 2, "attack": 2,
- "sanction": 2, "tariff": 2, "escalat": 2, "layoff": 2, "downgrade": 2,
- "fraud": 2, "scandal": 2, "disaster": 2, "weak": 1, "loss": 1,
- "deficit": 1, "fear": 1, "threat": 1, "warning": 1, "bearish": 1,
- "volatile": 1, "uncertain": 1, "ban": 1, "suspend": 1,
- }
+ analyzer = _get_vader()
+ engine = "vader" if analyzer else "lexicon"
results = []
for article in articles:
text = (article.get("headline", "") + " " + article.get("summary", "")).lower()
- pos_score = sum(w for p, w in positives.items() if p in text)
- neg_score = sum(w for p, w in negatives.items() if p in text)
+ pos_score, neg_score = _keyword_signals(text)
total = pos_score + neg_score
- net = pos_score - neg_score
-
- if total == 0:
- sentiment = "NEUTRAL"
- score = 0.0
- confidence = 0.2
- elif net >= 2:
- sentiment = "BULLISH"
- score = min(net / max(total, 1), 1.0)
- confidence = min(0.4 + total * 0.05, 0.95)
- elif net <= -2:
- sentiment = "BEARISH"
- score = max(net / max(total, 1), -1.0)
- confidence = min(0.4 + total * 0.05, 0.95)
+
+ if analyzer is not None:
+ score = analyzer.polarity_scores(text)["compound"] # -1..1
+ sentiment = _label_from_score(score)
+ if sentiment == "NEUTRAL":
+ confidence = round(min(0.2 + abs(score) * 0.8, 0.4), 3)
+ else:
+ confidence = round(min(0.45 + abs(score) * 0.45 + total * 0.02, 0.97), 3)
else:
- sentiment = "NEUTRAL"
- score = net / max(total, 1)
- confidence = 0.3
+ net = pos_score - neg_score
+ if total == 0:
+ sentiment, score, confidence = "NEUTRAL", 0.0, 0.2
+ elif net >= 2:
+ sentiment = "BULLISH"
+ score = min(net / max(total, 1), 1.0)
+ confidence = min(0.4 + total * 0.05, 0.95)
+ elif net <= -2:
+ sentiment = "BEARISH"
+ score = max(net / max(total, 1), -1.0)
+ confidence = min(0.4 + total * 0.05, 0.95)
+ else:
+ sentiment = "NEUTRAL"
+ score = net / max(total, 1)
+ confidence = 0.3
results.append({
"id": article.get("id", ""),
@@ -412,6 +465,7 @@ def analyze_sentiment_batch(headlines_json):
return {
"success": True,
+ "engine": engine,
"results": results,
"aggregate": {"bullish": bull, "bearish": bear, "neutral": neut},
"overall_score": round(sum(r["score"] for r in results) / max(len(results), 1), 3),
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index ca8409273..89cddf0df 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -445,6 +445,32 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
}, Qt::QueuedConnection);
});
+ // Equity Research "BUY/SELL" → reuse the Equity Trading order ticket without
+ // 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) {
+ const QString symbol = d.value("symbol").toString();
+ if (symbol.isEmpty())
+ return;
+ const QString exchange = d.value("exchange").toString();
+ const QStringList match_exchanges = d.value("match_exchanges").toStringList();
+ const bool is_buy = d.value("is_buy").toBool();
+ const double price = d.value("price").toDouble();
+ QMetaObject::invokeMethod(
+ this,
+ [this, symbol, exchange, match_exchanges, is_buy, price]() {
+ if (locked_ || !dock_router_)
+ return;
+ const QString id = QStringLiteral("equity_trading");
+ if (!dock_router_->screen_widget(id))
+ dock_router_->materialize_now(id); // create hidden, don't raise
+ if (auto* trading = qobject_cast<screens::EquityTradingScreen*>(dock_router_->screen_widget(id)))
+ trading->open_external_order_ticket(symbol, exchange, match_exchanges, is_buy, price);
+ },
+ Qt::QueuedConnection);
+ });
+
// ── Keyboard shortcuts via ActionRegistry (Phase 4) ───────────────────────
//
// Every global action is now defined once in core/actions/builtin_actions.cpp
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 4ea38d353..1598c1173 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -682,7 +682,7 @@ int main(int argc, char* argv[]) {
log.set_tag_level(tag, lvl_map.value(level));
}
}
- LOG_INFO("App", "Fincept Terminal v4.0.3 starting...");
+ LOG_INFO("App", "Fincept Terminal v4.1.0 starting...");
LOG_INFO("App", QString("TLS backend: %1 (available: %2)")
.arg(QSslSocket::activeBackend(),
QSslSocket::availableBackends().join(", ")));
@@ -975,30 +975,15 @@ int main(int argc, char* argv[]) {
}
if (!recovered) {
+ // Single primary window by default — see the matching no-setup
+ // path below for the full rationale. Extra windows stay an
+ // explicit user action ("New Window" / Ctrl+Shift+N / tear-off).
const QList<int> saved_ids =
fincept::SessionManager::instance().load_window_ids();
- const int max_windows = static_cast<int>(QGuiApplication::screens().size());
-
- if (saved_ids.isEmpty()) {
- auto* window = new fincept::WindowFrame(0);
- window->setAttribute(Qt::WA_DeleteOnClose);
- window->show();
- } else {
- const int count = std::min(static_cast<int>(saved_ids.size()), max_windows);
- for (int i = 0; i < count; ++i) {
- auto* w = new fincept::WindowFrame(saved_ids[i]);
- w->setAttribute(Qt::WA_DeleteOnClose);
- w->show();
- }
- if (count < saved_ids.size()) {
- QList<int> trimmed = saved_ids.mid(0, count);
- fincept::SessionManager::instance().save_window_ids(trimmed);
- LOG_INFO("App", QString("Clamped %1 saved windows to %2 (available screens)")
- .arg(saved_ids.size()).arg(count));
- }
- if (count > 1)
- LOG_INFO("App", QString("Restored %1 window(s) from last session").arg(count));
- }
+ const int primary_id = saved_ids.isEmpty() ? 0 : saved_ids.first();
+ auto* window = new fincept::WindowFrame(primary_id);
+ window->setAttribute(Qt::WA_DeleteOnClose);
+ window->show();
}
// Wire new-window handler + Launchpad surface now that the
@@ -1038,36 +1023,23 @@ int main(int argc, char* argv[]) {
recovered = dlg.was_restored();
}
- // Restore the set of windows from last session. saved_ids is the complete
- // set written by closeEvent (including the primary). If empty (first run),
- // create a single primary window. Clamp to the number of available screens
- // so a 3-monitor layout doesn't stack 3 windows on 1 screen after the user
- // disconnects external displays.
+ // Restore a SINGLE primary window at startup. The previous session may
+ // have had several windows spread across multiple monitors, but auto-
+ // reopening all of them surprised multi-monitor users — every launch
+ // popped a second terminal on the second screen. Opening additional
+ // windows stays an EXPLICIT action (toolbar "New Window", Ctrl+Shift+N,
+ // the Launchpad button, tear-off), consistent with the single-instance
+ // relaunch policy in wire_app_lifecycle(). We reopen the lowest saved
+ // window_id (the primary) so its geometry + dock layout come back; the
+ // user spawns extra windows on demand. closeEvent self-heals the saved
+ // id set to the surviving windows, so this converges to [primary] cleanly.
if (!recovered) {
const QList<int> saved_ids =
fincept::SessionManager::instance().load_window_ids();
- const int max_windows = static_cast<int>(QGuiApplication::screens().size());
-
- if (saved_ids.isEmpty()) {
- auto* primary = new fincept::WindowFrame(0);
- primary->setAttribute(Qt::WA_DeleteOnClose);
- primary->show();
- } else {
- const int count = std::min(static_cast<int>(saved_ids.size()), max_windows);
- for (int i = 0; i < count; ++i) {
- auto* w = new fincept::WindowFrame(saved_ids[i]);
- w->setAttribute(Qt::WA_DeleteOnClose);
- w->show();
- }
- if (count < saved_ids.size()) {
- QList<int> trimmed = saved_ids.mid(0, count);
- fincept::SessionManager::instance().save_window_ids(trimmed);
- LOG_INFO("App", QString("Clamped %1 saved windows to %2 (available screens)")
- .arg(saved_ids.size()).arg(count));
- }
- if (count > 1)
- LOG_INFO("App", QString("Restored %1 window(s) from last session").arg(count));
- }
+ const int primary_id = saved_ids.isEmpty() ? 0 : saved_ids.first();
+ auto* primary = new fincept::WindowFrame(primary_id);
+ primary->setAttribute(Qt::WA_DeleteOnClose);
+ primary->show();
}
// Wire new-window handler + Launchpad surface — see wire_app_lifecycle()
diff --git a/fincept-qt/src/mcp/McpClient.cpp b/fincept-qt/src/mcp/McpClient.cpp
index 3d7faf631..3ce42052d 100644
--- a/fincept-qt/src/mcp/McpClient.cpp
+++ b/fincept-qt/src/mcp/McpClient.cpp
@@ -168,7 +168,7 @@ Result<QJsonObject> McpClient::initialize() {
QJsonObject client_info;
client_info["name"] = "FinceptTerminal";
- client_info["version"] = "4.0.3";
+ client_info["version"] = "4.1.0";
params["clientInfo"] = client_info;
QJsonObject capabilities;
diff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cpp
index 2f23ceb3f..804dab978 100644
--- a/fincept-qt/src/mcp/McpInit.cpp
+++ b/fincept-qt/src/mcp/McpInit.cpp
@@ -167,7 +167,7 @@ void initialize_all_tools() {
// gov-data — 10 government providers (US Treasury/Congress, France, HK, UK, Australia, ...)
provider.register_tools(tools::get_gov_data_tools());
- // equity-research — symbol search, load, financials, technicals, peers, news, talipp, sentiment
+ // equity-research — symbol search, load, financials, technicals, peers, news, sentiment
provider.register_tools(tools::get_equity_research_tools());
// workspace — monitors, windows, panels, layouts, snapshots, symbol groups, actions, command-bar
diff --git a/fincept-qt/src/mcp/ToolSelfTest.cpp b/fincept-qt/src/mcp/ToolSelfTest.cpp
index b208d884b..0a1cb2f01 100644
--- a/fincept-qt/src/mcp/ToolSelfTest.cpp
+++ b/fincept-qt/src/mcp/ToolSelfTest.cpp
@@ -92,7 +92,7 @@ std::vector<EvalCase> corpus() {
// ── equity research ──
{"pull the latest financial statements for Apple", {"get_equity_financials", "edgar_get_financials"}},
{"what is the analyst sentiment on NVDA", {"get_equity_sentiment"}},
- {"show technical indicators for the SPY", {"get_equity_technicals", "compute_equity_talipp"}},
+ {"show technical indicators for the SPY", {"get_equity_technicals"}},
{"who are the peer companies of Microsoft", {"get_equity_peers"}},
// ── SEC EDGAR ──
diff --git a/fincept-qt/src/mcp/tools/EquityResearchTools.cpp b/fincept-qt/src/mcp/tools/EquityResearchTools.cpp
index 1eecee716..a2c6c8d94 100644
--- a/fincept-qt/src/mcp/tools/EquityResearchTools.cpp
+++ b/fincept-qt/src/mcp/tools/EquityResearchTools.cpp
@@ -1,6 +1,6 @@
// EquityResearchTools.cpp — Tools that drive the Equity Research screen.
//
-// 12 tools in category "equity-research":
+// 10 tools in category "equity-research":
// 1. search_equity_symbols
// 2. load_equity_symbol — combined quote + info + historical
// 3. get_equity_quote — quote only (price/change/vol)
@@ -10,9 +10,7 @@
// 7. get_equity_technicals — indicators + overall signal
// 8. get_equity_peers — peer-group comparison
// 9. get_equity_news — recent news articles for a symbol
-// 10. compute_equity_talipp — run a talipp indicator (generic)
-// 11. list_equity_talipp_indicators — talipp indicator catalog (sync)
-// 12. get_equity_sentiment — MarketSentimentService snapshot
+// 10. get_equity_sentiment — MarketSentimentService snapshot
//
// EquityResearchService signals do NOT carry a per-call request_id; most
// carry the symbol (or indicator) so we filter by that. Concurrent calls
@@ -250,46 +248,6 @@ QJsonObject sentiment_to_json(const services::equity::MarketSentimentSnapshot& s
};
}
-// Hand-curated talipp catalogue mirrored from EquityTalippTab::categories().
-// Kept in this TU to avoid pulling the UI header into the tools layer.
-struct TalippEntry { const char* id; const char* label; const char* data_type; const char* category; };
-static const TalippEntry kTalipp[] = {
- // trend
- {"sma","SMA","prices","trend"}, {"ema","EMA","prices","trend"}, {"wma","WMA","prices","trend"},
- {"dema","DEMA","prices","trend"}, {"tema","TEMA","prices","trend"}, {"hma","HMA","prices","trend"},
- {"kama","KAMA","prices","trend"}, {"alma","ALMA","prices","trend"}, {"t3","T3","prices","trend"},
- {"zlema","ZLEMA","prices","trend"},
- // trend advanced
- {"adx","ADX","ohlcv","trend_advanced"}, {"aroon","Aroon","ohlcv","trend_advanced"},
- {"ichimoku","Ichimoku","ohlcv","trend_advanced"}, {"parabolic_sar","Parabolic SAR","ohlcv","trend_advanced"},
- {"supertrend","SuperTrend","ohlcv","trend_advanced"},
- // momentum
- {"rsi","RSI","prices","momentum"}, {"macd","MACD","prices","momentum"},
- {"stoch","Stochastic","ohlcv","momentum"}, {"stoch_rsi","StochRSI","prices","momentum"},
- {"cci","CCI","ohlcv","momentum"}, {"roc","ROC","prices","momentum"},
- {"tsi","TSI","prices","momentum"}, {"williams","Williams %R","ohlcv","momentum"},
- // volatility
- {"atr","ATR","ohlcv","volatility"}, {"bb","Bollinger Bands","prices","volatility"},
- {"keltner","Keltner Channels","ohlcv","volatility"}, {"donchian","Donchian Channels","ohlcv","volatility"},
- {"chandelier_stop","Chandelier Stop","ohlcv","volatility"}, {"natr","NATR","ohlcv","volatility"},
- // volume
- {"obv","OBV","ohlcv","volume"}, {"vwap","VWAP","ohlcv","volume"},
- {"vwma","VWMA","ohlcv","volume"}, {"mfi","MFI","ohlcv","volume"},
- {"chaikin_osc","Chaikin Osc","ohlcv","volume"}, {"force_index","Force Index","ohlcv","volume"},
- // specialized
- {"ao","Awesome Osc","ohlcv","specialized"}, {"accu_dist","Accum/Dist","ohlcv","specialized"},
- {"bop","Balance of Pwr","ohlcv","specialized"}, {"chop","CHOP","ohlcv","specialized"},
- {"coppock_curve","Coppock Curve","prices","specialized"}, {"dpo","DPO","prices","specialized"},
- {"emv","EMV","ohlcv","specialized"}, {"ibs","IBS","ohlcv","specialized"},
- {"kst","KST","prices","specialized"}, {"kvo","KVO","ohlcv","specialized"},
- {"mass_index","Mass Index","ohlcv","specialized"}, {"mcginley","McGinley","prices","specialized"},
- {"mean_dev","Mean Dev","prices","specialized"}, {"smma","SMMA","prices","specialized"},
- {"sobv","Smoothed OBV","ohlcv","specialized"}, {"stc","STC","prices","specialized"},
- {"std_dev","Std Dev","prices","specialized"}, {"trix","TRIX","prices","specialized"},
- {"ttm","TTM Squeeze","ohlcv","specialized"}, {"uo","Ultimate Osc","ohlcv","specialized"},
- {"vtx","Vortex","ohlcv","specialized"}, {"zigzag","ZigZag","ohlcv","specialized"},
-};
-
} // namespace
std::vector<ToolDef> get_equity_research_tools() {
@@ -646,92 +604,7 @@ std::vector<ToolDef> get_equity_research_tools() {
tools.push_back(std::move(t));
}
- // ── 10. compute_equity_talipp ───────────────────────────────────────
- {
- ToolDef t;
- t.name = "compute_equity_talipp";
- t.description = "Compute a talipp technical indicator over historical data for a symbol.";
- t.category = "equity-research";
- t.default_timeout_ms = kDefaultTimeoutMs;
- t.input_schema = ToolSchemaBuilder()
- .string("symbol", "Ticker symbol").required().length(1, 32)
- .string("indicator", "Indicator id (use list_equity_talipp_indicators)").required().length(1, 32)
- .object("params", "Indicator-specific params (e.g. {period: 20})")
- .string("period", "Historical period").default_str("2y").length(1, 8)
- .build();
- t.async_handler = [](const QJsonObject& args, ToolContext ctx,
- std::shared_ptr<QPromise<ToolResult>> promise) {
- const QString sym = args["symbol"].toString().toUpper();
- const QString ind = args["indicator"].toString();
- const QJsonObject params = args["params"].toObject();
- const QString period = args["period"].toString("2y");
-
- // Convert JSON params object → QVariantMap for the service API.
- QVariantMap pmap;
- for (auto it = params.constBegin(); it != params.constEnd(); ++it)
- pmap.insert(it.key(), it.value().toVariant());
-
- auto* svc = &services::equity::EquityResearchService::instance();
- AsyncDispatch::callback_to_promise(
- svc, std::move(ctx), promise,
- [svc, sym, ind, pmap, period](auto resolve) {
- auto* holder = new QObject(svc);
- QObject::connect(svc, &services::equity::EquityResearchService::talipp_result, holder,
- [ind, resolve, holder](QString got_ind, QVector<double> vs,
- QVector<qint64> ts) {
- if (got_ind != ind) return;
- QJsonArray values;
- for (double v : vs) values.append(v);
- QJsonArray timestamps;
- for (qint64 t : ts) timestamps.append(t);
- resolve(ToolResult::ok_data(QJsonObject{
- {"indicator", got_ind},
- {"values", values},
- {"timestamps", timestamps},
- {"count", static_cast<int>(vs.size())},
- }));
- holder->deleteLater();
- });
- QObject::connect(svc, &services::equity::EquityResearchService::error_occurred, holder,
- [resolve, holder](QString, QString msg) {
- resolve(ToolResult::fail(msg));
- holder->deleteLater();
- });
- svc->compute_talipp(sym, ind, pmap, period);
- });
- };
- tools.push_back(std::move(t));
- }
-
- // ── 11. list_equity_talipp_indicators ───────────────────────────────
- {
- ToolDef t;
- t.name = "list_equity_talipp_indicators";
- t.description = "List all talipp indicators (id, label, category, data_type: 'prices' or 'ohlcv').";
- t.category = "equity-research";
- t.input_schema = ToolSchemaBuilder()
- .string("category", "Optional category filter (trend, trend_advanced, momentum, volatility, volume, specialized)")
- .default_str("").length(0, 32)
- .build();
- t.handler = [](const QJsonObject& args) -> ToolResult {
- const QString filter = args["category"].toString();
- QJsonArray arr;
- for (const auto& e : kTalipp) {
- if (!filter.isEmpty() && filter != QString::fromUtf8(e.category))
- continue;
- arr.append(QJsonObject{
- {"id", QString::fromUtf8(e.id)},
- {"label", QString::fromUtf8(e.label)},
- {"data_type", QString::fromUtf8(e.data_type)},
- {"category", QString::fromUtf8(e.category)},
- });
- }
- return ToolResult::ok_data(arr);
- };
- tools.push_back(std::move(t));
- }
-
- // ── 12. get_equity_sentiment ────────────────────────────────────────
+ // ── 10. get_equity_sentiment ────────────────────────────────────────
{
ToolDef t;
t.name = "get_equity_sentiment";
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoWatchlist.cpp b/fincept-qt/src/screens/crypto_trading/CryptoWatchlist.cpp
index c9fb71f83..89bf1a6b2 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoWatchlist.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoWatchlist.cpp
@@ -1,6 +1,8 @@
// CryptoWatchlist.cpp — compact watchlist, 3-column, no horizontal scroll
#include "screens/crypto_trading/CryptoWatchlist.h"
+#include "core/symbol/SymbolDragSource.h"
+#include "core/symbol/SymbolRef.h"
#include "ui/theme/Theme.h"
#include <QHBoxLayout>
@@ -98,6 +100,29 @@ CryptoWatchlist::CryptoWatchlist(QWidget* parent) : QWidget(parent) {
connect(table_, &QTableWidget::cellClicked, this, &CryptoWatchlist::on_cell_clicked);
layout->addWidget(table_, 1);
+
+ // Drag-out: hold-and-drag a pair row to ship it to any drop target — drop
+ // it on the pushpin bar at the top to pin + broadcast it, matching the
+ // standalone Watchlist tab and the equity watchlist. The ref MUST carry
+ // asset_class="crypto", or CryptoTradingScreen::on_group_symbol_changed
+ // drops it as a non-crypto symbol. The provider reads the row under the
+ // cursor at drag-start (the mouse press selects it first); the symbol is
+ // the cell text (col 0), like on_cell_clicked. Group None: the pushpin chip
+ // owns the broadcast group, so the source group is irrelevant here.
+ symbol_dnd::installDragSource(table_->viewport(), [this]() -> SymbolRef {
+ if (!table_)
+ return {};
+ const int r = table_->currentRow();
+ if (r < 0)
+ return {};
+ auto* item = table_->item(r, 0);
+ if (!item || item->text().isEmpty())
+ return {};
+ SymbolRef ref;
+ ref.symbol = item->text();
+ ref.asset_class = QStringLiteral("crypto");
+ return ref;
+ });
}
void CryptoWatchlist::changeEvent(QEvent* event) {
diff --git a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
index a0cbd1806..c7db72ee0 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
@@ -5,38 +5,74 @@
#include "trading/AccountManager.h"
#include "trading/BrokerTopic.h"
#include "trading/DataStreamManager.h"
+#include "trading/UnifiedTrading.h"
#include "ui/theme/Theme.h"
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QFormLayout>
+#include <QHBoxLayout>
#include <QHeaderView>
#include <QJsonObject>
#include <QLabel>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QStringList>
namespace fincept::screens::widgets {
+namespace {
+// Build a MARKET SELL / CNC order that exits the full quantity of one holding.
+trading::UnifiedOrder make_square_off_order(const trading::BrokerHolding& h) {
+ trading::UnifiedOrder o;
+ o.symbol = h.symbol;
+ o.exchange = h.exchange;
+ o.side = trading::OrderSide::Sell;
+ o.order_type = trading::OrderType::Market;
+ o.quantity = h.quantity;
+ // Market sells need a reference price for the paper engine to fill; the live
+ // market path ignores price. Fall back to avg cost if no LTP is cached yet.
+ o.price = h.ltp > 0 ? h.ltp : h.avg_price;
+ o.product_type = trading::ProductType::Delivery; // CNC / delivery
+ o.validity = QStringLiteral("DAY");
+ return o;
+}
+} // namespace
+
BrokerHoldingsWidget::BrokerHoldingsWidget(const QJsonObject& cfg, QWidget* parent)
: BaseWidget(tr("HOLDINGS"), parent) {
auto* vl = content_layout();
vl->setContentsMargins(8, 6, 8, 6);
vl->setSpacing(4);
+ auto* header_row = new QHBoxLayout();
+ header_row->setContentsMargins(0, 0, 0, 0);
+ header_row->setSpacing(6);
header_hint_ = new QLabel("—");
- vl->addWidget(header_hint_);
+ header_row->addWidget(header_hint_, 1);
+ square_off_all_btn_ = new QPushButton(tr("SQUARE OFF ALL"));
+ square_off_all_btn_->setCursor(Qt::PointingHandCursor);
+ square_off_all_btn_->setEnabled(false);
+ connect(square_off_all_btn_, &QPushButton::clicked, this, &BrokerHoldingsWidget::square_off_all);
+ header_row->addWidget(square_off_all_btn_, 0);
+ vl->addLayout(header_row);
- table_ = new QTableWidget(0, 5, this);
- table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Qty"), tr("Avg"), tr("LTP"), tr("P&L %")});
+ // Columns: Symbol, Qty, Avg, LTP, P&L %, and a trailing per-row exit button.
+ table_ = new QTableWidget(0, 6, this);
+ table_->setHorizontalHeaderLabels(
+ {tr("Symbol"), tr("Qty"), tr("Avg"), tr("LTP"), tr("P&L %"), QString()});
table_->verticalHeader()->setVisible(false);
table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
table_->setSelectionMode(QAbstractItemView::NoSelection);
table_->setShowGrid(false);
- table_->horizontalHeader()->setStretchLastSection(true);
+ table_->horizontalHeader()->setStretchLastSection(false);
table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setSectionResizeMode(5, QHeaderView::ResizeToContents);
vl->addWidget(table_, 1);
set_configurable(true);
@@ -117,7 +153,9 @@ void BrokerHoldingsWidget::hideEvent(QHideEvent* e) {
}
void BrokerHoldingsWidget::populate(const QVector<trading::BrokerHolding>& rows) {
+ holdings_ = rows;
table_->setRowCount(rows.size());
+ int sellable = 0;
for (int i = 0; i < rows.size(); ++i) {
const auto& h = rows[i];
auto* sym = new QTableWidgetItem(h.symbol);
@@ -137,7 +175,21 @@ void BrokerHoldingsWidget::populate(const QVector<trading::BrokerHolding>& rows)
table_->setItem(i, 2, avg);
table_->setItem(i, 3, ltp);
table_->setItem(i, 4, pnl_pct);
+
+ // Per-row exit button — squares off this single holding. Capture the
+ // holding by value so a click always acts on the row it was drawn for.
+ auto* exit_btn = new QPushButton(tr("Exit"), table_);
+ exit_btn->setCursor(Qt::PointingHandCursor);
+ exit_btn->setProperty("holdingsExit", true);
+ const bool can_sell = h.quantity > 0;
+ exit_btn->setEnabled(can_sell);
+ connect(exit_btn, &QPushButton::clicked, this,
+ [this, h]() { square_off_holding(h); });
+ table_->setCellWidget(i, 5, exit_btn);
+ if (can_sell)
+ ++sellable;
}
+ square_off_all_btn_->setEnabled(sellable > 0);
set_loading(false);
}
@@ -173,6 +225,74 @@ QDialog* BrokerHoldingsWidget::make_config_dialog(QWidget* parent) {
return dlg;
}
+void BrokerHoldingsWidget::square_off_holding(const trading::BrokerHolding& h) {
+ if (account_id_.isEmpty() || h.quantity <= 0)
+ return;
+
+ const auto answer = QMessageBox::warning(
+ this, tr("Square Off Holding"),
+ tr("Place a MARKET SELL order for %1 %2 (CNC)?")
+ .arg(QString::number(h.quantity, 'f', 0), h.symbol),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes)
+ return;
+
+ const auto resp = trading::UnifiedTrading::instance().place_order(account_id_, make_square_off_order(h));
+ if (resp.success) {
+ QMessageBox::information(this, tr("Square Off Holding"),
+ tr("Sell order placed for %1 (order %2).").arg(h.symbol, resp.order_id));
+ } else {
+ QMessageBox::critical(this, tr("Square Off Holding"),
+ tr("Failed to square off %1: %2").arg(h.symbol, resp.message));
+ }
+}
+
+void BrokerHoldingsWidget::square_off_all() {
+ if (account_id_.isEmpty())
+ return;
+
+ // Snapshot sellable holdings now — the holdings subscription may refresh
+ // (and rebuild the table) while the confirm dialog / orders are in flight.
+ QVector<trading::BrokerHolding> targets;
+ for (const auto& h : holdings_)
+ if (h.quantity > 0)
+ targets.append(h);
+ if (targets.isEmpty()) {
+ QMessageBox::information(this, tr("Square Off All Holdings"), tr("No holdings to square off."));
+ return;
+ }
+
+ const auto answer = QMessageBox::warning(
+ this, tr("Square Off All Holdings"),
+ tr("This will place MARKET SELL orders to exit ALL %1 holding(s) in this account.\n\n"
+ "Positions are NOT affected. Continue?")
+ .arg(targets.size()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes)
+ return;
+
+ int placed = 0;
+ QStringList failures;
+ for (const auto& h : targets) {
+ const auto resp = trading::UnifiedTrading::instance().place_order(account_id_, make_square_off_order(h));
+ if (resp.success)
+ ++placed;
+ else
+ failures.append(QStringLiteral("%1 (%2)").arg(h.symbol, resp.message));
+ }
+
+ if (failures.isEmpty()) {
+ QMessageBox::information(this, tr("Square Off All Holdings"),
+ tr("Placed %1 sell order(s).").arg(placed));
+ } else {
+ QMessageBox::warning(this, tr("Square Off All Holdings"),
+ tr("Placed %1 order(s). %2 failed:\n%3")
+ .arg(placed)
+ .arg(failures.size())
+ .arg(failures.join(QStringLiteral("\n"))));
+ }
+}
+
void BrokerHoldingsWidget::on_theme_changed() {
apply_styles();
}
@@ -185,9 +305,21 @@ void BrokerHoldingsWidget::apply_styles() {
"QTableWidget{background:transparent;color:%1;gridline-color:%2;font-size:10px;border:none;}"
"QHeaderView::section{background:%3;color:%4;border:none;border-bottom:1px solid %2;"
"padding:2px 4px;font-size:9px;font-weight:bold;}"
- "QTableWidget::item{padding:2px 4px;}")
+ "QTableWidget::item{padding:2px 4px;}"
+ "QPushButton[holdingsExit=\"true\"]{color:%5;background:transparent;border:1px solid %5;"
+ "border-radius:2px;padding:0 6px;font-size:9px;font-weight:bold;}"
+ "QPushButton[holdingsExit=\"true\"]:hover{color:%6;background:%5;}"
+ "QPushButton[holdingsExit=\"true\"]:disabled{color:%2;border-color:%2;}")
.arg(ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM(), ui::colors::BG_RAISED(),
- ui::colors::TEXT_TERTIARY()));
+ ui::colors::TEXT_TERTIARY(), ui::colors::NEGATIVE(), ui::colors::BG_BASE()));
+
+ if (square_off_all_btn_)
+ square_off_all_btn_->setStyleSheet(
+ QString("QPushButton{color:%1;background:transparent;border:1px solid %1;border-radius:2px;"
+ "padding:2px 8px;font-size:9px;font-weight:bold;}"
+ "QPushButton:hover{color:%2;background:%1;}"
+ "QPushButton:disabled{color:%3;border-color:%3;}")
+ .arg(ui::colors::NEGATIVE(), ui::colors::BG_BASE(), ui::colors::BORDER_DIM()));
}
void BrokerHoldingsWidget::retranslateUi() {
diff --git a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.h b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.h
index 6404f39c8..a9a8d8a08 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.h
@@ -12,6 +12,8 @@
#include <QTableWidget>
#include <QVector>
+class QPushButton;
+
namespace fincept::screens::widgets {
class BrokerHoldingsWidget : public BaseWidget {
@@ -37,11 +39,21 @@ class BrokerHoldingsWidget : public BaseWidget {
void hub_unsubscribe_all();
QString resolve_account_id() const;
+ // Square-off: places MARKET SELL / CNC orders for holdings of THIS account
+ // only — never touches positions. `square_off_all` exits every holding;
+ // `square_off_holding` exits one row.
+ void square_off_all();
+ void square_off_holding(const trading::BrokerHolding& h);
+
QString account_id_;
QString broker_id_;
QTableWidget* table_ = nullptr;
QLabel* header_hint_ = nullptr;
+ QPushButton* square_off_all_btn_ = nullptr;
+
+ // Last holdings rendered — source of truth for square-off actions.
+ QVector<trading::BrokerHolding> holdings_;
bool hub_active_ = false;
};
diff --git a/fincept-qt/src/screens/data_sources/connectors/AlternativeData.cpp b/fincept-qt/src/screens/data_sources/connectors/AlternativeData.cpp
index d93351bd9..7e6a91596 100644
--- a/fincept-qt/src/screens/data_sources/connectors/AlternativeData.cpp
+++ b/fincept-qt/src/screens/data_sources/connectors/AlternativeData.cpp
@@ -1,5 +1,5 @@
-// Alternative Data connectors (9): RavenPack, Bloomberg Second Measure, SafeGraph, Orbital Insight,
-// Refinitiv Tick History, Earnest Research, Thinknum, Revelio Labs, Adanos Market Sentiment
+// Alternative Data connectors (10): RavenPack, Bloomberg Second Measure, SafeGraph, Orbital Insight,
+// Refinitiv Tick History, Earnest Research, Thinknum, Revelio Labs, Adanos Market Sentiment, NewsAPI
#include "screens/data_sources/ConnectorRegistry.h"
namespace fincept::screens::datasources {
@@ -178,6 +178,18 @@ static QVector<ConnectorConfig> alt_data_configs() {
true,
{{"apiKey", "API Key", FieldType::Password, "sk_live_...", true, "", {}},
{"defaultUniverse", "Default Universe (optional)", FieldType::Text, "AAPL,MSFT,NVDA", false, "", {}}}},
+
+ {"newsapi",
+ "NewsAPI.org",
+ "newsapi",
+ Category::AlternativeData,
+ "N",
+ "#C4302B",
+ "Stock and company news from 150k+ sources via newsapi.org. Optional provider in the Equity "
+ "Research → News tab; get a free key at newsapi.org.",
+ true,
+ true,
+ {{"apiKey", "API Key", FieldType::Password, "your-newsapi-key", true, "", {}}}},
};
}
diff --git a/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp b/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp
index 53bb820d3..768e55893 100644
--- a/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityAnalysisTab.cpp
@@ -1,33 +1,171 @@
// src/screens/equity_research/EquityAnalysisTab.cpp
+//
+// The "Analysis" sub-tab interprets StockInfo into decisions rather than
+// listing it (Overview already lists). Layout: a full-width analyst
+// price-target gauge (hero) above a 3×2 grid of color-coded verdict cards
+// (Valuation, Financial Health, Cash Flow, Profitability, Growth, Risk).
+//
+// Every rating is computed purely from StockInfo — no extra backend calls.
+// The heuristics are absolute screening signals (not sector-adjusted), so
+// rationales stay factual. i18n follows the existing pattern: static labels
+// register an English source key in i18n_labels_; dynamic verdict/hero text
+// is rebuilt via tr() each time on_info_loaded() runs, and retranslateUi()
+// replays it on a language change.
#include "screens/equity_research/EquityAnalysisTab.h"
#include "services/equity/EquityResearchService.h"
#include "ui/theme/Theme.h"
#include <QEvent>
+#include <QFontMetrics>
#include <QFrame>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QPainter>
+#include <QPolygonF>
#include <QScrollArea>
#include <QVBoxLayout>
+#include <algorithm>
+
namespace fincept::screens {
-// ── Panel helpers ─────────────────────────────────────────────────────────────
-// Class methods (not anonymous-ns free functions) so they can register the
-// title and card labels with the per-instance i18n map. Every call site
-// passes a stable English source string declared via QT_TR_NOOP so lupdate
-// sees it; retranslateUi() iterates the map and re-applies tr().
+// ── AnalysisPriceTargetGauge ───────────────────────────────────────────────────
+// Custom-painted low—mean—high track with a clamped "now" marker. No Q_OBJECT
+// (no signals/slots) so it needs no moc and is safe in the unity build. Numeric
+// labels are drawn directly; the big price / upside / recommendation text lives
+// in sibling QLabels owned by the tab.
+class AnalysisPriceTargetGauge : public QWidget {
+ public:
+ explicit AnalysisPriceTargetGauge(QWidget* parent = nullptr) : QWidget(parent) {
+ setMinimumHeight(88);
+ setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ }
+
+ void set_data(double low, double mean, double high, double price, const QString& cur) {
+ low_ = low;
+ mean_ = mean;
+ high_ = high;
+ price_ = price;
+ cur_ = cur;
+ has_data_ = (low > 0.0 || mean > 0.0 || high > 0.0);
+ update();
+ }
+
+ void clear_data() {
+ has_data_ = false;
+ update();
+ }
+
+ protected:
+ void paintEvent(QPaintEvent*) override {
+ if (!has_data_)
+ return;
+
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing, true);
+
+ const double w = width();
+ const double margin = 12.0;
+ double x_left = margin;
+ double x_right = w - margin;
+ if (x_right <= x_left + 1.0) {
+ x_left = 2.0;
+ x_right = w - 2.0;
+ }
+ const double y_track = std::round(height() * 0.52);
+ const double track_h = 6.0;
+
+ auto x_for = [&](double v) -> double {
+ if (high_ <= low_)
+ return (x_left + x_right) / 2.0;
+ double t = (v - low_) / (high_ - low_);
+ t = std::clamp(t, 0.0, 1.0);
+ return x_left + (t * (x_right - x_left));
+ };
+
+ // Base track.
+ QRectF track(x_left, y_track - (track_h / 2.0), x_right - x_left, track_h);
+ p.setPen(Qt::NoPen);
+ p.setBrush(QColor(ui::colors::BORDER_MED()));
+ p.drawRoundedRect(track, 3, 3);
+
+ // Filled portion from low → now (visualizes where price sits in range).
+ if (price_ > 0.0) {
+ double xp = x_for(price_);
+ QRectF fill(x_left, y_track - (track_h / 2.0), xp - x_left, track_h);
+ p.setBrush(QColor(ui::colors::CYAN()));
+ p.drawRoundedRect(fill, 3, 3);
+ }
+
+ QFont small = font();
+ small.setPointSizeF(std::max(10.0, small.pointSizeF() + 1.0));
+ p.setFont(small);
+ const QFontMetrics fm(small);
+
+ auto money = [&](double v) -> QString {
+ const int dec = v >= 1000.0 ? 0 : 2;
+ return cur_ + QString::number(v, 'f', dec);
+ };
+
+ // Mean tick + label (above the track).
+ if (mean_ > 0.0) {
+ double xm = x_for(mean_);
+ p.setPen(QPen(QColor(ui::colors::AMBER()), 1.5));
+ p.drawLine(QPointF(xm, y_track - 9), QPointF(xm, y_track + 9));
+ const QString t = QStringLiteral("mean ") + money(mean_);
+ double tx = std::clamp(xm - (fm.horizontalAdvance(t) / 2.0), x_left, x_right - fm.horizontalAdvance(t));
+ p.setPen(QColor(ui::colors::AMBER()));
+ p.drawText(QPointF(tx, y_track - 12), t);
+ }
+
+ // Low / high labels (below the track ends).
+ p.setPen(QColor(ui::colors::TEXT_TERTIARY()));
+ if (low_ > 0.0)
+ p.drawText(QPointF(x_left, y_track + 20), QStringLiteral("low ") + money(low_));
+ if (high_ > 0.0) {
+ const QString t = QStringLiteral("high ") + money(high_);
+ p.drawText(QPointF(x_right - fm.horizontalAdvance(t), y_track + 20), t);
+ }
+
+ // "Now" marker: downward triangle sitting on the track.
+ if (price_ > 0.0) {
+ double xp = x_for(price_);
+ QPolygonF tri;
+ tri << QPointF(xp - 5, y_track - 10) << QPointF(xp + 5, y_track - 10) << QPointF(xp, y_track - 2);
+ p.setPen(Qt::NoPen);
+ p.setBrush(QColor(ui::colors::TEXT_PRIMARY()));
+ p.drawPolygon(tri);
+ // Beyond-range hint.
+ if (high_ > low_ && (price_ < low_ || price_ > high_)) {
+ p.setPen(QColor(ui::colors::WARNING()));
+ const QString hint = price_ < low_ ? QStringLiteral("▼") : QStringLiteral("▲");
+ p.drawText(QPointF(xp - (fm.horizontalAdvance(hint) / 2.0), y_track - 14), hint);
+ }
+ }
+ }
+
+ private:
+ double low_ = 0.0;
+ double mean_ = 0.0;
+ double high_ = 0.0;
+ double price_ = 0.0;
+ QString cur_ = QStringLiteral("$");
+ bool has_data_ = false;
+};
+
+// ── Panel helper ───────────────────────────────────────────────────────────────
+// Class method (not a free function) so it can register the title label with the
+// per-instance i18n map. retranslateUi() iterates the map and re-applies tr().
QFrame* EquityAnalysisTab::make_panel_(const char* title_key, const QString& accent_color) {
auto* f = new QFrame;
f->setStyleSheet(QString("QFrame { background:%1; border:1px solid %2; border-radius:4px; }")
.arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
auto* vl = new QVBoxLayout(f);
- vl->setContentsMargins(16, 14, 16, 16);
- vl->setSpacing(14);
+ vl->setContentsMargins(18, 16, 18, 18);
+ vl->setSpacing(12);
- // Header row: accent bar + title
auto* hdr = new QWidget(nullptr);
hdr->setStyleSheet(QString("background:transparent; border:0; border-bottom:2px solid %1;").arg(accent_color));
auto* hl = new QHBoxLayout(hdr);
@@ -40,7 +178,7 @@ QFrame* EquityAnalysisTab::make_panel_(const char* title_key, const QString& acc
hl->addWidget(bar);
auto* lbl = new QLabel(tr(title_key));
- lbl->setStyleSheet(QString("color:%1; font-size:11px; font-weight:700; letter-spacing:1px; "
+ lbl->setStyleSheet(QString("color:%1; font-size:13px; font-weight:700; letter-spacing:1px; "
"background:transparent; border:0;")
.arg(accent_color));
hl->addWidget(lbl);
@@ -51,29 +189,7 @@ QFrame* EquityAnalysisTab::make_panel_(const char* title_key, const QString& acc
return f;
}
-QWidget* EquityAnalysisTab::make_card_(const char* label_key, QLabel*& val_out, const QString& val_color) {
- auto* w = new QWidget(nullptr);
- w->setStyleSheet("background:transparent;");
- auto* vl = new QVBoxLayout(w);
- vl->setContentsMargins(0, 0, 0, 0);
- vl->setSpacing(3);
-
- auto* lbl = new QLabel(tr(label_key));
- lbl->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; letter-spacing:1px; "
- "background:transparent; border:0;")
- .arg(ui::colors::TEXT_TERTIARY()));
- vl->addWidget(lbl);
- i18n_labels_.insert(lbl, label_key);
-
- val_out = new QLabel(QStringLiteral("—"));
- val_out->setStyleSheet(QString("color:%1; font-size:16px; font-weight:700; font-family:monospace; "
- "background:transparent; border:0;")
- .arg(val_color));
- vl->addWidget(val_out);
- return w;
-}
-
-// ── EquityAnalysisTab ─────────────────────────────────────────────────────────
+// ── EquityAnalysisTab ───────────────────────────────────────────────────────────
EquityAnalysisTab::EquityAnalysisTab(QWidget* parent) : QWidget(parent) {
build_ui();
@@ -99,68 +215,46 @@ void EquityAnalysisTab::build_ui() {
scroll->setStyleSheet("background:transparent; border:0;");
auto* content = new QWidget(this);
- auto* grid = new QGridLayout(content);
- grid->setContentsMargins(12, 12, 12, 12);
+ auto* root = new QVBoxLayout(content);
+ root->setContentsMargins(12, 12, 12, 12);
+ root->setSpacing(10);
+
+ // Hero (full width).
+ root->addWidget(build_hero_());
+
+ // Verdict grid: 3 columns × 2 rows.
+ auto* grid_host = new QWidget(nullptr);
+ grid_host->setStyleSheet("background:transparent;");
+ auto* grid = new QGridLayout(grid_host);
+ grid->setContentsMargins(0, 0, 0, 0);
grid->setSpacing(10);
- // ── Panel 1: FINANCIAL HEALTH (top-left, orange) ──────────────────────────
- auto* health_panel = make_panel_(QT_TR_NOOP("FINANCIAL HEALTH"), ui::colors::AMBER);
- auto* hl_vl = static_cast<QVBoxLayout*>(health_panel->layout());
- auto* health_grid = new QGridLayout;
- health_grid->setSpacing(16);
- health_grid->addWidget(make_card_(QT_TR_NOOP("TOTAL CASH"), cash_val_, ui::colors::POSITIVE), 0, 0);
- health_grid->addWidget(make_card_(QT_TR_NOOP("TOTAL DEBT"), debt_val_, ui::colors::NEGATIVE), 0, 1);
- health_grid->addWidget(make_card_(QT_TR_NOOP("FREE CASHFLOW"), fcf_val_, "#22d3ee"), 1, 0);
- health_grid->addWidget(make_card_(QT_TR_NOOP("OPERATING CF"), ocf_val_, "#60a5fa"), 1, 1);
- hl_vl->addLayout(health_grid);
- hl_vl->addStretch();
-
- // ── Panel 2: ENTERPRISE VALUE (top-right, cyan) ───────────────────────────
- auto* ev_panel = make_panel_(QT_TR_NOOP("ENTERPRISE VALUE"), "#22d3ee");
- auto* ev_vl = static_cast<QVBoxLayout*>(ev_panel->layout());
- auto* ev_grid = new QGridLayout;
- ev_grid->setSpacing(16);
- ev_grid->addWidget(make_card_(QT_TR_NOOP("ENTERPRISE VALUE"), ev_val_, "#eab308"), 0, 0);
- ev_grid->addWidget(make_card_(QT_TR_NOOP("EV/REVENUE"), ev_rev_val_, "#22d3ee"), 0, 1);
- ev_grid->addWidget(make_card_(QT_TR_NOOP("EV/EBITDA"), ev_ebitda_val_, "#22d3ee"), 1, 0);
- ev_grid->addWidget(make_card_(QT_TR_NOOP("BOOK VALUE"), book_val_, ui::colors::TEXT_PRIMARY), 1, 1);
- ev_vl->addLayout(ev_grid);
- ev_vl->addStretch();
-
- // ── Panel 3: REVENUE & PROFITS (bottom-left, green) ───────────────────────
- auto* rev_panel = make_panel_(QT_TR_NOOP("REVENUE & PROFITS"), ui::colors::POSITIVE);
- auto* rev_vl = static_cast<QVBoxLayout*>(rev_panel->layout());
- auto* rev_grid = new QGridLayout;
- rev_grid->setSpacing(16);
- rev_grid->addWidget(make_card_(QT_TR_NOOP("TOTAL REVENUE"), rev_val_, ui::colors::POSITIVE), 0, 0);
- rev_grid->addWidget(make_card_(QT_TR_NOOP("REVENUE/SHARE"), rev_share_val_, "#22d3ee"), 0, 1);
- rev_grid->addWidget(make_card_(QT_TR_NOOP("GROSS PROFITS"), gp_val_, ui::colors::POSITIVE), 1, 0);
- rev_grid->addWidget(make_card_(QT_TR_NOOP("EBITDA MARGINS"), ebitda_m_val_, "#eab308"), 1, 1);
- rev_vl->addLayout(rev_grid);
- rev_vl->addStretch();
-
- // ── Panel 4: KEY RATIOS (bottom-right, purple) ────────────────────────────
- auto* ratios_panel = make_panel_(QT_TR_NOOP("KEY RATIOS"), "#a855f7");
- auto* rat_vl = static_cast<QVBoxLayout*>(ratios_panel->layout());
- auto* rat_grid = new QGridLayout;
- rat_grid->setSpacing(16);
- rat_grid->addWidget(make_card_(QT_TR_NOOP("P/E RATIO"), pe_val_, ui::colors::TEXT_PRIMARY), 0, 0);
- rat_grid->addWidget(make_card_(QT_TR_NOOP("PEG RATIO"), peg_val_, ui::colors::TEXT_PRIMARY), 0, 1);
- rat_grid->addWidget(make_card_(QT_TR_NOOP("ROE"), roe_val_, ui::colors::POSITIVE), 1, 0);
- rat_grid->addWidget(make_card_(QT_TR_NOOP("ROA"), roa_val_, ui::colors::POSITIVE), 1, 1);
- rat_grid->addWidget(make_card_(QT_TR_NOOP("BETA"), beta_val_, "#22d3ee"), 2, 0);
- rat_grid->addWidget(make_card_(QT_TR_NOOP("SHORT RATIO"), short_rat_val_, ui::colors::NEGATIVE), 2, 1);
- rat_vl->addLayout(rat_grid);
- rat_vl->addStretch();
-
- grid->addWidget(health_panel, 0, 0);
- grid->addWidget(ev_panel, 0, 1);
- grid->addWidget(rev_panel, 1, 0);
- grid->addWidget(ratios_panel, 1, 1);
- grid->setRowStretch(0, 1);
- grid->setRowStretch(1, 1);
+ struct DimSpec {
+ Dim dim;
+ const char* title;
+ QString accent;
+ };
+ const DimSpec specs[kDimCount] = {
+ {kValuation, QT_TR_NOOP("VALUATION"), ui::colors::CYAN()},
+ {kHealth, QT_TR_NOOP("FINANCIAL HEALTH"), ui::colors::AMBER()},
+ {kCashFlow, QT_TR_NOOP("CASH FLOW"), ui::colors::INFO()},
+ {kProfitability, QT_TR_NOOP("PROFITABILITY"), ui::colors::POSITIVE()},
+ {kGrowth, QT_TR_NOOP("GROWTH"), QStringLiteral("#a855f7")},
+ {kRisk, QT_TR_NOOP("RISK / SENTIMENT"), ui::colors::WARNING()},
+ };
+
+ for (int i = 0; i < kDimCount; ++i) {
+ auto* panel = make_panel_(specs[i].title, specs[i].accent);
+ cards_[specs[i].dim] = build_verdict_card_(panel, specs[i].title, specs[i].accent);
+ grid->addWidget(panel, i / 3, i % 3);
+ }
grid->setColumnStretch(0, 1);
grid->setColumnStretch(1, 1);
+ grid->setColumnStretch(2, 1);
+ grid->setRowStretch(0, 1);
+ grid->setRowStretch(1, 1);
+
+ root->addWidget(grid_host, 1);
scroll->setWidget(content);
auto* ol = new QVBoxLayout(this);
@@ -168,6 +262,106 @@ void EquityAnalysisTab::build_ui() {
ol->addWidget(scroll);
}
+QFrame* EquityAnalysisTab::build_hero_() {
+ auto* panel = make_panel_(QT_TR_NOOP("ANALYST PRICE TARGET"), ui::colors::AMBER());
+ auto* vl = static_cast<QVBoxLayout*>(panel->layout());
+
+ // Headline row: now-price + upside, with the recommendation badge on the right.
+ auto* head = new QWidget(nullptr);
+ head->setStyleSheet("background:transparent;");
+ auto* hl = new QHBoxLayout(head);
+ hl->setContentsMargins(0, 0, 0, 0);
+ hl->setSpacing(12);
+
+ auto* left = new QVBoxLayout;
+ left->setSpacing(2);
+ hero_price_ = new QLabel(QStringLiteral("—"));
+ hero_price_->setStyleSheet(QString("color:%1; font-size:26px; font-weight:800; font-family:monospace; "
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ hero_upside_ = new QLabel(QStringLiteral("—"));
+ hero_upside_->setStyleSheet(QString("color:%1; font-size:15px; font-weight:700;"
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ left->addWidget(hero_price_);
+ left->addWidget(hero_upside_);
+ hl->addLayout(left);
+ hl->addStretch();
+
+ auto* right = new QVBoxLayout;
+ right->setSpacing(2);
+ hero_reco_ = new QLabel(QStringLiteral("—"));
+ hero_reco_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ hero_reco_->setStyleSheet(QString("color:%1; font-size:18px; font-weight:800; letter-spacing:1px; "
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ hero_count_ = new QLabel(QString());
+ hero_count_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ hero_count_->setStyleSheet(QString("color:%1; font-size:13px; font-weight:600; "
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ right->addWidget(hero_reco_);
+ right->addWidget(hero_count_);
+ hl->addLayout(right);
+
+ vl->addWidget(head);
+
+ gauge_ = new AnalysisPriceTargetGauge;
+ vl->addWidget(gauge_);
+
+ // No-coverage fallback (hidden unless there is no analyst data).
+ hero_empty_ = new QLabel(tr("No analyst coverage available."));
+ hero_empty_->setStyleSheet(QString("color:%1; font-size:13px; font-style:italic; "
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ hero_empty_->setVisible(false);
+ vl->addWidget(hero_empty_);
+ i18n_labels_.insert(hero_empty_, QT_TR_NOOP("No analyst coverage available."));
+
+ return panel;
+}
+
+EquityAnalysisTab::VerdictCard EquityAnalysisTab::build_verdict_card_(QWidget* panel, const char* title_key,
+ const QString& /*accent*/) {
+ VerdictCard card;
+ card.title_key = title_key;
+ auto* vl = static_cast<QVBoxLayout*>(panel->layout());
+
+ card.rating = new QLabel(QStringLiteral("—"));
+ card.rating->setStyleSheet(QString("color:%1; font-size:26px; font-weight:800; letter-spacing:1px; "
+ "background:transparent; border:0; padding:2px 0 6px 0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ vl->addWidget(card.rating);
+
+ // Metric lines grouped tightly together (their own box) so they read as a
+ // block rather than drifting apart at the panel's wider spacing.
+ auto* lines_box = new QWidget(nullptr);
+ lines_box->setStyleSheet("background:transparent;");
+ auto* lines_vl = new QVBoxLayout(lines_box);
+ lines_vl->setContentsMargins(0, 0, 0, 0);
+ lines_vl->setSpacing(6);
+ for (auto& line : card.lines) {
+ line = new QLabel(QString());
+ line->setStyleSheet(QString("color:%1; font-size:15px; font-weight:600; font-family:monospace; "
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ lines_vl->addWidget(line);
+ }
+ vl->addWidget(lines_box);
+
+ card.rationale = new QLabel(QString());
+ card.rationale->setWordWrap(true);
+ card.rationale->setStyleSheet(QString("color:%1; font-size:13px; font-weight:500; line-height:140%; "
+ "background:transparent; border:0; padding-top:4px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ vl->addWidget(card.rationale);
+
+ vl->addStretch();
+ return card;
+}
+
+// ── Populate ────────────────────────────────────────────────────────────────────
+
void EquityAnalysisTab::on_info_loaded(services::equity::StockInfo info) {
if (info.symbol != current_symbol_)
return;
@@ -175,35 +369,345 @@ void EquityAnalysisTab::on_info_loaded(services::equity::StockInfo info) {
info_loaded_ = true;
loading_overlay_->hide_loading();
- const QString dash = QStringLiteral("—");
+ populate_hero_(info);
+
+ apply_verdict_(cards_[kValuation], assess_valuation_(info));
+ apply_verdict_(cards_[kHealth], assess_health_(info));
+ apply_verdict_(cards_[kCashFlow], assess_cashflow_(info));
+ apply_verdict_(cards_[kProfitability], assess_profitability_(info));
+ apply_verdict_(cards_[kGrowth], assess_growth_(info));
+ apply_verdict_(cards_[kRisk], assess_risk_(info));
+}
+
+void EquityAnalysisTab::populate_hero_(const services::equity::StockInfo& info) {
+ const bool has_targets = info.analyst_count > 0 && (info.target_mean > 0.0 || info.target_high > 0.0);
+
+ if (!has_targets) {
+ gauge_->clear_data();
+ gauge_->setVisible(false);
+ hero_price_->setText(info.current_price > 0.0 ? fmt_money(info.current_price) : QStringLiteral("—"));
+ hero_upside_->setVisible(false);
+ hero_reco_->setText(QStringLiteral("—"));
+ hero_reco_->setStyleSheet(QString("color:%1; font-size:18px; font-weight:800; letter-spacing:1px; "
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ hero_count_->setText(QString());
+ hero_empty_->setVisible(true);
+ return;
+ }
- // Financial Health
- cash_val_->setText(fmt_large(info.total_cash));
- debt_val_->setText(fmt_large(info.total_debt));
- fcf_val_->setText(fmt_large(info.free_cashflow));
- ocf_val_->setText(fmt_large(info.operating_cashflow));
+ hero_empty_->setVisible(false);
+ hero_upside_->setVisible(true);
+ gauge_->setVisible(true);
+ gauge_->set_data(info.target_low, info.target_mean, info.target_high, info.current_price, cur_symbol_());
+
+ hero_price_->setText(info.current_price > 0.0 ? fmt_money(info.current_price) + tr(" now") : QStringLiteral("—"));
+
+ if (info.current_price > 0.0 && info.target_mean > 0.0) {
+ const double up = (info.target_mean - info.current_price) / info.current_price * 100.0;
+ const QString sign = up >= 0.0 ? QStringLiteral("+") : QStringLiteral("-");
+ hero_upside_->setText(QString("%1%2% ").arg(sign).arg(std::abs(up), 0, 'f', 1) + tr("to mean target"));
+ hero_upside_->setStyleSheet(QString("color:%1; font-size:15px; font-weight:700;"
+ "background:transparent; border:0;")
+ .arg(up >= 0.0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ } else {
+ hero_upside_->setText(tr("target range shown"));
+ hero_upside_->setStyleSheet(QString("color:%1; font-size:15px; font-weight:700;"
+ "background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ }
- // Enterprise Value
- ev_val_->setText(fmt_large(info.enterprise_value));
- ev_rev_val_->setText(fmt(info.ev_to_revenue));
- ev_ebitda_val_->setText(fmt(info.ev_to_ebitda, 1));
- book_val_->setText(info.book_value > 0 ? QString("$%1").arg(info.book_value, 0, 'f', 2) : dash);
+ // Recommendation badge.
+ const QString key = info.recommendation_key.toLower();
+ QString label;
+ Tone tone = Tone::Neutral;
+ if (key == "strong_buy") {
+ label = tr("STRONG BUY");
+ tone = Tone::Good;
+ } else if (key == "buy") {
+ label = tr("BUY");
+ tone = Tone::Good;
+ } else if (key == "hold" || key == "neutral") {
+ label = tr("HOLD");
+ tone = Tone::Caution;
+ } else if (key == "underperform" || key == "sell") {
+ label = tr("SELL");
+ tone = Tone::Bad;
+ } else if (key == "strong_sell") {
+ label = tr("STRONG SELL");
+ tone = Tone::Bad;
+ } else {
+ label = key.isEmpty() ? QStringLiteral("—") : info.recommendation_key.toUpper();
+ tone = Tone::Neutral;
+ }
+ hero_reco_->setText(label);
+ hero_reco_->setStyleSheet(QString("color:%1; font-size:18px; font-weight:800; letter-spacing:1px; "
+ "background:transparent; border:0;")
+ .arg(color_for_(tone)));
+
+ QString count = tr("%n analyst(s)", "", info.analyst_count);
+ if (info.recommendation_mean > 0.0)
+ count = QString("%1 · ").arg(QString::number(info.recommendation_mean, 'f', 1)) + count;
+ hero_count_->setText(count);
+}
- // Revenue & Profits
- rev_val_->setText(fmt_large(info.total_revenue));
- rev_share_val_->setText(info.revenue_per_share > 0 ? QString("$%1").arg(info.revenue_per_share, 0, 'f', 2) : dash);
- gp_val_->setText(fmt_large(info.gross_profits));
- ebitda_m_val_->setText(fmt_pct(info.ebitda_margins));
+void EquityAnalysisTab::apply_verdict_(const VerdictCard& card, const Verdict& v) {
+ card.rating->setText(tr(v.rating_key));
+ card.rating->setStyleSheet(QString("color:%1; font-size:26px; font-weight:800; letter-spacing:1px; "
+ "background:transparent; border:0; padding:2px 0 6px 0;")
+ .arg(color_for_(v.tone)));
- // Key Ratios
- pe_val_->setText(info.pe_ratio > 0 ? fmt(info.pe_ratio, 1) : dash);
- peg_val_->setText(info.peg_ratio > 0 ? fmt(info.peg_ratio) : dash);
- roe_val_->setText(fmt_pct(info.roe));
- roa_val_->setText(fmt_pct(info.roa));
- beta_val_->setText(fmt(info.beta));
- short_rat_val_->setText(info.short_ratio > 0 ? fmt(info.short_ratio) : dash);
+ const QString lines[3] = {v.line1, v.line2, v.line3};
+ for (int i = 0; i < 3; ++i) {
+ card.lines[i]->setText(lines[i]);
+ card.lines[i]->setVisible(!lines[i].isEmpty());
+ }
+ card.rationale->setText(v.rationale);
+ card.rationale->setVisible(!v.rationale.isEmpty());
}
+// ── Assessment ────────────────────────────────────────────────────────────────
+// Pure functions of StockInfo. Thresholds are deliberately simple, transparent,
+// and market-cap/sector-agnostic — screening signals, not investment advice.
+
+EquityAnalysisTab::Verdict EquityAnalysisTab::assess_valuation_(const services::equity::StockInfo& s) const {
+ Verdict v;
+ const bool has_pe = s.pe_ratio > 0.0;
+ const bool has_peg = s.peg_ratio > 0.0;
+ if (!has_pe && !has_peg && s.forward_pe <= 0.0) {
+ v.rating_key = QT_TR_NOOP("N/A");
+ v.tone = Tone::NA;
+ v.rationale = tr("No earnings-based valuation available (may be unprofitable).");
+ return v;
+ }
+
+ // Prefer PEG (growth-adjusted); fall back to raw P/E.
+ int score = 0; // -1 expensive, 0 fair, +1 cheap
+ if (has_peg) {
+ if (s.peg_ratio < 1.0)
+ score = 1;
+ else if (s.peg_ratio <= 2.0)
+ score = 0;
+ else
+ score = -1;
+ } else if (has_pe) {
+ if (s.pe_ratio < 15.0)
+ score = 1;
+ else if (s.pe_ratio <= 30.0)
+ score = 0;
+ else
+ score = -1;
+ }
+
+ if (score > 0) {
+ v.rating_key = QT_TR_NOOP("UNDERVALUED");
+ v.tone = Tone::Good;
+ } else if (score == 0) {
+ v.rating_key = QT_TR_NOOP("FAIRLY VALUED");
+ v.tone = Tone::Caution;
+ } else {
+ v.rating_key = QT_TR_NOOP("EXPENSIVE");
+ v.tone = Tone::Bad;
+ }
+
+ QString pe_line = QStringLiteral("P/E ") + (has_pe ? fmt(s.pe_ratio, 1) : QStringLiteral("—"));
+ if (s.forward_pe > 0.0) {
+ const QString arrow = (has_pe && s.forward_pe < s.pe_ratio) ? QStringLiteral(" ↓") : QString();
+ pe_line += QString(" fwd %1%2").arg(fmt(s.forward_pe, 1), arrow);
+ }
+ v.line1 = pe_line;
+ v.line2 = QStringLiteral("PEG ") + (has_peg ? fmt(s.peg_ratio, 2) : QStringLiteral("—"));
+ if (s.price_to_book > 0.0)
+ v.line2 += QString(" · P/B %1").arg(fmt(s.price_to_book, 1));
+ if (s.ev_to_ebitda > 0.0)
+ v.line3 = QString("EV/EBITDA %1").arg(fmt(s.ev_to_ebitda, 1));
+
+ if (has_pe && s.forward_pe > 0.0 && s.forward_pe < s.pe_ratio)
+ v.rationale = tr("Forward P/E below trailing — earnings expected to grow.");
+ else if (score < 0)
+ v.rationale = tr("Trades at a premium; priced for growth or quality.");
+ else if (score > 0)
+ v.rationale = tr("Low multiple relative to earnings/growth.");
+ else
+ v.rationale = tr("Valuation in line with broad-market norms.");
+ return v;
+}
+
+EquityAnalysisTab::Verdict EquityAnalysisTab::assess_health_(const services::equity::StockInfo& s) const {
+ Verdict v;
+ if (s.total_cash <= 0.0 && s.total_debt <= 0.0) {
+ v.rating_key = QT_TR_NOOP("N/A");
+ v.tone = Tone::NA;
+ v.rationale = tr("Balance-sheet cash/debt not reported.");
+ return v;
+ }
+
+ const double net = s.total_cash - s.total_debt;
+ v.line1 = tr("Cash %1").arg(fmt_large(s.total_cash));
+ v.line2 = tr("Debt %1").arg(fmt_large(s.total_debt));
+ v.line3 = tr("Net %1%2").arg(net >= 0.0 ? QStringLiteral("+") : QStringLiteral("")).arg(fmt_large(net));
+
+ if (net > 0.0) {
+ v.rating_key = QT_TR_NOOP("STRONG");
+ v.tone = Tone::Good;
+ v.rationale = tr("Net cash position — more cash than total debt.");
+ } else {
+ const double ratio = s.total_cash > 0.0 ? s.total_debt / s.total_cash : 999.0;
+ if (ratio < 2.0) {
+ v.rating_key = QT_TR_NOOP("STABLE");
+ v.tone = Tone::Caution;
+ v.rationale = tr("Manageable leverage relative to cash on hand.");
+ } else {
+ v.rating_key = QT_TR_NOOP("STRETCHED");
+ v.tone = Tone::Bad;
+ v.rationale = tr("Debt is high relative to available cash.");
+ }
+ }
+ return v;
+}
+
+EquityAnalysisTab::Verdict EquityAnalysisTab::assess_cashflow_(const services::equity::StockInfo& s) const {
+ Verdict v;
+ if (s.free_cashflow == 0.0 && s.operating_cashflow == 0.0) {
+ v.rating_key = QT_TR_NOOP("N/A");
+ v.tone = Tone::NA;
+ v.rationale = tr("Cash-flow figures not reported.");
+ return v;
+ }
+
+ v.line1 = tr("FCF %1").arg(fmt_large(s.free_cashflow));
+ v.line2 = tr("Op CF %1").arg(fmt_large(s.operating_cashflow));
+ if (s.total_revenue > 0.0)
+ v.line3 = tr("FCF margin %1").arg(fmt_pct(s.free_cashflow / s.total_revenue));
+
+ if (s.free_cashflow > 0.0) {
+ v.rating_key = QT_TR_NOOP("STRONG");
+ v.tone = Tone::Good;
+ v.rationale = tr("Generates positive free cash flow after capex.");
+ } else if (s.operating_cashflow > 0.0) {
+ v.rating_key = QT_TR_NOOP("REINVESTING");
+ v.tone = Tone::Caution;
+ v.rationale = tr("Operating cash is positive but FCF is negative (heavy investment).");
+ } else {
+ v.rating_key = QT_TR_NOOP("BURNING CASH");
+ v.tone = Tone::Bad;
+ v.rationale = tr("Operations are consuming cash.");
+ }
+ return v;
+}
+
+EquityAnalysisTab::Verdict EquityAnalysisTab::assess_profitability_(const services::equity::StockInfo& s) const {
+ Verdict v;
+ const bool any = s.roe != 0.0 || s.roa != 0.0 || s.profit_margins != 0.0;
+ if (!any) {
+ v.rating_key = QT_TR_NOOP("N/A");
+ v.tone = Tone::NA;
+ v.rationale = tr("Profitability ratios not reported.");
+ return v;
+ }
+
+ v.line1 = QString("ROE %1 ROA %2").arg(fmt_pct(s.roe), fmt_pct(s.roa));
+ v.line2 = tr("Net margin %1").arg(fmt_pct(s.profit_margins));
+ if (s.operating_margins != 0.0)
+ v.line3 = tr("Oper. margin %1").arg(fmt_pct(s.operating_margins));
+
+ if (s.profit_margins < 0.0) {
+ v.rating_key = QT_TR_NOOP("LOSS-MAKING");
+ v.tone = Tone::Bad;
+ v.rationale = tr("Currently unprofitable on a net basis.");
+ } else if (s.roe > 0.20 && s.profit_margins > 0.15) {
+ v.rating_key = QT_TR_NOOP("EXCELLENT");
+ v.tone = Tone::Good;
+ v.rationale = tr("High returns on equity and strong net margins.");
+ } else if (s.roe > 0.10 || s.profit_margins > 0.08) {
+ v.rating_key = QT_TR_NOOP("SOLID");
+ v.tone = Tone::Good;
+ v.rationale = tr("Healthy, consistent profitability.");
+ } else {
+ v.rating_key = QT_TR_NOOP("THIN");
+ v.tone = Tone::Caution;
+ v.rationale = tr("Profitable, but margins and returns are slim.");
+ }
+ return v;
+}
+
+EquityAnalysisTab::Verdict EquityAnalysisTab::assess_growth_(const services::equity::StockInfo& s) const {
+ Verdict v;
+ if (s.revenue_growth == 0.0 && s.earnings_growth == 0.0) {
+ v.rating_key = QT_TR_NOOP("N/A");
+ v.tone = Tone::NA;
+ v.rationale = tr("Growth rates not reported.");
+ return v;
+ }
+
+ v.line1 = tr("Revenue %1").arg(fmt_pct(s.revenue_growth));
+ v.line2 = tr("Earnings %1").arg(fmt_pct(s.earnings_growth));
+
+ const double g = s.revenue_growth != 0.0 ? s.revenue_growth : s.earnings_growth;
+ if (g > 0.20) {
+ v.rating_key = QT_TR_NOOP("HIGH GROWTH");
+ v.tone = Tone::Good;
+ v.rationale = tr("Top line expanding rapidly.");
+ } else if (g >= 0.05) {
+ v.rating_key = QT_TR_NOOP("MODERATE");
+ v.tone = Tone::Caution;
+ v.rationale = tr("Steady single-to-double-digit growth.");
+ } else if (g >= -0.02) {
+ v.rating_key = QT_TR_NOOP("FLAT");
+ v.tone = Tone::Neutral;
+ v.rationale = tr("Revenue is roughly unchanged year over year.");
+ } else {
+ v.rating_key = QT_TR_NOOP("DECLINING");
+ v.tone = Tone::Bad;
+ v.rationale = tr("Revenue is contracting year over year.");
+ }
+ return v;
+}
+
+EquityAnalysisTab::Verdict EquityAnalysisTab::assess_risk_(const services::equity::StockInfo& s) const {
+ Verdict v;
+ const bool has_beta = s.beta != 0.0;
+ if (!has_beta && s.short_pct_of_float == 0.0 && s.week52_high <= 0.0) {
+ v.rating_key = QT_TR_NOOP("N/A");
+ v.tone = Tone::NA;
+ v.rationale = tr("Risk metrics not reported.");
+ return v;
+ }
+
+ if (has_beta)
+ v.line1 = tr("Beta %1").arg(fmt(s.beta, 2));
+ if (s.short_pct_of_float > 0.0)
+ v.line2 = tr("Short %1 of float").arg(fmt_pct(s.short_pct_of_float));
+ if (s.week52_high > s.week52_low && s.current_price > 0.0) {
+ const double pos = (s.current_price - s.week52_low) / (s.week52_high - s.week52_low) * 100.0;
+ v.line3 = tr("52w position %1%").arg(QString::number(std::clamp(pos, 0.0, 100.0), 'f', 0));
+ }
+
+ const bool high_short = s.short_pct_of_float > 0.10;
+ if ((has_beta && s.beta > 1.5) || high_short) {
+ v.rating_key = QT_TR_NOOP("ELEVATED");
+ v.tone = Tone::Bad;
+ v.rationale = high_short ? tr("Heavy short interest signals bearish positioning.")
+ : tr("High beta — amplifies market moves.");
+ } else if (has_beta && s.beta > 1.0) {
+ v.rating_key = QT_TR_NOOP("MODERATE");
+ v.tone = Tone::Caution;
+ v.rationale = tr("Moves roughly in line with, or above, the market.");
+ } else if (has_beta) {
+ v.rating_key = QT_TR_NOOP("LOW");
+ v.tone = Tone::Good;
+ v.rationale = tr("Lower volatility than the broad market.");
+ } else {
+ // No beta — don't claim a volatility level we can't support.
+ v.rating_key = QT_TR_NOOP("MODERATE");
+ v.tone = Tone::Neutral;
+ v.rationale = tr("Beta unavailable; based on limited risk signals.");
+ }
+ return v;
+}
+
+// ── Formatting ────────────────────────────────────────────────────────────────
+
QString EquityAnalysisTab::fmt(double v, int decimals) const {
return v != 0.0 ? QString::number(v, 'f', decimals) : QStringLiteral("—");
}
@@ -211,8 +715,8 @@ QString EquityAnalysisTab::fmt(double v, int decimals) const {
QString EquityAnalysisTab::fmt_large(double v) {
if (v == 0.0)
return QStringLiteral("—");
- bool neg = v < 0;
- double a = std::abs(v);
+ const bool neg = v < 0;
+ const double a = std::abs(v);
QString s;
if (a >= 1e12)
s = QString("%1T").arg(a / 1e12, 0, 'f', 2);
@@ -229,22 +733,57 @@ QString EquityAnalysisTab::fmt_pct(double v) const {
return v != 0.0 ? QString("%1%").arg(v * 100.0, 0, 'f', 2) : QStringLiteral("—");
}
-// ── Re-translation ───────────────────────────────────────────────────────────
-// Walk the i18n_labels_ map (populated by make_panel_/make_card_) and re-apply
-// tr() to every registered label. Then replay cached info so value labels
-// pick up the localized em-dash / N/A placeholders too.
+QString EquityAnalysisTab::cur_symbol_() const {
+ const QString c = cached_info_.currency.toUpper();
+ if (c == "INR")
+ return QStringLiteral("₹");
+ if (c == "EUR")
+ return QStringLiteral("€");
+ if (c == "GBP")
+ return QStringLiteral("£");
+ if (c == "JPY")
+ return QStringLiteral("¥");
+ if (c.isEmpty() || c == "USD")
+ return QStringLiteral("$");
+ return c + QStringLiteral(" ");
+}
+
+QString EquityAnalysisTab::fmt_money(double v) const {
+ if (v == 0.0)
+ return QStringLiteral("—");
+ const int dec = std::abs(v) >= 1000.0 ? 0 : 2;
+ return cur_symbol_() + QString::number(v, 'f', dec);
+}
+
+QString EquityAnalysisTab::color_for_(Tone t) const {
+ switch (t) {
+ case Tone::Good:
+ return ui::colors::POSITIVE();
+ case Tone::Caution:
+ return ui::colors::AMBER();
+ case Tone::Bad:
+ return ui::colors::NEGATIVE();
+ case Tone::Neutral:
+ return ui::colors::TEXT_SECONDARY();
+ case Tone::NA:
+ default:
+ return ui::colors::TEXT_TERTIARY();
+ }
+}
+
+// ── Re-translation ──────────────────────────────────────────────────────────────
+// Re-apply tr() to static labels, then replay cached info so all dynamic
+// hero/verdict text picks up the new language too.
void EquityAnalysisTab::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange) {
+ if (event->type() == QEvent::LanguageChange)
retranslateUi();
- }
QWidget::changeEvent(event);
}
void EquityAnalysisTab::retranslateUi() {
- for (auto it = i18n_labels_.constBegin(); it != i18n_labels_.constEnd(); ++it) {
+ for (auto it = i18n_labels_.constBegin(); it != i18n_labels_.constEnd(); ++it)
it.key()->setText(tr(it.value()));
- }
if (info_loaded_)
on_info_loaded(cached_info_);
}
diff --git a/fincept-qt/src/screens/equity_research/EquityAnalysisTab.h b/fincept-qt/src/screens/equity_research/EquityAnalysisTab.h
index 12e65d752..4a77d8181 100644
--- a/fincept-qt/src/screens/equity_research/EquityAnalysisTab.h
+++ b/fincept-qt/src/screens/equity_research/EquityAnalysisTab.h
@@ -5,66 +5,106 @@
#include <QHash>
#include <QLabel>
+#include <QVector>
#include <QWidget>
+#include <array>
#include <cmath>
+#include <cstdint>
class QFrame;
namespace fincept::screens {
+// Custom-painted analyst price-target gauge (defined in the .cpp, no Q_OBJECT).
+class AnalysisPriceTargetGauge;
+
+// EquityAnalysisTab — the "Analysis" sub-tab of Equity Research.
+//
+// Unlike Overview (which lists raw fundamentals), this tab *interprets* the
+// same StockInfo into decisions: an analyst price-target gauge plus six
+// color-coded verdict cards. All ratings are computed purely from StockInfo —
+// no extra backend calls. Heuristics are absolute screening signals (not
+// sector-adjusted); rationales stay factual rather than prescriptive.
class EquityAnalysisTab : public QWidget {
Q_OBJECT
public:
explicit EquityAnalysisTab(QWidget* parent = nullptr);
void set_symbol(const QString& symbol);
- protected:
- void changeEvent(QEvent* event) override;
-
private slots:
void on_info_loaded(services::equity::StockInfo info);
+ protected:
+ void changeEvent(QEvent* event) override;
+
private:
+ // ── Verdict model ─────────────────────────────────────────────────────────
+ enum class Tone : std::uint8_t { Good, Caution, Bad, Neutral, NA };
+
+ struct Verdict {
+ const char* rating_key = "—"; ///< QT_TR_NOOP literal chosen at assess time
+ Tone tone = Tone::NA;
+ QString line1;
+ QString line2;
+ QString line3;
+ QString rationale; ///< already tr()'d at build time
+ };
+
+ // One verdict card's live labels (scaffolding built once in build_ui).
+ struct VerdictCard {
+ const char* title_key = nullptr;
+ QLabel* rating = nullptr;
+ std::array<QLabel*, 3> lines{nullptr, nullptr, nullptr};
+ QLabel* rationale = nullptr;
+ };
+
+ enum Dim : std::uint8_t { kValuation, kHealth, kCashFlow, kProfitability, kGrowth, kRisk, kDimCount };
+
+ // ── Build ───────────────────────────────────────────────────────────────
void build_ui();
+ QFrame* build_hero_();
+ VerdictCard build_verdict_card_(QWidget* parent_grid_cell, const char* title_key, const QString& accent);
void retranslateUi();
+
QFrame* make_panel_(const char* title_key, const QString& accent_color);
- QWidget* make_card_(const char* label_key, QLabel*& val_out, const QString& val_color);
+
+ // ── Populate ──────────────────────────────────────────────────────────────
+ void populate_hero_(const services::equity::StockInfo& info);
+ void apply_verdict_(const VerdictCard& card, const Verdict& v);
+
+ // ── Assessment (pure, from StockInfo) ──────────────────────────────────────
+ Verdict assess_valuation_(const services::equity::StockInfo& s) const;
+ Verdict assess_health_(const services::equity::StockInfo& s) const;
+ Verdict assess_cashflow_(const services::equity::StockInfo& s) const;
+ Verdict assess_profitability_(const services::equity::StockInfo& s) const;
+ Verdict assess_growth_(const services::equity::StockInfo& s) const;
+ Verdict assess_risk_(const services::equity::StockInfo& s) const;
+
+ // ── Formatting ─────────────────────────────────────────────────────────────
QString fmt(double v, int decimals = 2) const;
static QString fmt_large(double v);
- QString fmt_pct(double v) const;
+ QString fmt_pct(double v) const; ///< v is a fraction (0.31 → "31.00%")
+ QString fmt_money(double v) const; ///< currency-symbol prefixed price
+ QString cur_symbol_() const; ///< $/₹/€/£ from cached_info_.currency
+ QString color_for_(Tone t) const;
- QHash<QLabel*, const char*> i18n_labels_; ///< label → English source key for tr()
+ // ── State ──────────────────────────────────────────────────────────────────
+ QHash<QLabel*, const char*> i18n_labels_; ///< static label → English source key
services::equity::StockInfo cached_info_;
bool info_loaded_ = false;
-
QString current_symbol_;
- // Financial Health
- QLabel* cash_val_ = nullptr;
- QLabel* debt_val_ = nullptr;
- QLabel* fcf_val_ = nullptr;
- QLabel* ocf_val_ = nullptr;
-
- // Enterprise Value
- QLabel* ev_val_ = nullptr;
- QLabel* ev_rev_val_ = nullptr;
- QLabel* ev_ebitda_val_ = nullptr;
- QLabel* book_val_ = nullptr;
-
- // Revenue & Profits
- QLabel* rev_val_ = nullptr;
- QLabel* rev_share_val_ = nullptr;
- QLabel* gp_val_ = nullptr;
- QLabel* ebitda_m_val_ = nullptr;
-
- // Key Ratios
- QLabel* pe_val_ = nullptr;
- QLabel* peg_val_ = nullptr;
- QLabel* roe_val_ = nullptr;
- QLabel* roa_val_ = nullptr;
- QLabel* beta_val_ = nullptr;
- QLabel* short_rat_val_ = nullptr;
+ // Hero
+ AnalysisPriceTargetGauge* gauge_ = nullptr;
+ QLabel* hero_price_ = nullptr; ///< "$182.40 now"
+ QLabel* hero_upside_ = nullptr; ///< "+18.3% to mean target"
+ QLabel* hero_reco_ = nullptr; ///< recommendation badge
+ QLabel* hero_count_ = nullptr; ///< "34 analysts"
+ QLabel* hero_empty_ = nullptr; ///< "No analyst coverage" fallback
+
+ // Verdict cards (one per Dim)
+ std::array<VerdictCard, kDimCount> cards_{};
ui::LoadingOverlay* loading_overlay_ = nullptr;
};
diff --git a/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp b/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
index 9dc60c675..887333936 100644
--- a/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityNewsTab.cpp
@@ -9,6 +9,7 @@
#include <QHBoxLayout>
#include <QPushButton>
#include <QScrollArea>
+#include <QStandardItemModel>
#include <QUrl>
namespace fincept::screens {
@@ -24,13 +25,57 @@ void EquityNewsTab::set_symbol(const QString& symbol) {
return;
current_symbol_ = symbol;
news_loaded_ = false;
+ company_label_->setText(symbol);
+ refresh_provider_availability();
+ start_fetch();
+}
+
+// (Re)fetch the current symbol's news using the selected provider. Sole owner of
+// the news fetch — the screen no longer triggers it, so the dropdown is authoritative.
+void EquityNewsTab::start_fetch() {
+ if (current_symbol_.isEmpty())
+ return;
clear_cards();
count_label_->setText("");
- company_label_->setText(symbol);
status_label_->setText(tr("Loading news…"));
status_label_->show();
loading_overlay_->show_loading(tr("LOADING NEWS…"));
- services::equity::EquityResearchService::instance().fetch_news(symbol, 20);
+ using NP = services::equity::NewsProvider;
+ services::equity::EquityResearchService::instance().fetch_news(current_symbol_, 20,
+ use_newsapi_ ? NP::NewsApi : NP::Auto);
+}
+
+// Enable the "NewsAPI" item only when a key is configured in Data Sources; if it
+// was selected but the key went away, fall back to Auto.
+void EquityNewsTab::refresh_provider_availability() {
+ if (!provider_combo_)
+ return;
+ const bool avail = !services::equity::EquityResearchService::instance().configured_newsapi_key().isEmpty();
+ if (auto* model = qobject_cast<QStandardItemModel*>(provider_combo_->model())) {
+ if (auto* item = model->item(1)) {
+ item->setEnabled(avail);
+ item->setToolTip(avail ? QString() : tr("Add a NewsAPI key in the Data Sources tab"));
+ }
+ }
+ if (!avail && use_newsapi_) {
+ use_newsapi_ = false;
+ suppress_provider_signal_ = true;
+ provider_combo_->setCurrentIndex(0);
+ suppress_provider_signal_ = false;
+ }
+}
+
+QString EquityNewsTab::provider_key() const {
+ return use_newsapi_ ? QStringLiteral("newsapi") : QStringLiteral("auto");
+}
+
+void EquityNewsTab::set_provider_key(const QString& key) {
+ use_newsapi_ = (key == QLatin1String("newsapi"));
+ if (provider_combo_) {
+ suppress_provider_signal_ = true;
+ provider_combo_->setCurrentIndex(use_newsapi_ ? 1 : 0);
+ suppress_provider_signal_ = false;
+ }
}
void EquityNewsTab::build_ui() {
@@ -66,22 +111,39 @@ void EquityNewsTab::build_ui() {
hl->addStretch();
+ // ── Provider switch ─────────────────────────────────────────────────────────
+ // "NewsAPI" stays disabled until a key is configured in the Data Sources tab.
+ provider_combo_ = new QComboBox;
+ provider_combo_->addItem(tr("Auto (GNews → Yahoo)"));
+ provider_combo_->addItem(QStringLiteral("NewsAPI"));
+ provider_combo_->setToolTip(tr("News source"));
+ provider_combo_->setStyleSheet(
+ QString("QComboBox { background:%1; color:%2; border:1px solid %3; border-radius:3px; "
+ "padding:3px 8px; font-size:10px; font-weight:700; }"
+ "QComboBox::drop-down { border:0; width:14px; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2; border:1px solid %3; "
+ "selection-background-color:%4; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(),
+ ui::colors::BG_RAISED()));
+ connect(provider_combo_, qOverload<int>(&QComboBox::currentIndexChanged), this, [this](int idx) {
+ if (suppress_provider_signal_)
+ return;
+ use_newsapi_ = (idx == 1);
+ start_fetch();
+ });
+ hl->addWidget(provider_combo_);
+
refresh_btn_ = new QPushButton(tr("REFRESH"));
refresh_btn_->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:1px solid %2; "
"border-radius:3px; padding:4px 12px; font-size:10px; font-weight:700; }"
"QPushButton:hover { border-color:%3; color:%3; }")
.arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), ui::colors::AMBER()));
- connect(refresh_btn_, &QPushButton::clicked, this, [this]() {
- if (!current_symbol_.isEmpty()) {
- clear_cards();
- status_label_->show();
- loading_overlay_->show_loading(tr("LOADING NEWS…"));
- services::equity::EquityResearchService::instance().fetch_news(current_symbol_, 20);
- }
- });
+ connect(refresh_btn_, &QPushButton::clicked, this, [this]() { start_fetch(); });
hl->addWidget(refresh_btn_);
vl->addWidget(hdr);
+ refresh_provider_availability(); // set the initial enabled state of the NewsAPI item
+
// ── Status label ──────────────────────────────────────────────────────────
status_label_ = new QLabel(tr("Search for a symbol to load news."));
status_label_->setAlignment(Qt::AlignCenter);
@@ -248,6 +310,10 @@ void EquityNewsTab::changeEvent(QEvent* event) {
void EquityNewsTab::retranslateUi() {
if (title_lbl_) title_lbl_->setText(tr("LATEST NEWS"));
if (refresh_btn_) refresh_btn_->setText(tr("REFRESH"));
+ if (provider_combo_) {
+ provider_combo_->setItemText(0, tr("Auto (GNews → Yahoo)"));
+ provider_combo_->setToolTip(tr("News source"));
+ }
if (status_label_) {
// Pick the appropriate idle text — never overwrite a live "Loading…"
diff --git a/fincept-qt/src/screens/equity_research/EquityNewsTab.h b/fincept-qt/src/screens/equity_research/EquityNewsTab.h
index 97df824c3..9ab8f166c 100644
--- a/fincept-qt/src/screens/equity_research/EquityNewsTab.h
+++ b/fincept-qt/src/screens/equity_research/EquityNewsTab.h
@@ -3,6 +3,7 @@
#include "services/equity/EquityResearchModels.h"
#include "ui/widgets/LoadingOverlay.h"
+#include <QComboBox>
#include <QEvent>
#include <QLabel>
#include <QPushButton>
@@ -19,6 +20,11 @@ class EquityNewsTab : public QWidget {
explicit EquityNewsTab(QWidget* parent = nullptr);
void set_symbol(const QString& symbol);
+ /// Selected news provider as a persistable token ("auto" | "newsapi").
+ /// Used by EquityResearchScreen save_state/restore_state.
+ QString provider_key() const;
+ void set_provider_key(const QString& key);
+
protected:
bool eventFilter(QObject* obj, QEvent* event) override;
void changeEvent(QEvent* event) override;
@@ -31,14 +37,19 @@ class EquityNewsTab : public QWidget {
void retranslateUi();
void populate(const QVector<services::equity::NewsArticle>& articles);
void clear_cards();
+ void start_fetch(); ///< (re)fetch current symbol with the selected provider
+ void refresh_provider_availability(); ///< enable/disable the NewsAPI item by key presence
QString current_symbol_;
+ bool use_newsapi_ = false; ///< false = Auto (GNews → Yahoo), true = NewsAPI
+ bool suppress_provider_signal_ = false; ///< guard programmatic combo changes
QWidget* cards_container_ = nullptr;
QVBoxLayout* cards_layout_ = nullptr;
QLabel* status_label_ = nullptr;
QLabel* count_label_ = nullptr;
QLabel* company_label_ = nullptr;
QLabel* title_lbl_ = nullptr;
+ QComboBox* provider_combo_ = nullptr;
QPushButton* refresh_btn_ = nullptr;
QVector<services::equity::NewsArticle> cached_articles_;
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 37bc9831d..82fc45c45 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -8,6 +8,7 @@
#include "datahub/DataHub.h"
#include "datahub/DataHubMetaTypes.h"
#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
#include "trading/BrokerTopic.h"
#include "screens/equity_research/EquityAnalysisTab.h"
#include "screens/equity_research/EquityFinancialsTab.h"
@@ -15,7 +16,6 @@
#include "screens/equity_research/EquityOverviewTab.h"
#include "screens/equity_research/EquityPeersTab.h"
#include "screens/equity_research/EquitySentimentTab.h"
-#include "screens/equity_research/EquityTalippTab.h"
#include "screens/equity_research/EquityTechnicalsTab.h"
#include "services/backtesting/BacktestingService.h"
#include "services/equity/EquityResearchService.h"
@@ -38,6 +38,7 @@
#include <QMessageBox>
#include <QPointer>
#include <QPushButton>
+#include <QTabBar>
#include <QTextStream>
#include <QTimeZone>
#include <QVBoxLayout>
@@ -61,6 +62,15 @@ EquityResearchScreen::EquityResearchScreen(QWidget* parent) : QWidget(parent) {
connect(&svc, &services::equity::EquityResearchService::quote_loaded, this, &EquityResearchScreen::on_quote_loaded);
connect(&svc, &services::equity::EquityResearchService::info_loaded, this, &EquityResearchScreen::on_info_loaded);
+ // Keep the BUY/SELL buttons in sync as broker accounts connect/disconnect or
+ // are added/removed, so they appear/disappear without needing a tab re-show.
+ auto& am = trading::AccountManager::instance();
+ connect(&am, &trading::AccountManager::connection_state_changed, this,
+ [this](const QString&, trading::ConnectionState) { update_trade_buttons(); });
+ connect(&am, &trading::AccountManager::account_added, this, [this](const QString&) { update_trade_buttons(); });
+ connect(&am, &trading::AccountManager::account_removed, this, [this](const QString&) { update_trade_buttons(); });
+ connect(&am, &trading::AccountManager::account_updated, this, [this](const QString&) { update_trade_buttons(); });
+
// Listen for navigation from CommandBar asset search
EventBus::instance().subscribe("equity_research.load_symbol", [this](const QVariantMap& payload) {
const QString symbol = payload.value("symbol").toString();
@@ -84,6 +94,7 @@ void EquityResearchScreen::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
refresh_timer_->start();
hub_subscribe_broker_quote();
+ update_trade_buttons(); // a broker may have connected since last shown
}
void EquityResearchScreen::hideEvent(QHideEvent* e) {
@@ -106,6 +117,12 @@ void EquityResearchScreen::build_ui() {
// ── Tabs ─────────────────────────────────────────────────────────────────
tab_widget_ = new QTabWidget;
tab_widget_->setDocumentMode(true);
+ // Don't let the style elide tab labels — the macOS tab-bar style hint
+ // defaults to ElideRight, which truncates "OVERVIEW"→"OVERVI…" even when
+ // there's room. Size tabs to their content and only scroll when narrow.
+ tab_widget_->tabBar()->setElideMode(Qt::ElideNone);
+ tab_widget_->tabBar()->setExpanding(false);
+ tab_widget_->setUsesScrollButtons(true);
tab_widget_->setStyleSheet(QString(R"(
QTabWidget::pane { border:0; background:%1; }
QTabBar::tab {
@@ -123,7 +140,6 @@ void EquityResearchScreen::build_ui() {
financials_tab_ = new EquityFinancialsTab;
analysis_tab_ = new EquityAnalysisTab;
technicals_tab_ = new EquityTechnicalsTab;
- talipp_tab_ = new EquityTalippTab;
peers_tab_ = new EquityPeersTab;
news_tab_ = new EquityNewsTab;
sentiment_tab_ = new EquitySentimentTab;
@@ -134,7 +150,6 @@ void EquityResearchScreen::build_ui() {
tab_widget_->addTab(financials_tab_, QString());
tab_widget_->addTab(analysis_tab_, QString());
tab_widget_->addTab(technicals_tab_, QString());
- tab_widget_->addTab(talipp_tab_, QString());
tab_widget_->addTab(peers_tab_, QString());
tab_widget_->addTab(news_tab_, QString());
tab_widget_->addTab(sentiment_tab_, QString());
@@ -170,6 +185,30 @@ QWidget* EquityResearchScreen::build_title_bar() {
link_group_);
hl->addWidget(symbol_label_);
+ // BUY / SELL — visible only when a broker is connected (paper or live) and the
+ // current symbol is tradable via the connected (Indian) broker. Clicking opens
+ // the SAME order ticket used in the Equity Trading tab (see on_trade_clicked()).
+ auto make_trade_btn = [&](const QString& text, const QString& color) -> QPushButton* {
+ auto* b = new QPushButton(text, container);
+ b->setCursor(Qt::PointingHandCursor);
+ b->setFixedHeight(24);
+ b->setStyleSheet(
+ QString("QPushButton { background:transparent; color:%1; border:1px solid %1;"
+ "padding:0 14px; font-size:%2px; font-family:%3; font-weight:700; letter-spacing:1px; }"
+ "QPushButton:hover { background:%1; color:%4; }")
+ .arg(color)
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::BG_BASE()));
+ b->setVisible(false);
+ hl->addWidget(b);
+ return b;
+ };
+ buy_btn_ = make_trade_btn(tr("BUY"), ui::colors::POSITIVE());
+ sell_btn_ = make_trade_btn(tr("SELL"), ui::colors::NEGATIVE());
+ connect(buy_btn_, &QPushButton::clicked, this, [this]() { on_trade_clicked(true); });
+ connect(sell_btn_, &QPushButton::clicked, this, [this]() { on_trade_clicked(false); });
+
auto* backtest_btn = new QPushButton(tr("BACKTEST"), container);
backtest_btn->setCursor(Qt::PointingHandCursor);
backtest_btn->setFixedHeight(24);
@@ -305,16 +344,13 @@ void EquityResearchScreen::on_tab_changed(int index) {
svc.fetch_technicals(current_symbol_);
break;
case 4:
- talipp_tab_->set_symbol(current_symbol_);
- break;
- case 5:
peers_tab_->set_symbol(current_symbol_);
break;
- case 6:
+ case 5:
+ // News tab owns its own fetch (provider-aware) via set_symbol().
news_tab_->set_symbol(current_symbol_);
- svc.fetch_news(current_symbol_);
break;
- case 7:
+ case 6:
sentiment_tab_->set_symbol(current_symbol_);
break;
default:
@@ -327,11 +363,13 @@ void EquityResearchScreen::load_symbol(const QString& symbol) {
if (symbol.isEmpty() || symbol == current_symbol_)
return;
current_symbol_ = symbol;
+ last_price_ = 0.0; // stale until the new symbol's quote arrives
// Update title bar and quote bar
symbol_label_->setText(symbol);
sym_label_->setText(symbol);
price_label_->setText(tr("Loading…"));
+ update_trade_buttons(); // a new symbol may (un)hide BUY/SELL
// Overview always loads (tab 0 is default)
overview_tab_->set_symbol(symbol);
@@ -370,6 +408,11 @@ void EquityResearchScreen::update_quote_bar(const services::equity::QuoteData& q
if (q.symbol != current_symbol_)
return;
+ // Cache the freshest price (both the yfinance poll and the live broker stream
+ // funnel through here) so a BUY/SELL ticket can seed it for paper market fills.
+ if (q.price > 0.0)
+ last_price_ = q.price;
+
const QString cs = EquityOverviewTab::currency_symbol(current_currency_.isEmpty() ? "USD" : current_currency_);
sym_label_->setText(q.symbol);
@@ -576,21 +619,25 @@ void EquityResearchScreen::retranslateUi() {
tab_widget_->setTabText(1, tr("Financials"));
tab_widget_->setTabText(2, tr("Analysis"));
tab_widget_->setTabText(3, tr("Technicals"));
- // "TALIpp" is a library name — kept verbatim across locales.
- tab_widget_->setTabText(4, QStringLiteral("TALIpp"));
- tab_widget_->setTabText(5, tr("Peers"));
- tab_widget_->setTabText(6, tr("News"));
- tab_widget_->setTabText(7, tr("Sentiment"));
+ tab_widget_->setTabText(4, tr("Peers"));
+ tab_widget_->setTabText(5, tr("News"));
+ tab_widget_->setTabText(6, tr("Sentiment"));
}
}
QVariantMap EquityResearchScreen::save_state() const {
QVariantMap state{{"symbol", current_symbol_}, {"tab_index", tab_widget_ ? tab_widget_->currentIndex() : 0}};
if (peers_tab_) state["peers"] = peers_tab_->peers_text();
+ if (news_tab_) state["news_provider"] = news_tab_->provider_key();
return state;
}
void EquityResearchScreen::restore_state(const QVariantMap& state) {
+ // Apply the saved news provider BEFORE load_symbol so the News tab's first
+ // fetch (if it's the active tab) uses the restored provider.
+ if (news_tab_ && state.contains("news_provider"))
+ news_tab_->set_provider_key(state.value("news_provider").toString());
+
const QString sym = state.value("symbol").toString();
if (!sym.isEmpty()) {
current_symbol_.clear();
@@ -616,21 +663,28 @@ void EquityResearchScreen::hub_subscribe_broker_quote() {
if (!current_symbol_.endsWith(QStringLiteral(".NS")) && !current_symbol_.endsWith(QStringLiteral(".BO")))
return;
- // Find a connected Fyers account
+ // Find a connected Indian-region broker account (any — not only Fyers). NSE/
+ // BSE quotes stream through whichever Indian broker the user has live;
+ // hardcoding "fyers" left every other connected broker (Zerodha, Upstox,
+ // AngelOne, …) without research quotes. Pick the first Connected IN broker.
const auto accounts = trading::AccountManager::instance().active_accounts();
- QString fyers_account_id;
+ QString quote_broker_id, quote_account_id;
for (const auto& a : accounts) {
- if (a.broker_id == QStringLiteral("fyers") && a.state == trading::ConnectionState::Connected) {
- fyers_account_id = a.account_id;
+ if (a.state != trading::ConnectionState::Connected)
+ continue;
+ auto* b = trading::BrokerRegistry::instance().get(a.broker_id);
+ if (b && b->profile().region == QLatin1String("IN")) {
+ quote_broker_id = a.broker_id;
+ quote_account_id = a.account_id;
break;
}
}
- if (fyers_account_id.isEmpty())
+ if (quote_account_id.isEmpty())
return;
// Strip .NS/.BO suffix to get plain broker symbol
QString broker_sym = current_symbol_.left(current_symbol_.length() - 3);
- const QString topic = trading::broker_topic(QStringLiteral("fyers"), fyers_account_id,
+ const QString topic = trading::broker_topic(quote_broker_id, quote_account_id,
QStringLiteral("quote"), broker_sym);
const QString sym = current_symbol_;
@@ -663,4 +717,110 @@ void EquityResearchScreen::hub_unsubscribe_broker_quote() {
refresh_timer_->start();
}
+// ── In-tab trading ──────────────────────────────────────────────────────────
+
+// Resolve a yfinance research symbol to a broker-tradable route, matched against
+// any broker's BrokerProfile.exchanges (works for every region — not a hardcoded
+// IN/US split). `match_exchanges` is the set a broker must serve to trade it;
+// `order_exchange` is what to put on the order (definite for single-venue markets,
+// empty for US where the broker routes by symbol and we can't tell NYSE/NASDAQ
+// apart). Unknown/forex symbols → not routable.
+struct ResearchTradeRoute {
+ QString bare; // broker symbol (suffix stripped)
+ QString order_exchange; // exchange for the order, or empty → broker default
+ QStringList match_exchanges;
+ bool routable = false;
+};
+
+static ResearchTradeRoute research_trade_route(const QString& sym) {
+ ResearchTradeRoute r;
+ r.bare = sym;
+
+ // Single-venue suffixes: map yfinance suffix → broker exchange name.
+ struct Suffix {
+ const char* suffix;
+ const char* exchange;
+ };
+ static const Suffix kSuffixes[] = {
+ {".NS", "NSE"}, {".BO", "BSE"}, {".L", "LSE"}, {".TO", "TSX"},
+ {".HK", "HKEX"}, {".DE", "XETRA"}, {".PA", "EURONEXT"}, {".AS", "EURONEXT"}, {".SW", "SIX"},
+ };
+ for (const auto& s : kSuffixes) {
+ const QString suffix = QLatin1String(s.suffix);
+ if (sym.endsWith(suffix, Qt::CaseInsensitive)) {
+ r.bare = sym.left(sym.length() - suffix.length());
+ r.order_exchange = QLatin1String(s.exchange);
+ r.match_exchanges = {r.order_exchange};
+ r.routable = true;
+ return r;
+ }
+ }
+
+ // No suffix → US listing (yfinance convention, e.g. SPGI/AAPL). Any broker that
+ // offers a US equity venue can trade it; leave the order exchange empty so the
+ // broker's default is used.
+ if (!sym.contains(QLatin1Char('.'))) {
+ r.match_exchanges = {QStringLiteral("NYSE"), QStringLiteral("NASDAQ"), QStringLiteral("AMEX"),
+ QStringLiteral("ARCA"), QStringLiteral("BATS"), QStringLiteral("CBOE")};
+ r.routable = true;
+ return r;
+ }
+
+ return r; // other suffixes (.SS, .KS, …) — not routable via the wired brokers
+}
+
+// True when at least one usable account (paper, or live + Connected) is on a broker
+// that serves one of `match_exchanges`.
+static bool any_usable_broker_trades(const QStringList& match_exchanges) {
+ if (match_exchanges.isEmpty())
+ return false;
+ for (const auto& a : trading::AccountManager::instance().list_accounts()) {
+ if (!a.is_active)
+ continue;
+ if (!(a.trading_mode == QLatin1String("paper") || a.state == trading::ConnectionState::Connected))
+ continue;
+ auto* b = trading::BrokerRegistry::instance().get(a.broker_id);
+ if (!b)
+ continue;
+ const QStringList exchanges = b->profile().exchanges;
+ for (const auto& me : match_exchanges)
+ if (exchanges.contains(me, Qt::CaseInsensitive))
+ return true;
+ }
+ return false;
+}
+
+void EquityResearchScreen::update_trade_buttons() {
+ if (!buy_btn_ || !sell_btn_)
+ return;
+
+ // Show BUY/SELL only when the symbol is routable AND a usable broker actually
+ // trades that market — so SPGI shows for Alpaca/IBKR/Saxo (US venues),
+ // RELIANCE.NS for an Indian broker, and nothing for a forex-only broker.
+ const auto route = research_trade_route(current_symbol_);
+ const bool show = route.routable && any_usable_broker_trades(route.match_exchanges);
+ buy_btn_->setVisible(show);
+ sell_btn_->setVisible(show);
+}
+
+void EquityResearchScreen::on_trade_clicked(bool is_buy) {
+ if (current_symbol_.isEmpty())
+ return;
+
+ const auto route = research_trade_route(current_symbol_);
+ if (!route.routable)
+ return;
+
+ // Hand off to the Equity Trading screen, which owns the order ticket + the
+ // paper/live placement path and routes to a broker that serves match_exchanges.
+ // WindowFrame materialises that screen (hidden, no tab switch) if needed, then
+ // the app-modal ticket pops over this tab.
+ EventBus::instance().publish("equity.open_order_ticket",
+ {{"symbol", route.bare},
+ {"exchange", route.order_exchange},
+ {"match_exchanges", route.match_exchanges},
+ {"is_buy", is_buy},
+ {"price", last_price_}});
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
index d92a50cb0..cd57bd347 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
@@ -6,6 +6,7 @@
#include <QHideEvent>
#include <QLabel>
+#include <QPushButton>
#include <QShowEvent>
#include <QTabWidget>
#include <QTimer>
@@ -17,7 +18,6 @@ class EquityOverviewTab;
class EquityFinancialsTab;
class EquityAnalysisTab;
class EquityTechnicalsTab;
-class EquityTalippTab;
class EquityPeersTab;
class EquityNewsTab;
class EquitySentimentTab;
@@ -49,6 +49,9 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
void on_quote_loaded(services::equity::QuoteData quote);
void on_info_loaded(services::equity::StockInfo info);
void on_tab_changed(int index);
+ // BUY/SELL from the title bar → routes the current symbol to the existing
+ // Equity Trading order ticket (same form + paper/live engine) via EventBus.
+ void on_trade_clicked(bool is_buy);
// Opens the "Download Price Data (CSV)" dialog and exports yfinance OHLCV
// history for current_symbol_ to a user-chosen file.
void on_download_csv_clicked();
@@ -62,10 +65,15 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
void retranslateUi();
void hub_subscribe_broker_quote();
void hub_unsubscribe_broker_quote();
+ // Show the BUY/SELL buttons only when a broker is connected (paper or live)
+ // AND the current symbol is tradable via those (Indian) brokers (.NS/.BO).
+ void update_trade_buttons();
// Title bar
QLabel* title_label_ = nullptr;
QLabel* symbol_label_ = nullptr;
+ QPushButton* buy_btn_ = nullptr;
+ QPushButton* sell_btn_ = nullptr;
QLabel* hint_label_ = nullptr;
// Quote bar
@@ -83,7 +91,6 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
EquityFinancialsTab* financials_tab_ = nullptr;
EquityAnalysisTab* analysis_tab_ = nullptr;
EquityTechnicalsTab* technicals_tab_ = nullptr;
- EquityTalippTab* talipp_tab_ = nullptr;
EquityPeersTab* peers_tab_ = nullptr;
EquityNewsTab* news_tab_ = nullptr;
EquitySentimentTab* sentiment_tab_ = nullptr;
@@ -91,6 +98,7 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
QTimer* refresh_timer_ = nullptr;
QString current_symbol_;
QString current_currency_;
+ double last_price_ = 0.0; // freshest quote price, seeds the order ticket
bool hub_broker_active_ = false;
// Symbol group link — SymbolGroup::None when unlinked.
diff --git a/fincept-qt/src/screens/equity_research/EquitySentimentTab.cpp b/fincept-qt/src/screens/equity_research/EquitySentimentTab.cpp
index 4683868c7..d9fc3842c 100644
--- a/fincept-qt/src/screens/equity_research/EquitySentimentTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquitySentimentTab.cpp
@@ -1,6 +1,6 @@
#include "screens/equity_research/EquitySentimentTab.h"
-#include "services/equity/MarketSentimentService.h"
+#include "services/equity/EquitySentimentService.h"
#include "ui/theme/Theme.h"
#include <QCoreApplication>
@@ -13,108 +13,61 @@ namespace fincept::screens {
namespace {
-// make_panel / make_stat_box optionally capture the title label so the caller
-// can re-translate it via retranslateUi. When title_lbl_out is nullptr the
-// helper still constructs the title but doesn't expose it (caller is
-// responsible for any later retranslation).
-QFrame* make_panel(const QString& title, QLabel** title_lbl_out = nullptr) {
+// Distinct helper names (anonymous namespace) to avoid unity-build ODR clashes.
+QFrame* sentiment_make_panel(const QString& title, QVBoxLayout** body_out, QLabel** title_out = nullptr) {
auto* frame = new QFrame;
- frame->setStyleSheet(
- QString("QFrame { background:%1; border:1px solid %2; border-radius:4px; }")
- .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+ frame->setStyleSheet(QString("QFrame { background:%1; border:1px solid %2; border-radius:4px; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
auto* layout = new QVBoxLayout(frame);
layout->setContentsMargins(12, 10, 12, 10);
- layout->setSpacing(6);
+ layout->setSpacing(8);
auto* label = new QLabel(title);
label->setStyleSheet(
QString("color:%1; font-size:11px; font-weight:700; letter-spacing:1px; background:transparent; border:0;")
.arg(ui::colors::AMBER()));
layout->addWidget(label);
- if (title_lbl_out)
- *title_lbl_out = label;
+ if (title_out)
+ *title_out = label;
+ if (body_out)
+ *body_out = layout;
return frame;
}
-QWidget* make_stat_box(const QString& title, QLabel** value_label, QLabel** title_label_out = nullptr) {
- auto* box = new QFrame;
- box->setStyleSheet(
- QString("QFrame { background:%1; border:1px solid %2; border-radius:4px; }")
- .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
- auto* layout = new QVBoxLayout(box);
- layout->setContentsMargins(10, 10, 10, 10);
- layout->setSpacing(4);
-
- auto* title_label = new QLabel(title);
- title_label->setStyleSheet(
- QString("color:%1; font-size:10px; font-weight:700; letter-spacing:1px; background:transparent; border:0;")
- .arg(ui::colors::TEXT_TERTIARY()));
- layout->addWidget(title_label);
- if (title_label_out)
- *title_label_out = title_label;
-
- auto* value = new QLabel(QStringLiteral("—"));
- value->setStyleSheet(
- QString("color:%1; font-size:18px; font-weight:700; background:transparent; border:0;")
- .arg(ui::colors::TEXT_PRIMARY()));
- layout->addWidget(value);
-
- *value_label = value;
- return box;
-}
-
-QString alignment_label(const QString& alignment) {
- // Caller is a Q_OBJECT instance method; we route translation through
- // QCoreApplication so lupdate associates these strings with the
- // EquitySentimentTab context.
- if (alignment == "aligned")
- return QCoreApplication::translate("EquitySentimentTab", "ALIGNED");
- if (alignment == "mixed")
- return QCoreApplication::translate("EquitySentimentTab", "MIXED");
- if (alignment == "divergent")
- return QCoreApplication::translate("EquitySentimentTab", "DIVERGENT");
- if (alignment == "single_source")
- return QCoreApplication::translate("EquitySentimentTab", "SINGLE SOURCE");
- return QCoreApplication::translate("EquitySentimentTab", "UNAVAILABLE");
-}
-
-QString alignment_color(const QString& alignment) {
- if (alignment == "aligned") {
+QString sentiment_label_color(const QString& label) {
+ if (label == "BULLISH")
return ui::colors::POSITIVE();
- }
- if (alignment == "mixed" || alignment == "single_source") {
- return ui::colors::WARNING();
- }
- if (alignment == "divergent") {
+ if (label == "BEARISH")
return ui::colors::NEGATIVE();
- }
return ui::colors::TEXT_TERTIARY();
}
+QString sentiment_fmt_score(double score) {
+ return QString("%1%2").arg(score >= 0.0 ? "+" : "", QString::number(score, 'f', 2));
+}
+
} // namespace
EquitySentimentTab::EquitySentimentTab(QWidget* parent) : QWidget(parent) {
build_ui();
- auto& service = services::equity::MarketSentimentService::instance();
- connect(&service, &services::equity::MarketSentimentService::snapshot_loaded,
- this, &EquitySentimentTab::on_snapshot_loaded);
+ connect(&services::equity::EquitySentimentService::instance(),
+ &services::equity::EquitySentimentService::sentiment_loaded, this,
+ &EquitySentimentTab::on_sentiment_loaded);
}
void EquitySentimentTab::set_symbol(const QString& symbol) {
- if (symbol.isEmpty()) {
+ if (symbol.isEmpty())
return;
- }
current_symbol_ = symbol;
snapshot_loaded_ = false;
company_label_->setText(symbol);
- coverage_label_->setText("");
+ caption_label_->setText("");
content_widget_->hide();
- clear_sources();
- status_label_->setText(tr("Loading market sentiment…"));
+ status_label_->setText(tr("Loading sentiment…"));
status_label_->show();
loading_overlay_->show_loading(tr("LOADING SENTIMENT…"));
- services::equity::MarketSentimentService::instance().fetch_snapshot(symbol);
+ services::equity::EquitySentimentService::instance().fetch_sentiment(symbol);
}
void EquitySentimentTab::build_ui() {
@@ -125,6 +78,7 @@ void EquitySentimentTab::build_ui() {
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
+ // ── Header ────────────────────────────────────────────────────────────────
auto* header = new QWidget;
header->setStyleSheet(
QString("background:%1; border-bottom:2px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::AMBER()));
@@ -138,15 +92,13 @@ void EquitySentimentTab::build_ui() {
.arg(ui::colors::AMBER()));
header_layout->addWidget(title_lbl_);
- coverage_label_ = new QLabel;
- coverage_label_->setStyleSheet(
- QString("color:%1; font-size:10px; background:transparent; border:0;")
- .arg(ui::colors::TEXT_TERTIARY()));
- header_layout->addWidget(coverage_label_);
+ caption_label_ = new QLabel;
+ caption_label_->setStyleSheet(
+ QString("color:%1; font-size:10px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
+ header_layout->addWidget(caption_label_);
company_label_ = new QLabel;
- company_label_->setStyleSheet(
- QString("color:%1; font-size:10px; background:transparent; border:0;").arg("#22d3ee"));
+ company_label_->setStyleSheet(QString("color:%1; font-size:10px; background:transparent; border:0;").arg("#22d3ee"));
header_layout->addWidget(company_label_);
header_layout->addStretch();
@@ -158,24 +110,21 @@ void EquitySentimentTab::build_ui() {
"QPushButton:hover { border-color:%3; color:%3; }")
.arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), ui::colors::AMBER()));
connect(refresh_btn_, &QPushButton::clicked, this, [this]() {
- if (!current_symbol_.isEmpty()) {
- content_widget_->hide();
- clear_sources();
- status_label_->setText(tr("Refreshing market sentiment…"));
- status_label_->show();
- loading_overlay_->show_loading(tr("REFRESHING SENTIMENT…"));
- services::equity::MarketSentimentService::instance().fetch_snapshot(current_symbol_, 7, true);
- }
+ if (!current_symbol_.isEmpty())
+ set_symbol(current_symbol_);
});
header_layout->addWidget(refresh_btn_);
root->addWidget(header);
- status_label_ = new QLabel(tr("Open a symbol and enable Adanos Market Sentiment in Data Sources to load a snapshot."));
+ // ── Idle / status text ──────────────────────────────────────────────────────
+ status_label_ = new QLabel(tr("Open a symbol to compute sentiment from news and price momentum."));
status_label_->setAlignment(Qt::AlignCenter);
+ status_label_->setWordWrap(true);
status_label_->setStyleSheet(
QString("color:%1; font-size:12px; padding:20px; background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
root->addWidget(status_label_);
+ // ── Scrollable content ────────────────────────────────────────────────────
auto* scroll = new QScrollArea;
scroll->setWidgetResizable(true);
scroll->setFrameShape(QFrame::NoFrame);
@@ -185,117 +134,225 @@ void EquitySentimentTab::build_ui() {
auto* content_layout = new QVBoxLayout(content_widget_);
content_layout->setContentsMargins(12, 12, 12, 12);
content_layout->setSpacing(12);
- content_layout->addWidget(build_summary_panel());
- auto* sources_panel = make_panel(tr("SOURCE BREAKDOWN"), &sources_title_lbl_);
- sources_widget_ = sources_panel;
- sources_layout_ = new QGridLayout;
+ // Net score badge + distribution bar in one summary panel.
+ QVBoxLayout* summary_body = nullptr;
+ auto* summary_panel = sentiment_make_panel(tr("OVERALL"), &summary_body, &summary_title_lbl_);
+
+ auto* badge_row = new QHBoxLayout;
+ badge_row->setContentsMargins(0, 0, 0, 0);
+ badge_row->setSpacing(16);
+
+ net_label_ = new QLabel(QStringLiteral("—"));
+ net_label_->setStyleSheet(
+ QString("color:%1; font-size:26px; font-weight:800; background:transparent; border:0;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ badge_row->addWidget(net_label_);
+
+ net_score_label_ = new QLabel;
+ net_score_label_->setStyleSheet(
+ QString("color:%1; font-size:22px; font-weight:700; background:transparent; border:0;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ badge_row->addWidget(net_score_label_);
+
+ badge_row->addStretch();
+
+ net_conf_label_ = new QLabel;
+ net_conf_label_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ net_conf_label_->setStyleSheet(
+ QString("color:%1; font-size:11px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
+ badge_row->addWidget(net_conf_label_);
+ summary_body->addLayout(badge_row);
+
+ // Distribution bar (bull / neutral / bear proportions).
+ auto* dist_bar = new QFrame;
+ dist_bar->setFixedHeight(10);
+ dist_bar->setStyleSheet("background:transparent; border:0;");
+ dist_layout_ = new QHBoxLayout(dist_bar);
+ dist_layout_->setContentsMargins(0, 0, 0, 0);
+ dist_layout_->setSpacing(2);
+ summary_body->addWidget(dist_bar);
+
+ dist_counts_label_ = new QLabel;
+ dist_counts_label_->setStyleSheet(
+ QString("color:%1; font-size:10px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
+ summary_body->addWidget(dist_counts_label_);
+
+ content_layout->addWidget(summary_panel);
+
+ // Source breakdown.
+ QVBoxLayout* sources_body = nullptr;
+ auto* sources_panel = sentiment_make_panel(tr("SIGNAL SOURCES"), &sources_body, &sources_title_lbl_);
+ sources_layout_ = new QVBoxLayout;
sources_layout_->setContentsMargins(0, 0, 0, 0);
- sources_layout_->setSpacing(10);
- static_cast<QVBoxLayout*>(sources_panel->layout())->addLayout(sources_layout_);
+ sources_layout_->setSpacing(6);
+ sources_body->addLayout(sources_layout_);
content_layout->addWidget(sources_panel);
- content_layout->addStretch();
+ // Per-article list.
+ QVBoxLayout* articles_body = nullptr;
+ auto* articles_panel = sentiment_make_panel(tr("HEADLINES"), &articles_body, &articles_title_lbl_);
+ articles_layout_ = new QVBoxLayout;
+ articles_layout_->setContentsMargins(0, 0, 0, 0);
+ articles_layout_->setSpacing(6);
+ articles_body->addLayout(articles_layout_);
+ content_layout->addWidget(articles_panel);
+
+ content_layout->addStretch();
scroll->setWidget(content_widget_);
root->addWidget(scroll, 1);
content_widget_->hide();
}
-QWidget* EquitySentimentTab::build_summary_panel() {
- auto* panel = make_panel(tr("SUMMARY"), &summary_title_lbl_);
- auto* grid = new QGridLayout;
- grid->setContentsMargins(0, 0, 0, 0);
- grid->setSpacing(10);
-
- grid->addWidget(make_stat_box(tr("AVERAGE BUZZ"), &avg_buzz_value_, &avg_buzz_title_), 0, 0);
- grid->addWidget(make_stat_box(tr("BULLISH %"), &avg_bullish_value_, &avg_bullish_title_), 0, 1);
- grid->addWidget(make_stat_box(tr("COVERAGE"), &coverage_value_, &coverage_title_), 1, 0);
- grid->addWidget(make_stat_box(tr("ALIGNMENT"), &alignment_value_, &alignment_title_), 1, 1);
-
- static_cast<QVBoxLayout*>(panel->layout())->addLayout(grid);
- return panel;
-}
-
-void EquitySentimentTab::clear_sources() {
- while (sources_layout_->count() > 0) {
- auto* item = sources_layout_->takeAt(0);
- if (item->widget()) {
+void EquitySentimentTab::clear_layout(QLayout* layout) {
+ if (!layout)
+ return;
+ while (layout->count() > 0) {
+ auto* item = layout->takeAt(0);
+ if (item->widget())
item->widget()->deleteLater();
- }
+ if (item->layout())
+ clear_layout(item->layout());
delete item;
}
}
-void EquitySentimentTab::populate(const services::equity::MarketSentimentSnapshot& snapshot) {
- avg_buzz_value_->setText(QString::number(snapshot.average_buzz, 'f', 1));
- avg_bullish_value_->setText(QString("%1%").arg(QString::number(snapshot.average_bullish_pct, 'f', 1)));
- coverage_value_->setText(QString("%1 / %2").arg(snapshot.coverage).arg(snapshot.sources.size()));
- alignment_value_->setText(alignment_label(snapshot.source_alignment));
- alignment_value_->setStyleSheet(
- QString("color:%1; font-size:18px; font-weight:700; background:transparent; border:0;")
- .arg(alignment_color(snapshot.source_alignment)));
-
- clear_sources();
- for (int i = 0; i < snapshot.sources.size(); ++i) {
- const auto& source = snapshot.sources.at(i);
- auto* card = make_panel(source.label);
- auto* layout = static_cast<QVBoxLayout*>(card->layout());
-
- auto add_row = [layout](const QString& key, const QString& value, const QString& color = QString()) {
- auto* row = new QWidget;
- auto* row_layout = new QHBoxLayout(row);
- row_layout->setContentsMargins(0, 0, 0, 0);
- row_layout->setSpacing(6);
-
- auto* key_label = new QLabel(key);
- key_label->setStyleSheet(
- QString("color:%1; font-size:10px; background:transparent; border:0;").arg(ui::colors::TEXT_SECONDARY()));
- row_layout->addWidget(key_label);
-
- auto* value_label = new QLabel(value);
- value_label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
- value_label->setStyleSheet(
- QString("color:%1; font-size:11px; font-weight:600; background:transparent; border:0;")
- .arg(color.isEmpty() ? ui::colors::TEXT_PRIMARY() : color));
- row_layout->addWidget(value_label, 1);
- layout->addWidget(row);
- };
-
- if (source.available) {
- add_row(tr("Buzz"), QString::number(source.buzz_score, 'f', 1));
- add_row(tr("Bullish"), QString("%1%").arg(QString::number(source.bullish_pct, 'f', 1)));
- add_row(tr("Activity"), QString::number(source.activity_count, 'f', 0));
- add_row(tr("Sentiment"), QString::number(source.sentiment_score, 'f', 2),
- source.sentiment_score >= 0.0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE());
+void EquitySentimentTab::populate(const services::equity::EquitySentimentSnapshot& snapshot) {
+ // ── Net badge ──────────────────────────────────────────────────────────────
+ net_label_->setText(snapshot.label);
+ net_label_->setStyleSheet(QString("color:%1; font-size:26px; font-weight:800; background:transparent; border:0;")
+ .arg(sentiment_label_color(snapshot.label)));
+ net_score_label_->setText(sentiment_fmt_score(snapshot.overall_score));
+ net_conf_label_->setText(tr("Confidence %1%").arg(QString::number(snapshot.confidence * 100.0, 'f', 0)));
+
+ // ── Distribution bar ─────────────────────────────────────────────────────
+ clear_layout(dist_layout_);
+ const int total = snapshot.bullish + snapshot.bearish + snapshot.neutral;
+ auto add_segment = [this](int count, const QString& color) {
+ if (count <= 0)
+ return;
+ auto* seg = new QFrame;
+ seg->setFixedHeight(10);
+ seg->setStyleSheet(QString("background:%1; border:0; border-radius:2px;").arg(color));
+ dist_layout_->addWidget(seg, count);
+ };
+ if (total > 0) {
+ add_segment(snapshot.bullish, ui::colors::POSITIVE());
+ add_segment(snapshot.neutral, ui::colors::BORDER_DIM());
+ add_segment(snapshot.bearish, ui::colors::NEGATIVE());
+ } else {
+ auto* seg = new QFrame;
+ seg->setFixedHeight(10);
+ seg->setStyleSheet(QString("background:%1; border:0; border-radius:2px;").arg(ui::colors::BORDER_DIM()));
+ dist_layout_->addWidget(seg, 1);
+ }
+ dist_counts_label_->setText(tr("%1 bullish · %2 neutral · %3 bearish (%4 headlines)")
+ .arg(snapshot.bullish)
+ .arg(snapshot.neutral)
+ .arg(snapshot.bearish)
+ .arg(snapshot.article_count));
+
+ // ── Signal sources ─────────────────────────────────────────────────────────
+ clear_layout(sources_layout_);
+ for (const auto& src : snapshot.sources) {
+ auto* row = new QWidget;
+ auto* row_layout = new QHBoxLayout(row);
+ row_layout->setContentsMargins(0, 0, 0, 0);
+ row_layout->setSpacing(8);
+
+ auto* name = new QLabel(src.label);
+ name->setStyleSheet(
+ QString("color:%1; font-size:11px; font-weight:600; background:transparent; border:0;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ row_layout->addWidget(name);
+ row_layout->addStretch();
+
+ if (src.available) {
+ auto* score = new QLabel(sentiment_fmt_score(src.score));
+ score->setStyleSheet(QString("color:%1; font-size:11px; font-weight:700; background:transparent; border:0;")
+ .arg(src.score >= 0.0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ row_layout->addWidget(score);
+
+ auto* weight = new QLabel(tr("wt %1%").arg(QString::number(src.weight * 100.0, 'f', 0)));
+ weight->setStyleSheet(QString("color:%1; font-size:10px; background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ row_layout->addWidget(weight);
} else {
- auto* empty = new QLabel(tr("No snapshot available."));
- empty->setWordWrap(true);
- empty->setStyleSheet(
- QString("color:%1; font-size:11px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
- layout->addWidget(empty);
+ auto* na = new QLabel(tr("n/a"));
+ na->setStyleSheet(QString("color:%1; font-size:10px; background:transparent; border:0;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ row_layout->addWidget(na);
}
+ sources_layout_->addWidget(row);
+ }
- sources_layout_->addWidget(card, i / 2, i % 2);
+ // ── Headlines ───────────────────────────────────────────────────────────────
+ clear_layout(articles_layout_);
+ if (snapshot.articles.isEmpty()) {
+ auto* empty = new QLabel(tr("No headlines available for this symbol."));
+ empty->setStyleSheet(
+ QString("color:%1; font-size:11px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
+ articles_layout_->addWidget(empty);
+ }
+ for (const auto& article : snapshot.articles) {
+ auto* row = new QFrame;
+ row->setStyleSheet(QString("QFrame { background:%1; border:1px solid %2; border-radius:3px; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));
+ auto* row_layout = new QHBoxLayout(row);
+ row_layout->setContentsMargins(8, 6, 8, 6);
+ row_layout->setSpacing(8);
+
+ const QString chip_color = sentiment_label_color(article.label);
+ auto* chip = new QLabel(article.label.left(4));
+ chip->setAlignment(Qt::AlignCenter);
+ chip->setFixedWidth(46);
+ chip->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; letter-spacing:1px; "
+ "border:1px solid %1; border-radius:3px; padding:2px 0; background:transparent;")
+ .arg(chip_color));
+ row_layout->addWidget(chip, 0, Qt::AlignTop);
+
+ auto* text_col = new QVBoxLayout;
+ text_col->setContentsMargins(0, 0, 0, 0);
+ text_col->setSpacing(2);
+
+ auto* headline = new QLabel(article.title);
+ headline->setWordWrap(true);
+ headline->setStyleSheet(
+ QString("color:%1; font-size:11px; background:transparent; border:0;").arg(ui::colors::TEXT_PRIMARY()));
+ text_col->addWidget(headline);
+
+ QString meta = article.publisher;
+ const QString date = article.published_date.left(10);
+ if (!date.isEmpty())
+ meta = meta.isEmpty() ? date : QString("%1 · %2").arg(meta, date);
+ if (!meta.isEmpty()) {
+ auto* meta_lbl = new QLabel(meta);
+ meta_lbl->setStyleSheet(
+ QString("color:%1; font-size:9px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
+ text_col->addWidget(meta_lbl);
+ }
+ row_layout->addLayout(text_col, 1);
+ articles_layout_->addWidget(row);
}
}
-void EquitySentimentTab::on_snapshot_loaded(QString symbol, fincept::services::equity::MarketSentimentSnapshot snapshot) {
- if (symbol != current_symbol_) {
+void EquitySentimentTab::on_sentiment_loaded(QString symbol,
+ fincept::services::equity::EquitySentimentSnapshot snapshot) {
+ if (symbol != current_symbol_)
return;
- }
loading_overlay_->hide_loading();
cached_snapshot_ = snapshot;
snapshot_loaded_ = true;
- coverage_label_->setText(snapshot.coverage > 0
- ? tr("%1 sources live").arg(snapshot.coverage)
- : tr("Optional alternative data"));
+ caption_label_->setText(snapshot.available && !snapshot.engine.isEmpty()
+ ? tr("engine: %1").arg(snapshot.engine)
+ : tr("self-computed"));
- if (!snapshot.configured || !snapshot.available) {
+ if (!snapshot.available) {
content_widget_->hide();
status_label_->setText(snapshot.message.isEmpty()
- ? tr("No market sentiment snapshot is available for this symbol.")
+ ? tr("No sentiment is available for this symbol.")
: snapshot.message);
status_label_->show();
return;
@@ -309,35 +366,28 @@ void EquitySentimentTab::on_snapshot_loaded(QString symbol, fincept::services::e
// ── Re-translation ───────────────────────────────────────────────────────────
void EquitySentimentTab::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange) {
+ if (event->type() == QEvent::LanguageChange)
retranslateUi();
- }
QWidget::changeEvent(event);
}
void EquitySentimentTab::retranslateUi() {
- if (title_lbl_) title_lbl_->setText(tr("MARKET SENTIMENT"));
- if (refresh_btn_) refresh_btn_->setText(tr("REFRESH"));
- if (sources_title_lbl_) sources_title_lbl_->setText(tr("SOURCE BREAKDOWN"));
- if (summary_title_lbl_) summary_title_lbl_->setText(tr("SUMMARY"));
- if (avg_buzz_title_) avg_buzz_title_->setText(tr("AVERAGE BUZZ"));
- if (avg_bullish_title_) avg_bullish_title_->setText(tr("BULLISH %"));
- if (coverage_title_) coverage_title_->setText(tr("COVERAGE"));
- if (alignment_title_) alignment_title_->setText(tr("ALIGNMENT"));
-
- // Idle status text — only overwrite when nothing's loaded yet.
+ if (title_lbl_)
+ title_lbl_->setText(tr("MARKET SENTIMENT"));
+ if (refresh_btn_)
+ refresh_btn_->setText(tr("REFRESH"));
+ if (summary_title_lbl_)
+ summary_title_lbl_->setText(tr("OVERALL"));
+ if (sources_title_lbl_)
+ sources_title_lbl_->setText(tr("SIGNAL SOURCES"));
+ if (articles_title_lbl_)
+ articles_title_lbl_->setText(tr("HEADLINES"));
+
if (status_label_ && current_symbol_.isEmpty())
- status_label_->setText(tr("Open a symbol and enable Adanos Market Sentiment in Data Sources to load a snapshot."));
-
- // Re-render from cached snapshot so coverage caption, alignment badge,
- // and per-source rows pick up the new locale.
- if (snapshot_loaded_) {
- coverage_label_->setText(cached_snapshot_.coverage > 0
- ? tr("%1 sources live").arg(cached_snapshot_.coverage)
- : tr("Optional alternative data"));
- if (cached_snapshot_.configured && cached_snapshot_.available)
- populate(cached_snapshot_);
- }
+ status_label_->setText(tr("Open a symbol to compute sentiment from news and price momentum."));
+
+ if (snapshot_loaded_ && cached_snapshot_.available)
+ populate(cached_snapshot_);
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_research/EquitySentimentTab.h b/fincept-qt/src/screens/equity_research/EquitySentimentTab.h
index bc2b259b1..aced103f4 100644
--- a/fincept-qt/src/screens/equity_research/EquitySentimentTab.h
+++ b/fincept-qt/src/screens/equity_research/EquitySentimentTab.h
@@ -4,7 +4,7 @@
#include "ui/widgets/LoadingOverlay.h"
#include <QEvent>
-#include <QGridLayout>
+#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
@@ -13,6 +13,9 @@
namespace fincept::screens {
+// Equity Research → Sentiment tab. Shows the terminal's own, keyless sentiment
+// (news headline NLP blended with price momentum, plus optional Adanos when a
+// key is configured) via EquitySentimentService.
class EquitySentimentTab : public QWidget {
Q_OBJECT
public:
@@ -23,36 +26,45 @@ class EquitySentimentTab : public QWidget {
void changeEvent(QEvent* event) override;
private slots:
- void on_snapshot_loaded(QString symbol, fincept::services::equity::MarketSentimentSnapshot snapshot);
+ void on_sentiment_loaded(QString symbol, fincept::services::equity::EquitySentimentSnapshot snapshot);
private:
void build_ui();
void retranslateUi();
- void populate(const fincept::services::equity::MarketSentimentSnapshot& snapshot);
- void clear_sources();
- QWidget* build_summary_panel();
+ void populate(const fincept::services::equity::EquitySentimentSnapshot& snapshot);
+ static void clear_layout(QLayout* layout);
QString current_symbol_;
- QWidget* content_widget_ = nullptr;
- QWidget* sources_widget_ = nullptr;
- QGridLayout* sources_layout_ = nullptr;
- QLabel* status_label_ = nullptr;
- QLabel* company_label_ = nullptr;
- QLabel* coverage_label_ = nullptr;
+
+ // Header
QLabel* title_lbl_ = nullptr;
+ QLabel* company_label_ = nullptr;
+ QLabel* caption_label_ = nullptr;
QPushButton* refresh_btn_ = nullptr;
- QLabel* sources_title_lbl_ = nullptr;
+
+ // Status / content
+ QLabel* status_label_ = nullptr;
+ QWidget* content_widget_ = nullptr;
+
+ // Net score badge
+ QLabel* net_label_ = nullptr;
+ QLabel* net_score_label_ = nullptr;
+ QLabel* net_conf_label_ = nullptr;
+
+ // Distribution bar
+ QLabel* dist_counts_label_ = nullptr;
+ QHBoxLayout* dist_layout_ = nullptr;
+
+ // Dynamic sections
+ QVBoxLayout* sources_layout_ = nullptr;
+ QVBoxLayout* articles_layout_ = nullptr;
+
+ // Panel titles (for retranslation)
QLabel* summary_title_lbl_ = nullptr;
- QLabel* avg_buzz_title_ = nullptr;
- QLabel* avg_bullish_title_ = nullptr;
- QLabel* coverage_title_ = nullptr;
- QLabel* alignment_title_ = nullptr;
- QLabel* avg_buzz_value_ = nullptr;
- QLabel* avg_bullish_value_ = nullptr;
- QLabel* coverage_value_ = nullptr;
- QLabel* alignment_value_ = nullptr;
-
- fincept::services::equity::MarketSentimentSnapshot cached_snapshot_;
+ QLabel* sources_title_lbl_ = nullptr;
+ QLabel* articles_title_lbl_ = nullptr;
+
+ fincept::services::equity::EquitySentimentSnapshot cached_snapshot_;
bool snapshot_loaded_ = false;
ui::LoadingOverlay* loading_overlay_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_research/EquityTalippTab.cpp b/fincept-qt/src/screens/equity_research/EquityTalippTab.cpp
deleted file mode 100644
index e340d5545..000000000
--- a/fincept-qt/src/screens/equity_research/EquityTalippTab.cpp
+++ /dev/null
@@ -1,566 +0,0 @@
-// src/screens/equity_research/EquityTalippTab.cpp
-#include "screens/equity_research/EquityTalippTab.h"
-
-#include "services/equity/EquityResearchService.h"
-#include "ui/theme/Theme.h"
-
-#include <QChart>
-#include <QDateTimeAxis>
-#include <QDoubleSpinBox>
-#include <QFrame>
-#include <QHBoxLayout>
-#include <QLineSeries>
-#include <QPen>
-#include <QVBoxLayout>
-#include <QValueAxis>
-
-namespace fincept::screens {
-
-// ── Static category/indicator data (matches reference INDICATORS object) ──────
-const QList<EquityTalippTab::CategoryDef>& EquityTalippTab::categories() {
- static const QList<CategoryDef> cats = {
- {"trend",
- "TREND",
- "#22d3ee",
- {
- {"sma", "SMA", "prices"},
- {"ema", "EMA", "prices"},
- {"wma", "WMA", "prices"},
- {"dema", "DEMA", "prices"},
- {"tema", "TEMA", "prices"},
- {"hma", "HMA", "prices"},
- {"kama", "KAMA", "prices"},
- {"alma", "ALMA", "prices"},
- {"t3", "T3", "prices"},
- {"zlema", "ZLEMA", "prices"},
- }},
- {"trend_advanced",
- "TREND+",
- "#60a5fa",
- {
- {"adx", "ADX", "ohlcv"},
- {"aroon", "Aroon", "ohlcv"},
- {"ichimoku", "Ichimoku", "ohlcv"},
- {"parabolic_sar", "Parabolic SAR", "ohlcv"},
- {"supertrend", "SuperTrend", "ohlcv"},
- }},
- {"momentum",
- "MOMENTUM",
- ui::colors::AMBER,
- {
- {"rsi", "RSI", "prices"},
- {"macd", "MACD", "prices"},
- {"stoch", "Stochastic", "ohlcv"},
- {"stoch_rsi", "StochRSI", "prices"},
- {"cci", "CCI", "ohlcv"},
- {"roc", "ROC", "prices"},
- {"tsi", "TSI", "prices"},
- {"williams", "Williams %R", "ohlcv"},
- }},
- {"volatility",
- "VOLATILITY",
- "#eab308",
- {
- {"atr", "ATR", "ohlcv"},
- {"bb", "Bollinger Bands", "prices"},
- {"keltner", "Keltner Channels", "ohlcv"},
- {"donchian", "Donchian Channels", "ohlcv"},
- {"chandelier_stop", "Chandelier Stop", "ohlcv"},
- {"natr", "NATR", "ohlcv"},
- }},
- {"volume",
- "VOLUME",
- ui::colors::POSITIVE,
- {
- {"obv", "OBV", "ohlcv"},
- {"vwap", "VWAP", "ohlcv"},
- {"vwma", "VWMA", "ohlcv"},
- {"mfi", "MFI", "ohlcv"},
- {"chaikin_osc", "Chaikin Osc", "ohlcv"},
- {"force_index", "Force Index", "ohlcv"},
- }},
- {"specialized",
- "SPECIAL",
- "#a855f7",
- {
- {"ao", "Awesome Osc", "ohlcv"},
- {"accu_dist", "Accum/Dist", "ohlcv"},
- {"bop", "Balance of Pwr", "ohlcv"},
- {"chop", "CHOP", "ohlcv"},
- {"coppock_curve", "Coppock Curve", "prices"},
- {"dpo", "DPO", "prices"},
- {"emv", "EMV", "ohlcv"},
- {"ibs", "IBS", "ohlcv"},
- {"kst", "KST", "prices"},
- {"kvo", "KVO", "ohlcv"},
- {"mass_index", "Mass Index", "ohlcv"},
- {"mcginley", "McGinley", "prices"},
- {"mean_dev", "Mean Dev", "prices"},
- {"smma", "SMMA", "prices"},
- {"sobv", "Smoothed OBV", "ohlcv"},
- {"stc", "STC", "prices"},
- {"std_dev", "Std Dev", "prices"},
- {"trix", "TRIX", "prices"},
- {"ttm", "TTM Squeeze", "ohlcv"},
- {"uo", "Ultimate Osc", "ohlcv"},
- {"vtx", "Vortex", "ohlcv"},
- {"zigzag", "ZigZag", "ohlcv"},
- }},
- };
- return cats;
-}
-
-const QMap<QString, QList<QPair<QString, double>>>& EquityTalippTab::param_defs() {
- static const QMap<QString, QList<QPair<QString, double>>> m = {
- {"sma", {{"period", 20}}},
- {"ema", {{"period", 20}}},
- {"wma", {{"period", 20}}},
- {"dema", {{"period", 20}}},
- {"tema", {{"period", 20}}},
- {"hma", {{"period", 20}}},
- {"kama", {{"period", 10}}},
- {"alma", {{"period", 20}, {"offset", 0.85}, {"sigma", 6.0}}},
- {"t3", {{"period", 5}, {"vfactor", 0.7}}},
- {"zlema", {{"period", 20}}},
- {"adx", {{"period", 14}}},
- {"aroon", {{"period", 14}}},
- {"ichimoku", {{"tenkan", 9}, {"kijun", 26}, {"senkou_b", 52}}},
- {"parabolic_sar", {{"acceleration", 0.02}, {"maximum", 0.2}}},
- {"supertrend", {{"period", 7}, {"multiplier", 3.0}}},
- {"rsi", {{"period", 14}}},
- {"macd", {{"fast", 12}, {"slow", 26}, {"signal", 9}}},
- {"stoch", {{"k_period", 14}, {"d_period", 3}}},
- {"stoch_rsi", {{"period", 14}}},
- {"cci", {{"period", 20}}},
- {"roc", {{"period", 10}}},
- {"tsi", {{"long_period", 25}, {"short_period", 13}}},
- {"williams", {{"period", 14}}},
- {"atr", {{"period", 14}}},
- {"bb", {{"period", 20}, {"stddev", 2.0}}},
- {"keltner", {{"period", 20}, {"multiplier", 2.0}}},
- {"donchian", {{"period", 20}}},
- {"chandelier_stop", {{"period", 22}, {"multiplier", 3.0}}},
- {"natr", {{"period", 14}}},
- {"obv", {}},
- {"vwap", {}},
- {"vwma", {{"period", 20}}},
- {"mfi", {{"period", 14}}},
- {"chaikin_osc", {{"fast", 3}, {"slow", 10}}},
- {"force_index", {{"period", 13}}},
- {"ao", {}},
- {"accu_dist", {}},
- {"bop", {}},
- {"chop", {{"period", 14}}},
- {"coppock_curve", {{"roc1", 14}, {"roc2", 11}, {"wma", 10}}},
- {"dpo", {{"period", 20}}},
- {"emv", {{"period", 14}}},
- {"ibs", {}},
- {"kst", {}},
- {"kvo", {{"fast", 34}, {"slow", 55}, {"signal", 13}}},
- {"mass_index", {{"fast", 9}, {"slow", 25}}},
- {"mcginley", {{"period", 14}}},
- {"mean_dev", {{"period", 14}}},
- {"smma", {{"period", 20}}},
- {"sobv", {{"period", 10}}},
- {"stc", {{"period", 12}, {"fast", 26}, {"slow", 50}}},
- {"std_dev", {{"period", 20}}},
- {"trix", {{"period", 15}}},
- {"ttm", {{"period", 20}}},
- {"uo", {{"fast", 7}, {"medium", 14}, {"slow", 28}}},
- {"vtx", {{"period", 14}}},
- {"zigzag", {{"deviation", 5.0}}},
- };
- return m;
-}
-
-QString EquityTalippTab::cat_color(const QString& cat_id) {
- for (const auto& c : categories())
- if (c.id == cat_id)
- return c.color;
- return ui::colors::AMBER;
-}
-
-// ── Constructor ───────────────────────────────────────────────────────────────
-EquityTalippTab::EquityTalippTab(QWidget* parent) : QWidget(parent) {
- build_ui();
- auto& svc = services::equity::EquityResearchService::instance();
- connect(&svc, &services::equity::EquityResearchService::talipp_result, this, &EquityTalippTab::on_talipp_result);
-}
-
-void EquityTalippTab::set_symbol(const QString& symbol) {
- if (symbol == current_symbol_)
- return;
- current_symbol_ = symbol;
- cached_indicator_.clear();
- data_points_lbl_->setText(tr("— data points | TALIpp Engine"));
- status_label_->setText(tr("Select an indicator and click CALCULATE."));
- empty_widget_->show();
- results_widget_->hide();
- loading_overlay_->hide_loading(); // reset overlay on symbol change
-}
-
-// ── build_ui ──────────────────────────────────────────────────────────────────
-void EquityTalippTab::build_ui() {
- setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- loading_overlay_ = new ui::LoadingOverlay(this);
- auto* vl = new QVBoxLayout(this);
- vl->setContentsMargins(10, 10, 10, 10);
- vl->setSpacing(8);
-
- // ── Category tab buttons ──────────────────────────────────────────────────
- auto* cat_row = new QHBoxLayout;
- cat_row->setSpacing(2);
- cat_row->setContentsMargins(0, 0, 0, 0);
-
- for (const auto& cat : categories()) {
- auto* btn = new QPushButton(cat.label);
- btn->setStyleSheet(QString("QPushButton { background:transparent; color:%3; "
- "border:1px solid %1; padding:5px 14px; font-size:10px; font-weight:700; }"
- "QPushButton:hover { border-color:%2; color:%2; }")
- .arg(ui::colors::BORDER_DIM(), cat.color, ui::colors::TEXT_TERTIARY()));
- btn->setProperty("cat_id", cat.id);
- connect(btn, &QPushButton::clicked, this, [this, id = cat.id]() { on_category_clicked(id); });
- cat_buttons_[cat.id] = btn;
- cat_row->addWidget(btn);
- }
- cat_row->addStretch();
- vl->addLayout(cat_row);
-
- // ── Indicator selector + params + run ─────────────────────────────────────
- auto* ctrl_frame = new QFrame;
- ctrl_frame->setStyleSheet(
- QString("QFrame { background:%1; border:1px solid %2; }").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* cl = new QHBoxLayout(ctrl_frame);
- cl->setContentsMargins(12, 10, 12, 10);
- cl->setSpacing(12);
-
- indicator_combo_ = new QComboBox;
- indicator_combo_->setMinimumWidth(200);
- indicator_combo_->setStyleSheet(
- QString(R"(
- QComboBox {
- background:%1; color:%2; border:1px solid %3;
- padding:5px 10px; font-size:12px;
- }
- QComboBox::drop-down { border:0; }
- QComboBox QAbstractItemView {
- background:%1; color:%2; border:1px solid %3;
- selection-background-color:%4;
- }
- )")
- .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM(), ui::colors::AMBER()));
- cl->addWidget(indicator_combo_);
-
- param_widget_ = new QWidget(this);
- param_widget_->setStyleSheet("background:transparent;");
- param_form_ = new QFormLayout(param_widget_);
- param_form_->setContentsMargins(0, 0, 0, 0);
- param_form_->setSpacing(6);
- param_form_->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
- cl->addWidget(param_widget_);
- cl->addStretch();
-
- data_points_lbl_ = new QLabel(tr("— data points | TALIpp Engine"));
- data_points_lbl_->setStyleSheet(
- QString("color:%1; font-size:10px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
- cl->addWidget(data_points_lbl_);
-
- compute_btn_ = new QPushButton(tr("▶ CALCULATE"));
- compute_btn_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:0; padding:6px 18px; "
- "font-size:10px; font-weight:700; }"
- "QPushButton:hover { background:%3; }"
- "QPushButton:disabled { background:%4; color:%5; }")
- .arg(ui::colors::AMBER(), ui::colors::BG_BASE(), ui::colors::AMBER_DIM(),
- ui::colors::TEXT_DIM(), ui::colors::TEXT_TERTIARY()));
- connect(compute_btn_, &QPushButton::clicked, this, &EquityTalippTab::on_compute_clicked);
- cl->addWidget(compute_btn_);
- vl->addWidget(ctrl_frame);
-
- // ── Empty state ───────────────────────────────────────────────────────────
- empty_widget_ = new QFrame;
- empty_widget_->setStyleSheet(
- QString("QFrame { background:%1; border:1px solid %2; }").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* ew_vl = new QVBoxLayout(empty_widget_);
- ew_vl->setAlignment(Qt::AlignCenter);
- ew_vl->setSpacing(8);
-
- auto* ew_icon = new QLabel("◈");
- ew_icon->setAlignment(Qt::AlignCenter);
- ew_icon->setStyleSheet(
- QString("color:%1; font-size:32px; background:transparent; border:0;").arg(ui::colors::TEXT_DIM()));
- status_label_ = new QLabel(tr("Select an indicator and click CALCULATE"));
- status_label_->setAlignment(Qt::AlignCenter);
- status_label_->setStyleSheet(
- QString("color:%1; font-size:13px; background:transparent; border:0;").arg(ui::colors::TEXT_TERTIARY()));
- empty_sub_lbl_ = new QLabel(tr("50+ indicators across 6 categories — powered by TALIpp incremental engine"));
- empty_sub_lbl_->setAlignment(Qt::AlignCenter);
- empty_sub_lbl_->setStyleSheet(
- QString("color:%1; font-size:10px; background:transparent; border:0;").arg(ui::colors::TEXT_DIM()));
- ew_vl->addWidget(ew_icon);
- ew_vl->addWidget(status_label_);
- ew_vl->addWidget(empty_sub_lbl_);
- vl->addWidget(empty_widget_, 1);
-
- // ── Results area (hidden until first compute) ─────────────────────────────
- results_widget_ = new QWidget(this);
- results_widget_->setStyleSheet("background:transparent;");
- auto* rw_vl = new QVBoxLayout(results_widget_);
- rw_vl->setContentsMargins(0, 0, 0, 0);
- rw_vl->setSpacing(8);
-
- last_values_area_ = new QWidget(this);
- last_values_area_->setStyleSheet("background:transparent;");
- new QHBoxLayout(last_values_area_);
- static_cast<QHBoxLayout*>(last_values_area_->layout())->setContentsMargins(0, 0, 0, 0);
- static_cast<QHBoxLayout*>(last_values_area_->layout())->setSpacing(8);
- rw_vl->addWidget(last_values_area_);
-
- chart_view_ = new QChartView;
- chart_view_->setRenderHint(QPainter::Antialiasing, false);
- chart_view_->setMinimumHeight(300);
- chart_view_->setStyleSheet(
- QString("background:%1; border:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- rw_vl->addWidget(chart_view_, 1);
-
- results_widget_->hide();
- vl->addWidget(results_widget_, 1);
-
- connect(indicator_combo_, &QComboBox::currentTextChanged, this, &EquityTalippTab::on_indicator_changed);
-
- on_category_clicked("trend");
-}
-
-// ── on_category_clicked ───────────────────────────────────────────────────────
-void EquityTalippTab::on_category_clicked(const QString& cat_id) {
- active_category_ = cat_id;
-
- for (auto it = cat_buttons_.begin(); it != cat_buttons_.end(); ++it) {
- bool active = (it.key() == cat_id);
- QString color = cat_color(it.key());
- it.value()->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:1px solid %3; "
- "padding:5px 14px; font-size:10px; font-weight:700; }"
- "QPushButton:hover { border-color:%3; }")
- .arg(active ? color : "transparent",
- active ? ui::colors::BG_BASE() : ui::colors::TEXT_TERTIARY(),
- active ? color : ui::colors::BORDER_DIM()));
- }
-
- rebuild_indicator_combo(cat_id);
-}
-
-void EquityTalippTab::rebuild_indicator_combo(const QString& cat_id) {
- indicator_combo_->blockSignals(true);
- indicator_combo_->clear();
- for (const auto& cat : categories()) {
- if (cat.id != cat_id)
- continue;
- for (const auto& item : cat.items)
- indicator_combo_->addItem(item.label, item.id);
- break;
- }
- indicator_combo_->blockSignals(false);
- if (indicator_combo_->count() > 0)
- rebuild_param_form(indicator_combo_->currentData().toString());
-}
-
-// ── on_indicator_changed ──────────────────────────────────────────────────────
-void EquityTalippTab::on_indicator_changed(const QString& /*label*/) {
- rebuild_param_form(indicator_combo_->currentData().toString());
- empty_widget_->show();
- results_widget_->hide();
-}
-
-void EquityTalippTab::rebuild_param_form(const QString& indicator_id) {
- while (param_form_->rowCount() > 0)
- param_form_->removeRow(0);
-
- const auto& defs = param_defs();
- if (!defs.contains(indicator_id))
- return;
-
- for (const auto& [name, default_val] : defs[indicator_id]) {
- auto* spin = new QDoubleSpinBox;
- spin->setObjectName(name);
- spin->setValue(default_val);
- spin->setRange(0.001, 9999);
- spin->setDecimals(name.contains("period") || name == "fast" || name == "slow" || name == "signal" ? 0 : 3);
- spin->setFixedWidth(72);
- spin->setStyleSheet(QString("QDoubleSpinBox { background:%1; color:%2; border:1px solid %3; "
- "padding:3px 6px; font-size:11px; }")
- .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM()));
- auto* lbl = new QLabel(name + ":");
- lbl->setStyleSheet(
- QString("color:%1; font-size:10px; background:transparent; border:0;").arg(ui::colors::TEXT_SECONDARY()));
- param_form_->addRow(lbl, spin);
- }
-}
-
-QVariantMap EquityTalippTab::collect_params() const {
- QVariantMap params;
- for (auto* spin : param_widget_->findChildren<QDoubleSpinBox*>())
- params[spin->objectName()] = spin->value();
- return params;
-}
-
-// ── on_compute_clicked ────────────────────────────────────────────────────────
-void EquityTalippTab::on_compute_clicked() {
- if (current_symbol_.isEmpty()) {
- status_label_->setText(tr("No symbol loaded. Search for a symbol first."));
- return;
- }
- QString id = indicator_combo_->currentData().toString();
- QString label = indicator_combo_->currentText();
- if (id.isEmpty())
- return;
-
- compute_btn_->setEnabled(false);
- compute_btn_->setText(tr("COMPUTING…"));
- status_label_->setText(tr("Computing %1…").arg(label));
- loading_overlay_->show_loading(tr("COMPUTING %1…").arg(label.toUpper()));
- empty_widget_->show();
- results_widget_->hide();
-
- services::equity::EquityResearchService::instance().compute_talipp(current_symbol_, id, collect_params(), "2y");
-}
-
-// ── rebuild_last_values ───────────────────────────────────────────────────────
-void EquityTalippTab::rebuild_last_values(const QString& /*indicator_id*/, const QVector<double>& values) {
- auto* hl = qobject_cast<QHBoxLayout*>(last_values_area_->layout());
- if (!hl)
- return;
- while (hl->count() > 0) {
- auto* item = hl->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
-
- auto make_lv = [&](const QString& lbl, const QString& val, const QString& color) {
- auto* w = new QFrame;
- w->setStyleSheet(QString("QFrame { background:%1; border:1px solid %2; }")
- .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* wl = new QVBoxLayout(w);
- wl->setContentsMargins(12, 8, 12, 8);
- wl->setSpacing(2);
- auto* l = new QLabel(lbl);
- l->setStyleSheet(QString("color:%1; font-size:9px; letter-spacing:0.5px; "
- "background:transparent; border:0;")
- .arg(ui::colors::TEXT_TERTIARY()));
- auto* v = new QLabel(val);
- v->setStyleSheet(QString("color:%1; font-size:15px; font-weight:700; font-family:monospace; "
- "background:transparent; border:0;")
- .arg(color));
- wl->addWidget(l);
- wl->addWidget(v);
- hl->addWidget(w);
- };
-
- if (!values.isEmpty()) {
- double last = values.last();
- make_lv(tr("LAST"), !qIsNaN(last) ? QString::number(last, 'f', 4) : tr("N/A"), ui::colors::AMBER);
- }
-
- for (auto* spin : param_widget_->findChildren<QDoubleSpinBox*>())
- make_lv(spin->objectName().toUpper(), QString::number(spin->value(), 'f', 0), ui::colors::TEXT_TERTIARY());
-
- hl->addStretch();
-}
-
-// ── rebuild_chart ─────────────────────────────────────────────────────────────
-void EquityTalippTab::rebuild_chart(const QString& /*indicator_id*/, const QVector<double>& values,
- const QVector<qint64>& timestamps) {
- QString color = cat_color(active_category_);
- QString label = indicator_combo_->currentText();
-
- auto* series = new QLineSeries;
- series->setName(label);
- {
- QPen pen(QColor(color), 2, Qt::SolidLine);
- series->setPen(pen);
- }
-
- for (int i = 0; i < values.size() && i < timestamps.size(); ++i) {
- if (!qIsNaN(values[i]) && !qIsInf(values[i]))
- series->append(static_cast<qreal>(timestamps[i]) * 1000.0, values[i]);
- }
-
- auto* chart = new QChart;
- chart->addSeries(series);
- chart->setBackgroundBrush(QBrush(QColor(ui::colors::BG_SURFACE())));
- chart->setPlotAreaBackgroundBrush(QBrush(QColor(ui::colors::BG_BASE())));
- chart->setPlotAreaBackgroundVisible(true);
- chart->legend()->hide();
- chart->setMargins(QMargins(4, 4, 4, 4));
- chart->setTitle(label.toUpper() + " — " + QString(active_category_).toUpper());
- QFont title_font("", 10, QFont::Bold);
- chart->setTitleFont(title_font);
- chart->setTitleBrush(QBrush(QColor(color)));
-
- auto* axisX = new QDateTimeAxis;
- axisX->setFormat("MMM yy");
- axisX->setLabelsColor(QColor(ui::colors::TEXT_TERTIARY()));
- axisX->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
- axisX->setLabelsFont(QFont("", 8));
- chart->addAxis(axisX, Qt::AlignBottom);
- series->attachAxis(axisX);
-
- auto* axisY = new QValueAxis;
- axisY->setLabelsColor(QColor(ui::colors::TEXT_TERTIARY()));
- axisY->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
- axisY->setLabelsFont(QFont("", 8));
- chart->addAxis(axisY, Qt::AlignLeft);
- series->attachAxis(axisY);
-
- chart_view_->setChart(chart);
-}
-
-// ── on_talipp_result ──────────────────────────────────────────────────────────
-void EquityTalippTab::on_talipp_result(QString indicator, QVector<double> values, QVector<qint64> timestamps) {
- compute_btn_->setEnabled(true);
- compute_btn_->setText(tr("▶ CALCULATE"));
- loading_overlay_->hide_loading();
-
- if (values.isEmpty()) {
- status_label_->setText(tr("No data returned for %1").arg(indicator));
- empty_widget_->show();
- results_widget_->hide();
- return;
- }
-
- cached_indicator_ = indicator;
- rebuild_last_values(indicator, values);
- rebuild_chart(indicator, values, timestamps);
-
- empty_widget_->hide();
- results_widget_->show();
-}
-
-// ── Re-translation ───────────────────────────────────────────────────────────
-// Static chrome (button text, idle status text, data-points caption, empty-
-// state copy). Category tab labels and indicator names stay as the
-// originally-loaded strings — these are technical-analysis terms (SMA,
-// MACD, etc.) that conventionally remain English across locales.
-
-void EquityTalippTab::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange) {
- retranslateUi();
- }
- QWidget::changeEvent(event);
-}
-
-void EquityTalippTab::retranslateUi() {
- if (compute_btn_) compute_btn_->setText(tr("▶ CALCULATE"));
- if (data_points_lbl_)data_points_lbl_->setText(tr("— data points | TALIpp Engine"));
- if (empty_sub_lbl_) empty_sub_lbl_->setText(tr("50+ indicators across 6 categories — powered by TALIpp incremental engine"));
-
- if (status_label_) {
- // Pick the right idle line for the current state — never overwrite a
- // live "Computing…" message mid-fetch.
- if (current_symbol_.isEmpty())
- status_label_->setText(tr("Select an indicator and click CALCULATE."));
- else if (cached_indicator_.isEmpty())
- status_label_->setText(tr("Select an indicator and click CALCULATE"));
- }
-}
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_research/EquityTalippTab.h b/fincept-qt/src/screens/equity_research/EquityTalippTab.h
deleted file mode 100644
index 03016f150..000000000
--- a/fincept-qt/src/screens/equity_research/EquityTalippTab.h
+++ /dev/null
@@ -1,80 +0,0 @@
-// src/screens/equity_research/EquityTalippTab.h
-#pragma once
-#include "services/equity/EquityResearchModels.h"
-#include "ui/widgets/LoadingOverlay.h"
-
-#include <QChartView>
-#include <QComboBox>
-#include <QFormLayout>
-#include <QLabel>
-#include <QMap>
-#include <QPushButton>
-#include <QScrollArea>
-#include <QWidget>
-
-namespace fincept::screens {
-
-class EquityTalippTab : public QWidget {
- Q_OBJECT
- public:
- explicit EquityTalippTab(QWidget* parent = nullptr);
- void set_symbol(const QString& symbol);
-
- protected:
- void changeEvent(QEvent* event) override;
-
- private slots:
- void on_category_clicked(const QString& cat_id);
- void on_indicator_changed(const QString& indicator);
- void on_compute_clicked();
- void on_talipp_result(QString indicator, QVector<double> values, QVector<qint64> timestamps);
-
- private:
- void build_ui();
- void retranslateUi();
- void rebuild_indicator_combo(const QString& cat_id);
- void rebuild_param_form(const QString& indicator);
- void rebuild_last_values(const QString& indicator, const QVector<double>& values);
- void rebuild_chart(const QString& indicator, const QVector<double>& values, const QVector<qint64>& timestamps);
- QVariantMap collect_params() const;
-
- QString current_symbol_;
- QString active_category_ = "trend";
- QLabel* empty_sub_lbl_ = nullptr; ///< "50+ indicators across…" caption
- QString cached_indicator_; ///< last computed indicator for retranslate
-
- // Category tab buttons
- QMap<QString, QPushButton*> cat_buttons_;
-
- QComboBox* indicator_combo_ = nullptr;
- QWidget* param_widget_ = nullptr;
- QFormLayout* param_form_ = nullptr;
- QLabel* status_label_ = nullptr;
- QWidget* last_values_area_ = nullptr;
- QChartView* chart_view_ = nullptr;
- QWidget* results_widget_ = nullptr;
- QWidget* empty_widget_ = nullptr;
- QLabel* data_points_lbl_ = nullptr;
- QPushButton* compute_btn_ = nullptr;
-
- struct IndicatorDef {
- QString id;
- QString label;
- QString data_type; // "prices" | "ohlcv"
- };
-
- struct CategoryDef {
- QString id;
- QString label;
- QString color;
- QList<IndicatorDef> items;
- };
-
- static const QList<CategoryDef>& categories();
- static const QMap<QString, QList<QPair<QString, double>>>& param_defs();
- static QString cat_color(const QString& cat_id);
-
- ui::LoadingOverlay* loading_overlay_ = nullptr;
-};
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
index 2da11041a..84421457f 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
@@ -16,6 +16,7 @@
#include <QDesktopServices>
#include <QFrame>
#include <QHBoxLayout>
+#include <QInputDialog>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
@@ -50,6 +51,135 @@ static QLabel* make_field_label(const QString& text) {
return l;
}
+// Assembled exchange_token() inputs. The generic dialog collects one value per
+// declared CredentialField, but each broker's exchange_token(api_key, api_secret,
+// auth_code) parses those three args differently (some pack multiple secrets into
+// one). Centralising the packing here keeps per-broker quirks in ONE place
+// instead of scattered branches in the connect handler — add a broker by adding
+// one case below, not by editing the form + handler + loader separately.
+struct ExchangeArgs {
+ QString api_key;
+ QString api_secret;
+ QString auth_code;
+ QString additional_data; // pre-exchange additional_data to merge after token exchange
+};
+
+static ExchangeArgs assemble_exchange_args(const QString& broker_id,
+ const QMap<int, QString>& f) {
+ using CF = CredentialField;
+ ExchangeArgs a;
+ a.api_key = f.value(static_cast<int>(CF::ApiKey));
+ a.api_secret = f.value(static_cast<int>(CF::ApiSecret));
+ a.auth_code = f.value(static_cast<int>(CF::AuthCode));
+ const QString client_code = f.value(static_cast<int>(CF::ClientCode));
+
+ if (broker_id == QLatin1String("angelone")) {
+ // AngelOne logs in via TOTP: exchange_token() expects client_code AND the
+ // Base32 TOTP secret packed into auth_code as JSON {"client_code","totp_secret"}
+ // (AngelOneBroker.cpp). exchange_token() never receives additional_data, so
+ // the old generic path — which stashed client_code in additional_data and
+ // passed the bare TOTP secret as auth_code — always failed with
+ // "Client code is required". Pack them the way the broker parses them.
+ const QJsonObject o{{"client_code", client_code}, {"totp_secret", a.auth_code}};
+ a.auth_code = QJsonDocument(o).toJson(QJsonDocument::Compact);
+ return a; // api_key = API key, api_secret = MPIN (already set above)
+ }
+
+ // Default mapping (unchanged historical behaviour): api_key/api_secret/auth_code
+ // pass straight through; a ClientCode field rides in additional_data as JSON so
+ // load_saved_credentials() can repopulate it on reopen.
+ if (!client_code.isEmpty())
+ a.additional_data =
+ QJsonDocument(QJsonObject{{"client_code", client_code}}).toJson(QJsonDocument::Compact);
+ return a;
+}
+
+// ── Custom multi-sub-field credential forms ──────────────────────────────────
+// Some brokers pack several distinct secrets into a single exchange_token() arg
+// with a delimiter (e.g. fivepaisa api_key = "app:::user:::client"). The plain
+// profile form has one box per CredentialField, which forced the user to hand-
+// type the delimiters into one box — undiscoverable and error-prone. Instead we
+// render one labelled box PER real secret and pack them here exactly the way each
+// broker's exchange_token() parses them (verified against each <Broker>.cpp).
+struct CredSubField {
+ QString key; // identifier used by the packer below
+ QString label; // UI label
+ bool secret; // echo as password
+};
+
+// Returns the custom sub-field list for a broker, or empty if the broker uses the
+// plain profile-driven form. Keys MUST match pack_custom_credentials() below.
+static QVector<CredSubField> custom_cred_fields(const QString& broker_id) {
+ if (broker_id == QLatin1String("fivepaisa"))
+ return {{"app_key", QObject::tr("APP KEY"), false},
+ {"user_id", QObject::tr("USER ID"), false},
+ {"client_id", QObject::tr("CLIENT ID"), false},
+ {"app_secret", QObject::tr("APP SECRET (EncryKey)"), true},
+ {"email", QObject::tr("EMAIL"), false},
+ {"pin", QObject::tr("PIN"), true},
+ {"totp", QObject::tr("TOTP (current 6-digit code)"), true}};
+ if (broker_id == QLatin1String("iifl"))
+ return {{"trade_app_key", QObject::tr("INTERACTIVE APP KEY"), false},
+ {"trade_secret", QObject::tr("INTERACTIVE SECRET KEY"), true},
+ {"market_app_key", QObject::tr("MARKET-DATA APP KEY"), false},
+ {"market_secret", QObject::tr("MARKET-DATA SECRET KEY"), true}};
+ if (broker_id == QLatin1String("kotak"))
+ return {{"portal_token", QObject::tr("ACCESS TOKEN (from Kotak Neo portal)"), true},
+ {"mobile", QObject::tr("MOBILE NUMBER (10-digit or +91…)"), false},
+ {"ucc", QObject::tr("UCC (Client ID)"), false},
+ {"mpin", QObject::tr("MPIN"), true},
+ {"totp_secret", QObject::tr("TOTP SECRET (Base32)"), true}};
+ if (broker_id == QLatin1String("flattrade"))
+ return {{"uid", QObject::tr("CLIENT ID (UID)"), false},
+ {"apikey", QObject::tr("API KEY"), true},
+ {"api_secret", QObject::tr("API SECRET"), true},
+ {"request_code", QObject::tr("REQUEST CODE (from web login)"), false}};
+ if (broker_id == QLatin1String("shoonya"))
+ return {{"uid", QObject::tr("USER ID"), false},
+ {"password", QObject::tr("PASSWORD"), true},
+ {"vendor_code", QObject::tr("VENDOR CODE"), false},
+ {"totp", QObject::tr("TOTP (current 6-digit code)"), true}};
+ if (broker_id == QLatin1String("motilal"))
+ return {{"userid", QObject::tr("USER ID / API KEY"), false},
+ {"password", QObject::tr("PASSWORD"), true},
+ {"dob", QObject::tr("DATE OF BIRTH (DD/MM/YYYY)"), false},
+ {"totp", QObject::tr("TOTP (current 6-digit code, if enabled)"), true}};
+ return {};
+}
+
+// Pack custom sub-field values into the exact exchange_token() args each broker
+// parses. Delimiters/order verified against the corresponding <Broker>.cpp.
+static ExchangeArgs pack_custom_credentials(const QString& broker_id, const QMap<QString, QString>& v) {
+ const QString S = QStringLiteral(":::");
+ ExchangeArgs a;
+ if (broker_id == QLatin1String("fivepaisa")) {
+ a.api_key = v.value("app_key") + S + v.value("user_id") + S + v.value("client_id");
+ a.api_secret = v.value("app_secret");
+ a.auth_code = v.value("email") + S + v.value("pin") + S + v.value("totp");
+ } else if (broker_id == QLatin1String("iifl")) {
+ a.api_key = v.value("trade_app_key") + S + v.value("trade_secret");
+ a.api_secret = v.value("market_app_key") + S + v.value("market_secret");
+ } else if (broker_id == QLatin1String("kotak")) {
+ a.api_key = v.value("portal_token") + QStringLiteral("|||") + v.value("mobile")
+ + QStringLiteral("|||") + v.value("ucc");
+ a.api_secret = v.value("mpin");
+ a.auth_code = v.value("totp_secret");
+ } else if (broker_id == QLatin1String("flattrade")) {
+ a.api_key = v.value("uid") + S + v.value("apikey");
+ a.api_secret = v.value("api_secret");
+ a.auth_code = v.value("request_code");
+ } else if (broker_id == QLatin1String("shoonya")) {
+ a.api_key = v.value("uid");
+ a.api_secret = v.value("password");
+ a.auth_code = v.value("vendor_code") + S + v.value("totp");
+ } else if (broker_id == QLatin1String("motilal")) {
+ a.api_key = v.value("userid");
+ a.api_secret = v.value("password");
+ a.auth_code = v.value("dob") + S + v.value("totp");
+ }
+ return a;
+}
+
// ── constructor ──────────────────────────────────────────────────────────────
AccountManagementDialog::AccountManagementDialog(QWidget* parent)
@@ -430,6 +560,7 @@ void AccountManagementDialog::build_credential_form(const trading::BrokerProfile
f->deleteLater();
cred_fields_.clear();
cred_field_defs_ = profile.credential_fields;
+ cred_form_keys_.clear();
// Remove old widgets from layout
while (fields_layout_->count() > 0) {
@@ -439,6 +570,22 @@ void AccountManagementDialog::build_credential_form(const trading::BrokerProfile
delete item;
}
+ // Brokers that pack several secrets into one exchange_token() arg get a custom
+ // multi-sub-field form — one labelled box per real secret — instead of the
+ // plain profile form (which would force the user to hand-type ":::"/"|||"
+ // delimiters). on_connect_account packs the values back via pack_custom_credentials.
+ const auto custom = custom_cred_fields(profile.id);
+ if (!custom.isEmpty()) {
+ for (const auto& sf : custom) {
+ fields_layout_->addWidget(make_field_label(sf.label));
+ auto* field = make_field(QString(), sf.secret);
+ fields_layout_->addWidget(field);
+ cred_fields_.append(field);
+ cred_form_keys_.append(sf.key);
+ }
+ return;
+ }
+
// Build fields from BrokerProfile::credential_fields
for (const auto& def : profile.credential_fields) {
if (def.field == CredentialField::Environment)
@@ -492,6 +639,12 @@ void AccountManagementDialog::load_saved_credentials(const QString& account_id)
return;
}
+ // Custom multi-sub-field forms (delimiter brokers) can't be cleanly unpacked
+ // back into individual boxes — and they're daily-expiring TOTP logins anyway —
+ // so leave them blank for re-entry rather than mis-populate from packed creds.
+ if (!cred_form_keys_.isEmpty())
+ return;
+
int idx = 0;
for (const auto& def : cred_field_defs_) {
if (def.field == CredentialField::Environment)
@@ -592,36 +745,36 @@ void AccountManagementDialog::on_connect_account() {
if (!broker)
return;
- // Collect credentials from form fields
+ // Collect one raw value per declared credential field, then assemble the exact
+ // exchange_token() arguments this broker expects. assemble_exchange_args()
+ // centralises per-broker packing (e.g. AngelOne needs client_code + TOTP secret
+ // packed into auth_code as JSON) so brokers like AngelOne actually connect.
BrokerCredentials creds;
creds.broker_id = account.broker_id;
- QString auth_code;
- int idx = 0;
- for (const auto& def : cred_field_defs_) {
- if (def.field == CredentialField::Environment)
- continue;
- if (idx >= cred_fields_.size())
- break;
- const QString val = cred_fields_[idx]->text().trimmed();
- switch (def.field) {
- case CredentialField::ApiKey:
- creds.api_key = val;
- break;
- case CredentialField::ApiSecret:
- creds.api_secret = val;
- break;
- case CredentialField::AuthCode:
- auth_code = val;
- break;
- case CredentialField::ClientCode:
- // Store in additional_data as JSON
- creds.additional_data = QJsonDocument(QJsonObject{{"client_code", val}}).toJson(QJsonDocument::Compact);
- break;
- default:
- break;
+ ExchangeArgs ex;
+ if (!cred_form_keys_.isEmpty()) {
+ // Custom multi-sub-field form: collect values by key, pack per broker.
+ QMap<QString, QString> kv;
+ for (int i = 0; i < cred_form_keys_.size() && i < cred_fields_.size(); ++i)
+ kv.insert(cred_form_keys_[i], cred_fields_[i]->text().trimmed());
+ ex = pack_custom_credentials(account.broker_id, kv);
+ } else {
+ QMap<int, QString> field_values;
+ int idx = 0;
+ for (const auto& def : cred_field_defs_) {
+ if (def.field == CredentialField::Environment)
+ continue;
+ if (idx >= cred_fields_.size())
+ break;
+ field_values.insert(static_cast<int>(def.field), cred_fields_[idx]->text().trimmed());
+ ++idx;
}
- ++idx;
+ ex = assemble_exchange_args(account.broker_id, field_values);
}
+ creds.api_key = ex.api_key;
+ creds.api_secret = ex.api_secret;
+ creds.additional_data = ex.additional_data;
+ QString auth_code = ex.auth_code;
// Attempt token exchange asynchronously — exchange_token() makes a blocking
// HTTP call (BrokerHttp::execute uses QEventLoop), so running it on the UI
@@ -697,17 +850,37 @@ void AccountManagementDialog::on_connect_account() {
}
void AccountManagementDialog::on_rename_account() {
- if (selected_account_id_.isEmpty())
+ if (selected_account_id_.isEmpty()) {
+ QMessageBox::information(this, tr("Rename Account"),
+ tr("Select an account first, then rename it."));
return;
- const QString new_name = display_name_input_->text().trimmed();
- if (new_name.isEmpty())
+ }
+
+ // Ask for the new name inline, seeded with the current one. The RENAME
+ // buttons live on the right-hand broker forms — far from the left-panel
+ // "Account name..." field, which is shared with + ADD. The old handler read
+ // that field, so RENAME silently did nothing whenever it was empty (the
+ // common case), making the button look dead. Prompting here makes every
+ // RENAME button self-contained.
+ const QString acct_id = selected_account_id_;
+ const auto account = AccountManager::instance().get_account(acct_id);
+ bool ok = false;
+ const QString new_name =
+ QInputDialog::getText(this, tr("Rename Account"), tr("New account name:"),
+ QLineEdit::Normal, account.display_name, &ok)
+ .trimmed();
+ if (!ok || new_name.isEmpty() || new_name == account.display_name)
return;
- AccountManager::instance().update_display_name(selected_account_id_, new_name);
- display_name_input_->clear();
+
+ AccountManager::instance().update_display_name(acct_id, new_name);
+
+ // refresh_account_list() clears the list, which emits currentRowChanged(-1)
+ // and wipes selected_account_id_ — so re-select via the captured acct_id,
+ // not the member. Re-selecting also refreshes the broker form's title with
+ // the new name.
refresh_account_list();
- // Re-select the account
for (int i = 0; i < account_list_->count(); ++i) {
- if (account_list_->item(i)->data(Qt::UserRole).toString() == selected_account_id_) {
+ if (account_list_->item(i)->data(Qt::UserRole).toString() == acct_id) {
account_list_->setCurrentRow(i);
break;
}
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h
index 2e944c5ac..f6cbcf12f 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.h
@@ -103,6 +103,11 @@ class AccountManagementDialog : public QDialog {
// Dynamic credential fields (rebuilt per broker profile)
QVector<QLineEdit*> cred_fields_;
QVector<trading::CredentialFieldDef> cred_field_defs_;
+ // Non-empty when the focused broker uses a custom multi-sub-field form (the
+ // delimiter brokers — fivepaisa/iifl/kotak/flattrade/shoonya/motilal — whose
+ // exchange_token() packs several secrets into one arg). Holds the per-field
+ // keys, row-aligned with cred_fields_, used to pack the values back together.
+ QStringList cred_form_keys_;
// Zerodha-specific widgets
QLabel* z_title_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index d1cc2bb7b..f3b3ff31e 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -201,6 +201,7 @@ void EquityBottomPanel::retranslateUi() {
if (close_all_btn_) close_all_btn_->setText(tr("SQUARE OFF ALL"));
if (cancel_all_btn_) cancel_all_btn_->setText(tr("CANCEL ALL ORDERS"));
if (holdings_import_btn_) holdings_import_btn_->setText(tr("IMPORT TO PORTFOLIO"));
+ if (holdings_square_off_btn_) holdings_square_off_btn_->setText(tr("SQUARE OFF ALL"));
// Holdings summary-strip captions
if (holdings_count_caption_) holdings_count_caption_->setText(tr("HOLDINGS"));
@@ -451,13 +452,44 @@ void EquityBottomPanel::setup_holdings_tab() {
[this]() { emit replicate_portfolio_requested(); });
strip_layout->addWidget(holdings_replicate_btn_);
+ // SQUARE OFF ALL — sells every holding (delivery/CNC) at market. Mirrors the
+ // Positions tab button, but acts ONLY on holdings; positions are untouched.
+ holdings_square_off_btn_ = new QPushButton(tr("SQUARE OFF ALL"));
+ holdings_square_off_btn_->setCursor(Qt::PointingHandCursor);
+ holdings_square_off_btn_->setEnabled(false);
+ holdings_square_off_btn_->setStyleSheet(
+ QString("QPushButton{background:rgba(220,38,38,0.12);color:%1;border:1px solid %2;"
+ "padding:4px 14px;font-size:11px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"
+ "QPushButton:hover{background:rgba(220,38,38,0.25);}"
+ "QPushButton:disabled{color:%3;border-color:%2;}")
+ .arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::NEGATIVE_DIM(),
+ fincept::ui::colors::TEXT_SECONDARY()));
+ connect(holdings_square_off_btn_, &QPushButton::clicked, this, [this]() {
+ LOG_INFO("sqoff", QString("[panel] SQUARE OFF ALL clicked: account_id='%1' holdings=%2")
+ .arg(account_id_)
+ .arg(last_holdings_.size()));
+ if (account_id_.isEmpty() || last_holdings_.isEmpty())
+ return;
+ auto answer = QMessageBox::warning(
+ this, tr("Square Off All Holdings"),
+ tr("This will place MARKET SELL orders to exit ALL %1 holding(s).\n\n"
+ "Positions are NOT affected. Are you sure?")
+ .arg(last_holdings_.size()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes)
+ return;
+ emit square_off_all_holdings_requested(last_holdings_);
+ });
+ strip_layout->addWidget(holdings_square_off_btn_);
+
v->addWidget(strip);
holdings_table_ = new QTableWidget;
holdings_table_->setObjectName("eqTable");
- holdings_table_->setColumnCount(8);
- holdings_table_->setHorizontalHeaderLabels(
- {tr("Symbol"), tr("Qty"), tr("Avg Price"), tr("LTP"), tr("Invested"), tr("Current"), tr("P&L"), tr("P&L %")});
+ holdings_table_->setColumnCount(9);
+ holdings_table_->setHorizontalHeaderLabels({tr("Symbol"), tr("Qty"), tr("Avg Price"), tr("LTP"),
+ tr("Invested"), tr("Current"), tr("P&L"), tr("P&L %"),
+ tr("Action")});
holdings_table_->verticalHeader()->setVisible(false);
holdings_table_->setSelectionBehavior(QAbstractItemView::SelectRows);
holdings_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
@@ -660,12 +692,31 @@ void EquityBottomPanel::setup_stats_tab() {
// ── Data Setters ───────────────────────────────────────────────────────────
+void EquityBottomPanel::clear_blotter_tables() {
+ if (positions_table_) positions_table_->setRowCount(0);
+ if (holdings_table_) holdings_table_->setRowCount(0);
+ if (orders_table_) orders_table_->setRowCount(0);
+ last_positions_.clear();
+ last_paper_positions_.clear();
+ last_holdings_.clear();
+ update_positions_summary(); // zero the net-P&L / winners-losers strip
+}
+
void EquityBottomPanel::set_mode(bool is_paper) {
+ if (is_paper_ == is_paper)
+ return;
is_paper_ = is_paper;
+ // Paper and live share the same tables — clear so the previous mode's rows
+ // can't linger under the new one until fresh data arrives.
+ clear_blotter_tables();
}
void EquityBottomPanel::set_account_id(const QString& account_id) {
+ if (account_id_ == account_id)
+ return;
account_id_ = account_id;
+ // Different account → drop the previous account's positions/holdings/orders.
+ clear_blotter_tables();
}
void EquityBottomPanel::set_currency(const QString& sym) {
@@ -887,8 +938,12 @@ QWidget* EquityBottomPanel::make_positions_action_cell(const QString& symbol, co
.arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::BORDER_MED()));
const double held = qAbs(qty);
const QString prod = product.isEmpty() ? QStringLiteral("MIS") : product;
- connect(sell, &QPushButton::clicked, this,
- [this, symbol, prod, held]() { emit trade_symbol_requested(symbol, prod, false, held); });
+ connect(sell, &QPushButton::clicked, this, [this, symbol, prod, held]() {
+ LOG_INFO("sqoff", QString("[panel] per-row SELL clicked: sym='%1' prod='%2' qty=%3")
+ .arg(symbol, prod)
+ .arg(held));
+ emit trade_symbol_requested(symbol, prod, false, held);
+ });
lay->addWidget(sell);
// Paper intraday only: convert MIS → CNC (carry overnight).
@@ -1097,6 +1152,8 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
last_holdings_ = holdings;
if (holdings_import_btn_)
holdings_import_btn_->setEnabled(!holdings.isEmpty());
+ if (holdings_square_off_btn_)
+ holdings_square_off_btn_->setEnabled(!holdings.isEmpty());
// Disable sorting during population so setItem assignments stay at intended rows.
const bool was_sorting = holdings_table_->isSortingEnabled();
@@ -1134,6 +1191,32 @@ void EquityBottomPanel::set_holdings(const QVector<trading::BrokerHolding>& hold
pct_item->setData(Qt::EditRole, h.pnl_pct);
pct_item->setForeground(h.pnl_pct >= 0 ? pos_color : neg_color);
+ // 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->setFixedHeight(18);
+ sell_btn->setCursor(Qt::PointingHandCursor);
+ sell_btn->setToolTip(tr("Square off %1 — sells the full holding at market").arg(h.symbol));
+ sell_btn->setStyleSheet(QString("QPushButton#eqTableBtn{background:rgba(239,68,68,0.15);color:%1;"
+ "border:1px solid %2;font-size:10px;padding:0 6px;border-radius:2px;}"
+ "QPushButton#eqTableBtn:hover{background:rgba(239,68,68,0.30);}")
+ .arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::BORDER_MED()));
+ 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, 8, action_cell);
+
total_invested += h.invested_value;
total_current += h.current_value;
total_pnl += h.pnl;
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
index e75245969..f490b5dc2 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h
@@ -75,6 +75,11 @@ class EquityBottomPanel : public QWidget {
void replicate_portfolio_requested();
void cancel_all_orders_requested(const QString& account_id);
void close_all_positions_requested(const QString& account_id);
+ // Square off ALL holdings (delivery/CNC) — carries the current holdings so the
+ // screen can close each. Positions are NOT affected.
+ void square_off_all_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
+ // Square off a single holding (per-row SELL) — screen confirms then closes it.
+ void square_off_holding_requested(const QString& symbol, const QString& exchange);
// Paper: convert an open position's product in place (MIS -> CNC), identified
// by its paper position id.
void convert_position_requested(const QString& position_id, const QString& symbol, const QString& new_product);
@@ -113,6 +118,13 @@ class EquityBottomPanel : public QWidget {
// tick refresh as the Positions table so Holdings tracks in real time.
void update_holding_quote(const QString& symbol, double ltp);
+ // Blank the shared positions/holdings/orders tables (and their row-aligned
+ // caches). Called on every account or paper↔live transition so one account's
+ // (or one mode's) data never lingers under another — e.g. Fyers paper orders
+ // showing under a Zerodha live account. The incoming context repaints via
+ // refresh_paper_panels() (paper) or the live broker hub topics (live).
+ void clear_blotter_tables();
+
static QTableWidgetItem* ensure_item(QTableWidget* table, int row, int col);
// Build the Positions "Action" cell: a SELL button (opens an order ticket
@@ -167,6 +179,7 @@ class EquityBottomPanel : public QWidget {
QLabel* holdings_pnl_pct_caption_ = nullptr;
class QPushButton* holdings_import_btn_ = nullptr;
class QPushButton* holdings_replicate_btn_ = nullptr;
+ class QPushButton* holdings_square_off_btn_ = nullptr;
QVector<trading::BrokerHolding> last_holdings_;
QTableWidget* orders_table_ = nullptr;
QDateEdit* orders_date_edit_ = nullptr; // per-day order book selector
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 86594d8cb..346d59490 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -155,6 +155,14 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
// Hub subscriptions for streaming data (D4)
hub_subscribe_streaming();
+ // On REOPEN (not first show — init_focused_account handles that), the stream
+ // stayed running while hidden, so neither start() nor resume() re-fetches the
+ // portfolio. Force an immediate live refresh so Holdings/Positions/Orders show
+ // current broker data right away instead of staying stale (or blank) until the
+ // 5-min poll. Paper data is repainted by refresh_paper_panels() just below.
+ if (initialized_ && !focused_is_paper_ && !focused_account_id_.isEmpty())
+ DataStreamManager::instance().refresh_portfolio(focused_account_id_);
+
// Catch up intraday auto-square for paper portfolios (e.g. the app was closed
// at 15:30, so yesterday's MIS positions never squared). Refresh picks up the
// resulting state; it no-ops for live accounts.
@@ -431,6 +439,10 @@ void EquityTradingScreen::setup_ui() {
[this](const QString&) { on_cancel_all_orders(); });
connect(bottom_panel_, &EquityBottomPanel::close_all_positions_requested, this,
[this](const QString&) { on_close_all_positions(); });
+ connect(bottom_panel_, &EquityBottomPanel::square_off_all_holdings_requested, this,
+ &EquityTradingScreen::on_square_off_all_holdings);
+ connect(bottom_panel_, &EquityBottomPanel::square_off_holding_requested, this,
+ &EquityTradingScreen::on_square_off_holding);
connect(bottom_panel_, &EquityBottomPanel::import_holdings_requested, this, &EquityTradingScreen::on_import_holdings_requested);
connect(bottom_panel_, &EquityBottomPanel::replicate_portfolio_requested, this,
&EquityTradingScreen::on_replicate_portfolio_requested);
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index bc8f7b8b9..98e01253c 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -61,6 +61,20 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void restore_state(const QVariantMap& state) override;
QString state_key() const override { return QStringLiteral("equity_trading"); }
+ // External entry point — opens the SAME quick order ticket used in-screen for
+ // an arbitrary symbol/side, driven from another screen (e.g. Equity Research).
+ // Ensures a broker account is focused (the credential-aware pick this tab uses
+ // on show) and seeds a reference price the caller already has, so paper market
+ // orders fill even when this screen's own quote stream hasn't ticked for the
+ // symbol. The trading tab's own symbol selection is saved and restored, so this
+ // never disturbs an in-progress trade here. Reuses open_order_ticket_for() +
+ // on_order_submitted() — no duplicate form, no duplicate placement logic.
+ // match_exchanges are the broker exchanges that can trade the symbol's market
+ // (e.g. {"NSE"} or the US venues); the order routes to a usable account whose
+ // broker serves one of them, so multi-broker setups pick the right account.
+ void open_external_order_ticket(const QString& symbol, const QString& exchange,
+ const QStringList& match_exchanges, bool is_buy, double ref_price);
+
protected:
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
@@ -78,7 +92,12 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void on_order_submitted(const trading::UnifiedOrder& order);
void on_cancel_order(const QString& order_id);
void on_cancel_all_orders(); // CANCEL ALL ORDERS button
- void on_close_all_positions(); // SQUARE OFF ALL button
+ void on_close_all_positions(); // SQUARE OFF ALL button (positions)
+ // SQUARE OFF ALL button on the Holdings tab — market-sells every holding
+ // (CNC/delivery). Acts ONLY on holdings; positions are untouched.
+ void on_square_off_all_holdings(const QVector<trading::BrokerHolding>& holdings);
+ // Per-row SELL on the Holdings tab — confirm then close that single holding.
+ void on_square_off_holding(const QString& symbol, const QString& exchange);
void on_strategy_submitted(const trading::BasketOrderRequest& basket); // options strategy → basket
void on_ob_price_clicked(double price);
void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
@@ -154,6 +173,10 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
// from the positions/holdings tables). Routes through on_order_submitted().
void open_order_ticket_for(const QString& symbol, const QString& exchange, const QString& product, bool is_buy,
double qty = 0.0);
+ // Pick a usable account (paper, or live + Connected) whose broker can trade one
+ // of `match_exchanges` (broker.exchanges ∩ match). Prefers the already-focused
+ // account, then a live match, then a paper match. Empty when nothing matches.
+ QString pick_account_for_exchanges(const QStringList& match) const;
// Re-reads the focused account's paper portfolio into the panels. No-op for
// live accounts (their data flows from AccountDataStream via the hub).
void refresh_paper_panels();
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 917aa8a75..9c7bdb5e2 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -146,6 +146,12 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
// handler will re-run the data-fetch path once the user connects.
const bool has_creds = !AccountManager::instance().load_credentials(account_id).api_key.isEmpty();
auto& dsm = DataStreamManager::instance();
+ // If the stream is ALREADY running, start_stream() below is a no-op and does
+ // NOT re-fetch the portfolio. A fresh start() fetches on its own, so we only
+ // force a refresh in the already-running case — never stack a second fetch
+ // batch on a fresh start (firing too many async fetches at once has crashed
+ // macOS; see the credentials note below).
+ const bool stream_existed = dsm.has_stream(account_id);
if (has_creds) {
// Load the broker instrument master (numeric securityId map) so quotes,
// charts and depth resolve. Loads from the SQLite cache when present,
@@ -167,6 +173,13 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
}
}
+ // Switching accounts cleared the shared blotter (EquityBottomPanel::
+ // set_account_id). For a live account whose stream was already running, force
+ // an immediate portfolio refetch so it refills with THIS account's positions/
+ // holdings/orders right away instead of staying blank until the 5-min poll.
+ if (has_creds && is_live && stream_existed)
+ dsm.refresh_portfolio(account_id);
+
// Each account's order book opens on today's session.
orders_view_day_ = QDate::currentDate();
@@ -315,8 +328,13 @@ void EquityTradingScreen::on_mode_toggled() {
if (!is_live) {
refresh_paper_panels(); // positions/orders/trades/stats/funds from the paper engine
+ } else {
+ // Switching to live: set_mode() just cleared the shared blotter and the
+ // stream is already running (so it won't re-fetch on its own). Force an
+ // immediate refresh so live positions/holdings/orders appear now instead
+ // of leaving the blotter blank until the 5-min poll.
+ DataStreamManager::instance().refresh_portfolio(focused_account_id_);
}
- // Live mode data comes automatically from the running AccountDataStream
}
void EquityTradingScreen::handle_token_expired(const QString& account_id) {
@@ -688,7 +706,12 @@ void EquityTradingScreen::refresh_paper_panels() {
h.ltp = p.current_price > 0.0 ? p.current_price : p.entry_price;
h.invested_value = p.entry_price * p.quantity;
h.current_value = h.ltp * p.quantity;
- h.pnl = h.current_value - h.invested_value;
+ // Sign P&L by side: a short position gains when price falls. Using the
+ // long formula unconditionally inverted short-side P&L and corrupted
+ // holdings_value/total_equity.
+ h.pnl = (p.side.compare("short", Qt::CaseInsensitive) == 0)
+ ? (h.invested_value - h.current_value)
+ : (h.current_value - h.invested_value);
h.pnl_pct = h.invested_value > 0.0 ? (h.pnl / h.invested_value) * 100.0 : 0.0;
holdings.push_back(h);
holdings_value += h.current_value;
@@ -730,9 +753,12 @@ void EquityTradingScreen::refresh_paper_panels() {
// ── Stats card view ──
EquityStatsView sv;
sv.currency = sym;
- sv.realized_pnl = stats.total_pnl; // all-time realized
+ sv.realized_pnl = stats.total_pnl; // all-time realized (gross of fees)
sv.unrealized_pnl = unrealized;
- sv.net_pnl = stats.total_pnl + unrealized;
+ // Net P&L is the bottom line: realized − fees + unrealized. This makes
+ // net_pnl == (total_equity − opening_balance); previously it omitted fees,
+ // so Net P&L / Return % read higher than the actual account gain.
+ sv.net_pnl = stats.total_pnl - stats.total_fees + unrealized;
sv.today_pnl = stats.today_pnl;
sv.return_pct = portfolio.initial_balance > 0.0 ? (sv.net_pnl / portfolio.initial_balance) * 100.0 : 0.0;
sv.win_rate = stats.win_rate;
@@ -748,6 +774,24 @@ void EquityTradingScreen::refresh_paper_panels() {
sv.turnover = stats.turnover;
bottom_panel_->set_stats_view(sv);
+ // [TEMP DEBUG] Capture the paper accounting so we can see exactly where an
+ // import/replicate inflates the total. balance should DROP by purchase cost
+ // and holdings_value should rise by ~the same → total_equity ≈ opening.
+ LOG_INFO("statsdbg",
+ QString("[paper-stats] acct=%1 opening=%2 balance=%3 used_margin=%4 holdings_value=%5 "
+ "mis_unreal=%6 total_equity=%7 #pos=%8 #holdings=%9 realized=%10 unreal=%11")
+ .arg(account.paper_portfolio_id)
+ .arg(portfolio.initial_balance, 0, 'f', 2)
+ .arg(portfolio.balance, 0, 'f', 2)
+ .arg(used_margin, 0, 'f', 2)
+ .arg(holdings_value, 0, 'f', 2)
+ .arg(mis_unrealized, 0, 'f', 2)
+ .arg(fv.total_equity, 0, 'f', 2)
+ .arg(intraday.size())
+ .arg(holdings.size())
+ .arg(sv.realized_pnl, 0, 'f', 2)
+ .arg(unrealized, 0, 'f', 2));
+
// Held symbols get live WebSocket prices even if not in the active list.
update_position_symbols(pos_syms);
update_chart_position(); // refresh the on-chart position card
@@ -908,6 +952,97 @@ void EquityTradingScreen::open_order_ticket_for(const QString& symbol, const QSt
on_order_submitted(order);
}
+QString EquityTradingScreen::pick_account_for_exchanges(const QStringList& match) const {
+ if (match.isEmpty())
+ return {};
+ QString connected, paper;
+ for (const auto& a : AccountManager::instance().list_accounts()) {
+ if (!a.is_active)
+ continue;
+ const bool live_ok = a.state == ConnectionState::Connected;
+ if (!(a.trading_mode == "paper" || live_ok))
+ continue;
+ auto* b = BrokerRegistry::instance().get(a.broker_id);
+ if (!b)
+ continue;
+ const QStringList exchanges = b->profile().exchanges;
+ bool hit = false;
+ for (const auto& me : match) {
+ if (exchanges.contains(me, Qt::CaseInsensitive)) {
+ hit = true;
+ break;
+ }
+ }
+ if (!hit)
+ continue;
+ if (a.account_id == focused_account_id_)
+ return a.account_id; // already focused & matches — least disruptive
+ if (live_ok && connected.isEmpty())
+ connected = a.account_id;
+ if (paper.isEmpty())
+ paper = a.account_id;
+ }
+ return !connected.isEmpty() ? connected : paper;
+}
+
+void EquityTradingScreen::open_external_order_ticket(const QString& symbol, const QString& exchange,
+ const QStringList& match_exchanges, bool is_buy,
+ double ref_price) {
+ if (symbol.isEmpty())
+ return;
+
+ // Route to a usable account whose broker can actually trade this symbol's market
+ // (broker.exchanges ∩ match_exchanges) — so a US ticker goes to Alpaca/IBKR/Saxo
+ // and an NSE ticker to the Indian broker, even with several brokers connected.
+ // When the caller didn't constrain the market, fall back to the credential-aware
+ // focused pick (also covers a never-shown screen with no focus yet).
+ QString target = pick_account_for_exchanges(match_exchanges);
+ if (target.isEmpty() && match_exchanges.isEmpty()) {
+ ensure_account_loaded();
+ target = focused_account_id_;
+ }
+ if (target.isEmpty()) {
+ QMessageBox::information(
+ this, tr("Trade %1").arg(symbol),
+ tr("No connected broker can trade %1. Add or connect a broker for this market in the ACCOUNTS panel.")
+ .arg(symbol));
+ return;
+ }
+
+ // Switch to the matching account through the normal path (which clears and
+ // refetches the shared blotter correctly) so the order — and the trading tab,
+ // next time it's opened — reflect the broker we're trading with.
+ if (target != focused_account_id_)
+ on_account_changed(target);
+ if (focused_account_id_.isEmpty())
+ return;
+
+ // open_order_ticket_for() / on_order_submitted() read the ref + paper-fill price
+ // from selected_symbol_ / current_price_. Adopt the caller's symbol/price (and
+ // the resolved exchange) for THIS order, then restore — the per-order overrides
+ // must not outlive the modal. exec() is synchronous, so placement completes
+ // before we restore. An empty exchange keeps the broker's default (set by
+ // on_account_changed) — correct for US brokers that route by symbol. ref_price<=0
+ // leaves price at 0 so a paper MARKET order is guarded ("price not available")
+ // rather than filling at a stale price.
+ const QString prev_symbol = selected_symbol_;
+ const QString prev_exchange = selected_exchange_;
+ const double prev_price = current_price_;
+
+ selected_symbol_ = symbol;
+ if (!exchange.isEmpty())
+ selected_exchange_ = exchange;
+ current_price_ = ref_price > 0.0 ? ref_price : 0.0;
+
+ // Delivery (CNC) default for a research-driven order; the quick ticket doesn't
+ // expose product choice (the full trading tab does).
+ open_order_ticket_for(symbol, selected_exchange_, QStringLiteral("CNC"), is_buy, 0.0);
+
+ selected_symbol_ = prev_symbol;
+ selected_exchange_ = prev_exchange;
+ current_price_ = prev_price;
+}
+
void EquityTradingScreen::on_chart_exit_position(const QString& symbol, const QString& exchange,
const QString& product_type, const QString& side,
double qty) {
@@ -1037,6 +1172,95 @@ void EquityTradingScreen::on_close_all_positions() {
});
}
+void EquityTradingScreen::on_square_off_all_holdings(const QVector<trading::BrokerHolding>& holdings) {
+ LOG_INFO("sqoff", QString("[screen] on_square_off_all_holdings: focused_account='%1' holdings=%2")
+ .arg(focused_account_id_)
+ .arg(holdings.size()));
+ if (focused_account_id_.isEmpty()) {
+ order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
+ return;
+ }
+ // The Holdings tab already confirmed via dialog. Square off each holding the
+ // SAME way the Positions tab does — via close_position, which finds the
+ // existing position by symbol and closes it with the correct opposite side.
+ // A raw SELL can open a short in paper (or fail to net) instead of reducing
+ // the holding. Holdings are delivery, so product = CNC. Touches ONLY holdings.
+ struct Target {
+ QString symbol;
+ QString exchange;
+ };
+ QVector<Target> targets;
+ for (const auto& h : holdings)
+ if (h.quantity > 0)
+ targets.push_back({h.symbol, h.exchange});
+ if (targets.isEmpty()) {
+ order_entry_->show_order_status(tr("No holdings to square off"), false);
+ return;
+ }
+
+ const QString acct_id = focused_account_id_;
+ QPointer<EquityTradingScreen> self = this;
+ (void)QtConcurrent::run([self, acct_id, targets]() {
+ if (!self)
+ return;
+ int ok = 0, fail = 0;
+ for (const auto& t : targets) {
+ auto r = UnifiedTrading::instance().close_position(acct_id, t.symbol, t.exchange,
+ QStringLiteral("CNC"));
+ LOG_INFO("sqoff", QString("[screen] close_position sym='%1' exch='%2' -> success=%3 err='%4'")
+ .arg(t.symbol, t.exchange,
+ r.success ? QStringLiteral("true") : QStringLiteral("false"), r.error));
+ r.success ? ++ok : ++fail;
+ }
+ QMetaObject::invokeMethod(
+ self,
+ [self, ok, fail]() {
+ if (!self)
+ return;
+ self->order_entry_->show_order_status(
+ self->tr("Squared off %1 holding(s)%2")
+ .arg(ok)
+ .arg(fail > 0 ? self->tr(", %1 failed").arg(fail) : QString()),
+ fail == 0);
+ self->refresh_paper_panels(); // paper refreshes here; live flows via the hub
+ },
+ Qt::QueuedConnection);
+ });
+}
+
+void EquityTradingScreen::on_square_off_holding(const QString& symbol, const QString& exchange) {
+ if (focused_account_id_.isEmpty()) {
+ order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
+ return;
+ }
+ const auto reply =
+ QMessageBox::question(this, tr("Square Off Holding"), tr("Square off %1 at market?").arg(symbol),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (reply != QMessageBox::Yes)
+ return;
+
+ const QString acct_id = focused_account_id_;
+ QPointer<EquityTradingScreen> self = this;
+ (void)QtConcurrent::run([self, acct_id, symbol, exchange]() {
+ if (!self)
+ return;
+ auto r = UnifiedTrading::instance().close_position(acct_id, symbol, exchange, QStringLiteral("CNC"));
+ LOG_INFO("sqoff", QString("[screen] per-row close_position sym='%1' exch='%2' -> success=%3 err='%4'")
+ .arg(symbol, exchange, r.success ? QStringLiteral("true") : QStringLiteral("false"),
+ r.error));
+ QMetaObject::invokeMethod(
+ self,
+ [self, r, symbol]() {
+ if (!self)
+ return;
+ self->order_entry_->show_order_status(
+ r.success ? self->tr("Squared off %1").arg(symbol) : r.error, r.success);
+ self->refresh_paper_panels();
+ },
+ Qt::QueuedConnection);
+ });
+}
+
void EquityTradingScreen::on_strategy_submitted(const trading::BasketOrderRequest& basket) {
if (focused_account_id_.isEmpty()) {
order_entry_->show_order_status(tr("No account selected — add one via ACCOUNTS"), false);
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
index 44b82245d..6057b223a 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
@@ -2,6 +2,8 @@
#include "screens/equity_trading/EquityWatchlist.h"
#include "screens/equity_trading/EquityTypes.h"
+#include "core/symbol/SymbolDragSource.h"
+#include "core/symbol/SymbolRef.h"
#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
#include "trading/instruments/InstrumentNormalize.h"
@@ -236,6 +238,26 @@ EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
connect(table_, &QTableWidget::customContextMenuRequested, this,
&EquityWatchlist::on_table_context_menu);
layout->addWidget(table_, 1);
+
+ // Drag-out: hold-and-drag a symbol row to ship the ticker to any drop
+ // target — drop it on the pushpin bar at the top to pin + broadcast it,
+ // matching the standalone Watchlist tab (WatchlistScreen). The provider
+ // reads the row under the cursor at drag-start (the mouse press selects it
+ // first), so it always ships the row actually grabbed. Group is None: the
+ // pushpin chip owns the broadcast group, so the source group is irrelevant
+ // for the drag-to-pin flow.
+ symbol_dnd::installDragSource(table_->viewport(), [this]() -> SymbolRef {
+ if (!table_)
+ return {};
+ const int r = table_->currentRow();
+ if (r < 0)
+ return {};
+ auto* item = table_->item(r, 0);
+ if (!item)
+ return {};
+ const QString sym = item->data(Qt::UserRole).toString();
+ return sym.isEmpty() ? SymbolRef{} : SymbolRef::equity(sym);
+ });
}
void EquityWatchlist::set_watchlists(const QVector<QPair<QString, QString>>& lists,
diff --git a/fincept-qt/src/services/equity/EquityResearchModels.h b/fincept-qt/src/services/equity/EquityResearchModels.h
index ff62d6fd8..bb9013498 100644
--- a/fincept-qt/src/services/equity/EquityResearchModels.h
+++ b/fincept-qt/src/services/equity/EquityResearchModels.h
@@ -207,4 +207,47 @@ struct MarketSentimentSnapshot {
QString fetched_at;
};
+// ── Self-computed (keyless) sentiment ───────────────────────────────────────
+// Produced by EquitySentimentService by blending free signals (news headline
+// NLP + price/technical momentum, plus optional Adanos when keyed). Replaces
+// the Adanos-only view as the default Sentiment tab content.
+
+// One scored headline, for the per-article list.
+struct ArticleSentiment {
+ QString title;
+ QString publisher;
+ QString published_date;
+ QString url;
+ QString label; // "BULLISH" | "BEARISH" | "NEUTRAL"
+ double score = 0.0; // -1..1
+};
+
+// One contributing signal in the blend (news / price / adanos).
+struct SentimentSource {
+ QString id; // "news" | "price" | "adanos"
+ QString label; // human-readable
+ double score = 0.0; // -1..1
+ double weight = 0.0; // normalized blend weight actually applied (0..1)
+ double confidence = 0.0; // 0..1
+ bool available = false;
+};
+
+struct EquitySentimentSnapshot {
+ QString symbol;
+ bool available = false;
+ QString status; // "ok" | "loading" | "unavailable"
+ QString message;
+ QString engine; // "vader" | "lexicon"
+ double overall_score = 0.0; // -1..1 blended
+ QString label; // "BULLISH" | "BEARISH" | "NEUTRAL"
+ double confidence = 0.0; // 0..1
+ int bullish = 0;
+ int bearish = 0;
+ int neutral = 0;
+ int article_count = 0;
+ QVector<SentimentSource> sources;
+ QVector<ArticleSentiment> articles;
+ QString fetched_at;
+};
+
} // namespace fincept::services::equity
diff --git a/fincept-qt/src/services/equity/EquityResearchService.cpp b/fincept-qt/src/services/equity/EquityResearchService.cpp
index 1559c1c84..e6d79b210 100644
--- a/fincept-qt/src/services/equity/EquityResearchService.cpp
+++ b/fincept-qt/src/services/equity/EquityResearchService.cpp
@@ -4,16 +4,139 @@
#include "core/logging/Logger.h"
#include "python/PythonRunner.h"
#include "storage/cache/CacheManager.h"
+#include "storage/repositories/DataSourceRepository.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerInterface.h"
+#include "trading/BrokerRegistry.h"
+#include "trading/HistoricalDataService.h"
+#include <QDate>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
#include <QPointer>
+#include <QUrl>
+#include <QUrlQuery>
+#include <algorithm>
#include <cmath>
+#include <vector>
namespace fincept::services::equity {
+namespace {
+
+// yfinance symbol → broker region. ".NS"/".BO" are Indian (NSE/BSE); a bare
+// ticker with no exchange suffix is a US listing (yfinance convention, e.g.
+// AAPL/SPGI). Other suffixes (.L, .TO, .HK …) aren't routable via the wired
+// brokers → empty region. Mirrors research_symbol_region() in the screen.
+QString candle_symbol_region(const QString& sym) {
+ if (sym.endsWith(QStringLiteral(".NS"), Qt::CaseInsensitive) ||
+ sym.endsWith(QStringLiteral(".BO"), Qt::CaseInsensitive))
+ return QStringLiteral("IN");
+ if (!sym.contains(QLatin1Char('.')))
+ return QStringLiteral("US");
+ return {};
+}
+
+// yfinance form (RELIANCE.NS / TCS.BO) → bare broker symbol. US tickers are
+// already bare.
+QString candle_bare_symbol(const QString& sym) {
+ if (sym.endsWith(QStringLiteral(".NS"), Qt::CaseInsensitive) ||
+ sym.endsWith(QStringLiteral(".BO"), Qt::CaseInsensitive))
+ return sym.left(sym.length() - 3);
+ return sym;
+}
+
+// Pick the first *Connected* active account whose broker region matches the
+// symbol's market, so RELIANCE.NS routes through a live Indian broker and a US
+// ticker through a live US broker — never cross-region. Returns false when no
+// usable broker exists (caller then uses yfinance).
+bool resolve_connected_data_broker(const QString& symbol, QString& broker_id, QString& account_id) {
+ const QString region = candle_symbol_region(symbol);
+ if (region.isEmpty())
+ return false;
+ const auto accounts = fincept::trading::AccountManager::instance().active_accounts();
+ for (const auto& a : accounts) {
+ if (a.state != fincept::trading::ConnectionState::Connected)
+ continue;
+ auto* b = fincept::trading::BrokerRegistry::instance().get(a.broker_id);
+ if (b && b->profile().region == region) {
+ broker_id = a.broker_id;
+ account_id = a.account_id;
+ return true;
+ }
+ }
+ return false;
+}
+
+// yfinance period string ("2y"/"1y"/"6mo"/"3mo"/"1mo"/"5d"/"max") → lookback
+// days for the broker history request. Defaults to ~2y (good indicator warm-up).
+int candle_lookback_days(const QString& period) {
+ const QString p = period.trimmed().toLower();
+ if (p == QLatin1String("max"))
+ return 3650;
+ auto num = [&](int trim) { return p.left(p.size() - trim).toInt(); };
+ if (p.endsWith(QLatin1String("mo"))) {
+ int n = num(2);
+ if (n > 0)
+ return n * 31;
+ } else if (p.endsWith(QLatin1Char('y'))) {
+ int n = num(1);
+ if (n > 0)
+ return n * 365;
+ } else if (p.endsWith(QLatin1String("wk"))) {
+ int n = num(2);
+ if (n > 0)
+ return n * 7;
+ } else if (p.endsWith(QLatin1Char('d'))) {
+ int n = num(1);
+ if (n > 0)
+ return n;
+ }
+ return 730;
+}
+
+// trading-layer BrokerCandle[] → the yfinance-shaped JSON array the indicator
+// scripts consume: [{timestamp(sec), open, high, low, close, volume}, …], ascending.
+// Timestamps are normalised to epoch SECONDS (some brokers, e.g. Fyers, return
+// milliseconds — the chart and the indicator engine assume seconds).
+QString broker_candles_to_json(const QVector<fincept::trading::BrokerCandle>& candles) {
+ struct Row {
+ qint64 ts;
+ const fincept::trading::BrokerCandle* c;
+ };
+ std::vector<Row> rows;
+ rows.reserve(static_cast<size_t>(candles.size()));
+ for (const auto& c : candles) {
+ qint64 ts = c.timestamp;
+ if (ts > 1000000000000LL) // > ~Sep 2001 in ms → milliseconds, convert to seconds
+ ts /= 1000;
+ if (ts <= 0)
+ continue;
+ rows.push_back({ts, &c});
+ }
+ std::sort(rows.begin(), rows.end(), [](const Row& a, const Row& b) { return a.ts < b.ts; });
+
+ QJsonArray arr;
+ for (const auto& r : rows) {
+ QJsonObject o;
+ o["timestamp"] = static_cast<double>(r.ts);
+ o["open"] = r.c->open;
+ o["high"] = r.c->high;
+ o["low"] = r.c->low;
+ o["close"] = r.c->close;
+ o["volume"] = r.c->volume;
+ arr.append(o);
+ }
+ return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));
+}
+
+} // namespace
+
// ── Singleton ─────────────────────────────────────────────────────────────────
EquityResearchService& EquityResearchService::instance() {
static EquityResearchService inst;
@@ -180,14 +303,8 @@ void EquityResearchService::fetch_financials(const QString& symbol) {
// ── Technicals ────────────────────────────────────────────────────────────────
void EquityResearchService::fetch_technicals(const QString& symbol, const QString& period) {
- // Step 1: fetch historical (from CacheManager), then step 2: compute technicals
- QString cached_json;
- {
- const QVariant hcv = fincept::CacheManager::instance().get("equity:candles:" + symbol);
- if (!hcv.isNull())
- cached_json = hcv.toString();
- }
-
+ // Candles come from ensure_candles (cache → region-matched connected broker →
+ // yfinance fallback); compute_technicals.py then derives the rating + indicators.
auto run_compute = [this, symbol](const QString& hist_json) {
run_python("compute_technicals.py", {hist_json}, [this, symbol](bool ok2, const QString& out2) {
if (!ok2) {
@@ -203,21 +320,16 @@ void EquityResearchService::fetch_technicals(const QString& symbol, const QStrin
});
};
- if (!cached_json.isEmpty()) {
- run_compute(cached_json);
- } else {
- run_python("yfinance_data.py", {"historical_period", symbol, period, "1d"},
- [this, symbol, run_compute](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("Technicals", "Failed historical fetch");
- return;
- }
- auto raw = python::extract_json(out);
- fincept::CacheManager::instance().put("equity:candles:" + symbol, QVariant(raw),
- kHistoricalTtlSec, "equity");
- run_compute(raw);
- });
- }
+ QPointer<EquityResearchService> self = this;
+ ensure_candles(symbol, period, [self, run_compute](bool ok, const QString& hist_json) {
+ if (!self)
+ return;
+ if (!ok || hist_json.trimmed().isEmpty()) {
+ emit self->error_occurred("Technicals", "Failed historical fetch");
+ return;
+ }
+ run_compute(hist_json);
+ });
}
// ── Peers ─────────────────────────────────────────────────────────────────────
@@ -238,7 +350,89 @@ void EquityResearchService::fetch_peers(const QString& symbol, const QStringList
}
// ── News ──────────────────────────────────────────────────────────────────────
-void EquityResearchService::fetch_news(const QString& symbol, int count) {
+// Turn a yfinance company_name into a Google-News-friendly query by dropping the
+// trailing corporate suffix(es) and punctuation — "Reliance Industries Limited" →
+// "Reliance Industries", "Tesla, Inc." → "Tesla". Materially improves GNews recall.
+static QString gnews_query_from_company_name(const QString& company_name) {
+ static const QStringList kSuffixes = {"Limited", "Ltd", "Incorporated", "Inc", "Corporation", "Corp",
+ "Company", "Co", "PLC", "Holdings", "Holding", "Group",
+ "SA", "NV", "AG", "SE", "SpA", "AB"};
+ QString q = company_name.trimmed();
+ bool changed = true;
+ while (changed) {
+ changed = false;
+ q = q.trimmed();
+ while (q.endsWith(QLatin1Char(',')) || q.endsWith(QLatin1Char('.')))
+ q.chop(1);
+ for (const auto& suf : kSuffixes) {
+ if (q.endsWith(QLatin1Char(' ') + suf, Qt::CaseInsensitive)) {
+ q.chop(suf.size() + 1);
+ changed = true;
+ break;
+ }
+ }
+ }
+ return q.trimmed();
+}
+
+// Build the news search query for a symbol: the cleaned company name from cached
+// info when available, else the bare ticker (.NS/.BO suffix stripped).
+static QString news_query_for_symbol(const QString& symbol) {
+ const bool indian = symbol.endsWith(QStringLiteral(".NS"), Qt::CaseInsensitive) ||
+ symbol.endsWith(QStringLiteral(".BO"), Qt::CaseInsensitive);
+ QString query = indian ? symbol.left(symbol.length() - 3) : symbol;
+ const QVariant icv = fincept::CacheManager::instance().get("equity:info:" + symbol);
+ if (!icv.isNull()) {
+ const auto info = QJsonDocument::fromJson(icv.toString().toUtf8()).object();
+ const QString cleaned = gnews_query_from_company_name(info.value("company_name").toString());
+ if (!cleaned.isEmpty())
+ query = cleaned;
+ }
+ return query;
+}
+
+// NewsAPI /v2/everything query for a symbol. Builds an EXACT-PHRASE (quoted) match
+// on the company name (ticker as fallback) so results are about THIS company.
+// Paired with searchIn=title,description at the call site, this keeps the feed
+// stock-specific — the default everything search also scans the full article body,
+// so a bare word like "Apple"/"Reliance" otherwise pulled in unrelated general news.
+static QString newsapi_query_for_symbol(const QString& symbol) {
+ const bool indian = symbol.endsWith(QStringLiteral(".NS"), Qt::CaseInsensitive) ||
+ symbol.endsWith(QStringLiteral(".BO"), Qt::CaseInsensitive);
+ const QString ticker = indian ? symbol.left(symbol.length() - 3) : symbol;
+ QString company;
+ const QVariant icv = fincept::CacheManager::instance().get("equity:info:" + symbol);
+ if (!icv.isNull()) {
+ const auto info = QJsonDocument::fromJson(icv.toString().toUtf8()).object();
+ company = gnews_query_from_company_name(info.value("company_name").toString());
+ }
+ QString phrase = company;
+ if (phrase.isEmpty())
+ phrase = ticker;
+ if (phrase.isEmpty())
+ phrase = symbol;
+ return QStringLiteral("\"%1\"").arg(phrase); // quotes → NewsAPI exact-phrase match
+}
+
+void EquityResearchService::fetch_news(const QString& symbol, int count, NewsProvider provider) {
+ // NewsAPI.org provider (opt-in): use it only when a key is configured, and
+ // cache it under a separate key so switching providers doesn't surface the
+ // other provider's cached result.
+ if (provider == NewsProvider::NewsApi) {
+ const QString key = configured_newsapi_key();
+ if (!key.isEmpty()) {
+ const QVariant ncv = fincept::CacheManager::instance().get("equity:news:newsapi:" + symbol);
+ if (!ncv.isNull()) {
+ const QJsonArray arr = QJsonDocument::fromJson(ncv.toString().toUtf8()).array();
+ emit news_loaded(symbol, parse_news(arr));
+ return;
+ }
+ fetch_news_newsapi(symbol, count, key);
+ return;
+ }
+ // No key configured → fall through to the default Auto chain below.
+ }
+
{
const QVariant ncv = fincept::CacheManager::instance().get("equity:news:" + symbol);
if (!ncv.isNull()) {
@@ -247,6 +441,45 @@ void EquityResearchService::fetch_news(const QString& symbol, int count) {
return;
}
}
+
+ // Primary source: Google News (fetch_company_news.py) — broader, more current
+ // company coverage than yfinance's Yahoo feed. Google News recall is far better
+ // for a clean company NAME than a bare ticker or the full legal name (e.g.
+ // "Reliance Industries" returns articles where "RELIANCE" and "Reliance
+ // Industries Limited" both return none), so query by the cleaned company_name
+ // from the cached info when available, falling back to the bare ticker.
+ const bool indian = symbol.endsWith(QStringLiteral(".NS"), Qt::CaseInsensitive) ||
+ symbol.endsWith(QStringLiteral(".BO"), Qt::CaseInsensitive);
+ const QString country = indian ? QStringLiteral("IN") : QStringLiteral("US");
+ const QString query = news_query_for_symbol(symbol);
+
+ run_python(
+ "fetch_company_news.py",
+ {"search", query, QString::number(count), QStringLiteral("1M"), QStringLiteral("en"), country},
+ [this, symbol, count](bool ok, const QString& out) {
+ if (ok) {
+ const auto obj = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).object();
+ // GNews returns {"success":true,"data":[...]}. Only accept a
+ // non-empty result; anything else falls through to yfinance.
+ if (obj.value("success").toBool()) {
+ const auto arr = obj.value("data").toArray();
+ if (!arr.isEmpty()) {
+ fincept::CacheManager::instance().put(
+ "equity:news:" + symbol,
+ QVariant(QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact))), kNewsTtlSec,
+ "equity");
+ emit news_loaded(symbol, parse_news(arr));
+ return;
+ }
+ }
+ }
+ // Google News unavailable (e.g. gnews missing / network) or empty →
+ // fall back to the Yahoo/yfinance feed.
+ fetch_news_yfinance(symbol, count);
+ });
+}
+
+void EquityResearchService::fetch_news_yfinance(const QString& symbol, int count) {
run_python(
"yfinance_data.py", {"news", symbol, QString::number(count)}, [this, symbol](bool ok, const QString& out) {
if (!ok) {
@@ -262,49 +495,163 @@ void EquityResearchService::fetch_news(const QString& symbol, int count) {
});
}
-// ── TALIpp ────────────────────────────────────────────────────────────────────
-void EquityResearchService::compute_talipp(const QString& symbol, const QString& indicator, const QVariantMap& params,
- const QString& period) {
- auto run_talipp = [this, indicator, params](const QString& hist_json) {
- QJsonObject p_obj;
- for (auto it = params.constBegin(); it != params.constEnd(); ++it)
- p_obj[it.key()] = QJsonValue::fromVariant(it.value());
- QString params_json = QJsonDocument(p_obj).toJson(QJsonDocument::Compact);
-
- run_python("equity_talipp.py", {indicator, hist_json, params_json},
- [this, indicator](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("TALIpp", out);
- return;
- }
- auto doc = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).object();
- QVector<double> values;
- QVector<qint64> timestamps;
- for (const auto& v : doc["values"].toArray())
- values.append(v.toDouble());
- for (const auto& t : doc["timestamps"].toArray())
- timestamps.append(static_cast<qint64>(t.toDouble()));
- emit talipp_result(indicator, values, timestamps);
- });
+// ── NewsAPI.org ─────────────────────────────────────────────────────────────
+// The configured & enabled NewsAPI key from the Data Sources tab (provider id
+// "newsapi", set by ConnectionConfigDialog as ds.provider = connector id). Empty
+// when no enabled NewsAPI connection has a non-empty apiKey.
+QString EquityResearchService::configured_newsapi_key() const {
+ const auto res = fincept::DataSourceRepository::instance().list_all();
+ if (res.is_err())
+ return {};
+ for (const auto& ds : res.value()) {
+ if (!ds.enabled || ds.provider != QLatin1String("newsapi"))
+ continue;
+ const auto cfg = QJsonDocument::fromJson(ds.config.toUtf8()).object();
+ const QString key = cfg.value("apiKey").toString().trimmed();
+ if (!key.isEmpty())
+ return key;
+ }
+ return {};
+}
+
+// Fetch stock-specific news from newsapi.org/v2/everything. On any failure
+// (network error, non-"ok" status such as 401/quota, or no usable articles) it
+// falls back to the default Auto chain so the tab always shows news.
+void EquityResearchService::fetch_news_newsapi(const QString& symbol, int count, const QString& api_key) {
+ if (!news_nam_)
+ news_nam_ = new QNetworkAccessManager(this);
+
+ QUrl url(QStringLiteral("https://newsapi.org/v2/everything"));
+ QUrlQuery params;
+ // Exact-phrase company query restricted to title+description (NOT the full
+ // article body) so results are about THIS company, not any article that
+ // merely mentions the word. This is what makes the feed stock-specific.
+ params.addQueryItem(QStringLiteral("q"), newsapi_query_for_symbol(symbol));
+ params.addQueryItem(QStringLiteral("searchIn"), QStringLiteral("title,description"));
+ params.addQueryItem(QStringLiteral("language"), QStringLiteral("en"));
+ params.addQueryItem(QStringLiteral("sortBy"), QStringLiteral("publishedAt"));
+ params.addQueryItem(QStringLiteral("pageSize"), QString::number(std::clamp(count, 1, 100)));
+ params.addQueryItem(QStringLiteral("from"), QDate::currentDate().addDays(-30).toString(Qt::ISODate));
+ url.setQuery(params);
+
+ QNetworkRequest req(url);
+ req.setRawHeader("X-Api-Key", api_key.toUtf8()); // key in header, not the URL
+ req.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("FinceptTerminal"));
+
+ QNetworkReply* reply = news_nam_->get(req);
+ connect(reply, &QNetworkReply::finished, this, [this, reply, symbol, count]() {
+ reply->deleteLater();
+ const auto fall_back = [this, symbol, count]() { fetch_news(symbol, count, NewsProvider::Auto); };
+
+ if (reply->error() != QNetworkReply::NoError) {
+ LOG_WARN("EquityResearch",
+ QString("NewsAPI request failed (%1) — falling back").arg(reply->errorString()));
+ fall_back();
+ return;
+ }
+ const auto obj = QJsonDocument::fromJson(reply->readAll()).object();
+ if (obj.value("status").toString() != QLatin1String("ok")) {
+ LOG_WARN("EquityResearch",
+ QString("NewsAPI error: %1 — falling back").arg(obj.value("message").toString("unknown")));
+ fall_back();
+ return;
+ }
+
+ // Reshape NewsAPI articles into the {title, description, url, publisher,
+ // published_date} shape parse_news() consumes.
+ QJsonArray reshaped;
+ for (const auto& v : obj.value("articles").toArray()) {
+ const auto a = v.toObject();
+ const QString title = a.value("title").toString();
+ if (title.isEmpty() || title == QLatin1String("[Removed]"))
+ continue;
+ reshaped.append(QJsonObject{
+ {"title", title},
+ {"description", a.value("description").toString()},
+ {"url", a.value("url").toString()},
+ {"publisher", a.value("source").toObject().value("name").toString()},
+ {"published_date", a.value("publishedAt").toString()},
+ });
+ }
+ if (reshaped.isEmpty()) {
+ fall_back(); // nothing usable from NewsAPI → Auto chain
+ return;
+ }
+ fincept::CacheManager::instance().put(
+ "equity:news:newsapi:" + symbol,
+ QVariant(QString::fromUtf8(QJsonDocument(reshaped).toJson(QJsonDocument::Compact))), kNewsTtlSec, "equity");
+ emit news_loaded(symbol, parse_news(reshaped));
+ });
+}
+
+// ── Candle source: connected broker first, yfinance fallback ─────────────────
+// Shared by fetch_technicals (and any future indicator path). Order:
+// 1. cache hit → return immediately
+// 2. region-matched *connected* broker → broker get_history (live, reliable)
+// 3. yfinance → fallback (no broker, or broker empty/failed)
+// The result is cached under "equity:candles:<symbol>". done(ok, hist_json) is
+// always invoked on the main thread.
+void EquityResearchService::ensure_candles(const QString& symbol, const QString& period,
+ std::function<void(bool, const QString&)> done) {
+ const QString cache_key = "equity:candles:" + symbol;
+ const QVariant cached = fincept::CacheManager::instance().get(cache_key);
+ if (!cached.isNull()) {
+ // Reject a cached empty payload ("" or "[]") — a stale rate-limited
+ // result would otherwise wedge the tab on "No data returned".
+ const QString c = cached.toString().trimmed();
+ if (!c.isEmpty() && c != QLatin1String("[]")) {
+ done(true, cached.toString());
+ return;
+ }
+ }
+
+ QPointer<EquityResearchService> self = this;
+ auto run_yfinance = [self, symbol, period, cache_key, done]() {
+ if (!self) {
+ done(false, {});
+ return;
+ }
+ self->run_python("yfinance_data.py", {"historical_period", symbol, period, "1d"},
+ [cache_key, done](bool ok, const QString& out) {
+ if (!ok) {
+ done(false, {});
+ return;
+ }
+ const QString raw = python::extract_json(out);
+ const QString trimmed = raw.trimmed();
+ if (trimmed.isEmpty() || trimmed == QLatin1String("[]")) {
+ done(false, {}); // yfinance rate-limited / unknown symbol
+ return;
+ }
+ fincept::CacheManager::instance().put(cache_key, QVariant(raw), kHistoricalTtlSec, "equity");
+ done(true, raw);
+ });
};
- // Use cached historical if available, else fetch
- const QVariant cached_candles = fincept::CacheManager::instance().get("equity:candles:" + symbol);
- if (!cached_candles.isNull()) {
- run_talipp(cached_candles.toString());
- } else {
- run_python("yfinance_data.py", {"historical_period", symbol, period, "1d"},
- [this, symbol, run_talipp](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("TALIpp", "Historical fetch failed");
- return;
- }
- auto raw = python::extract_json(out);
- fincept::CacheManager::instance().put("equity:candles:" + symbol, QVariant(raw),
- kHistoricalTtlSec, "equity");
- run_talipp(raw);
- });
+ QString broker_id, account_id;
+ if (resolve_connected_data_broker(symbol, broker_id, account_id)) {
+ const QString bare = candle_bare_symbol(symbol);
+ const int lookback = candle_lookback_days(period);
+ LOG_INFO("EquityResearch",
+ QString("Candles for %1 via broker %2").arg(symbol, broker_id));
+ fincept::trading::HistoricalDataService::instance().fetch(
+ bare, QStringLiteral("1d"), lookback, broker_id, account_id,
+ [cache_key, done, run_yfinance](bool ok, const QVector<fincept::trading::BrokerCandle>& candles,
+ const QString& /*err*/) {
+ if (ok && !candles.isEmpty()) {
+ const QString json = broker_candles_to_json(candles);
+ if (!json.isEmpty() && json != QLatin1String("[]")) {
+ fincept::CacheManager::instance().put(cache_key, QVariant(json), kHistoricalTtlSec, "equity");
+ done(true, json);
+ return;
+ }
+ }
+ run_yfinance(); // broker had no data — fall back
+ });
+ return;
}
+
+ run_yfinance(); // no connected region-matched broker
}
// ── Parsers ───────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/services/equity/EquityResearchService.h b/fincept-qt/src/services/equity/EquityResearchService.h
index 95a2b8144..7b605cd4f 100644
--- a/fincept-qt/src/services/equity/EquityResearchService.h
+++ b/fincept-qt/src/services/equity/EquityResearchService.h
@@ -7,8 +7,14 @@
#include <functional>
+class QNetworkAccessManager;
+
namespace fincept::services::equity {
+/// News source for fetch_news(). Auto = the default GNews → Yahoo chain;
+/// NewsApi = newsapi.org (only when a key is configured in Data Sources).
+enum class NewsProvider { Auto, NewsApi };
+
class EquityResearchService : public QObject {
Q_OBJECT
public:
@@ -33,11 +39,12 @@ class EquityResearchService : public QObject {
void fetch_financials(const QString& symbol);
void fetch_technicals(const QString& symbol, const QString& period = "1y");
void fetch_peers(const QString& symbol, const QStringList& peer_symbols);
- void fetch_news(const QString& symbol, int count = 20);
+ void fetch_news(const QString& symbol, int count = 20, NewsProvider provider = NewsProvider::Auto);
- /// TALIpp tab: fetch historical then run equity_talipp.py
- void compute_talipp(const QString& symbol, const QString& indicator, const QVariantMap& params,
- const QString& period = "2y");
+ /// The configured & enabled NewsAPI.org key from the Data Sources tab, or an
+ /// empty string when none. Used to gate the News-tab provider switch and to
+ /// supply the key at fetch time.
+ QString configured_newsapi_key() const;
signals:
void search_results_loaded(QVector<fincept::services::equity::SearchResult> results);
@@ -48,7 +55,6 @@ class EquityResearchService : public QObject {
void technicals_loaded(fincept::services::equity::TechnicalsData data);
void peers_loaded(QVector<fincept::services::equity::PeerData> peers);
void news_loaded(QString symbol, QVector<fincept::services::equity::NewsArticle> articles);
- void talipp_result(QString indicator, QVector<double> values, QVector<qint64> timestamps);
void error_occurred(QString context, QString message);
private:
@@ -58,6 +64,21 @@ class EquityResearchService : public QObject {
// ── Python helpers ────────────────────────────────────────────────────────
void run_python(const QString& script, const QStringList& args, std::function<void(bool, const QString&)> cb);
+ // Candle source: cache → region-matched connected broker → yfinance
+ // fallback. done(ok, hist_json) is invoked on the main thread.
+ void ensure_candles(const QString& symbol, const QString& period,
+ std::function<void(bool, const QString&)> done);
+
+ // yfinance news path — the fallback fetch_news() uses when Google News
+ // (fetch_company_news.py) is unavailable or returns no articles.
+ void fetch_news_yfinance(const QString& symbol, int count);
+
+ // NewsAPI.org path (native HTTP via news_nam_). Used when the equity News tab
+ // selects the NewsApi provider and a key is configured. Caches under
+ // "equity:news:newsapi:<symbol>"; on any failure (401/quota/network/empty)
+ // it falls back to fetch_news(symbol, count, NewsProvider::Auto).
+ void fetch_news_newsapi(const QString& symbol, int count, const QString& api_key);
+
// ── Parsers ───────────────────────────────────────────────────────────────
QuoteData parse_quote(const QJsonObject& obj) const;
StockInfo parse_info(const QJsonObject& obj) const;
@@ -78,6 +99,10 @@ class EquityResearchService : public QObject {
static constexpr int kDebounceMs = 350;
QTimer* search_debounce_ = nullptr;
QString pending_query_;
+
+ // Dedicated NAM for third-party NewsAPI.org calls — kept separate from the
+ // Fincept-backend HttpClient singleton (which carries base-url/session token).
+ QNetworkAccessManager* news_nam_ = nullptr;
};
} // namespace fincept::services::equity
diff --git a/fincept-qt/src/services/equity/EquitySentimentService.cpp b/fincept-qt/src/services/equity/EquitySentimentService.cpp
new file mode 100644
index 000000000..4674ffb1c
--- /dev/null
+++ b/fincept-qt/src/services/equity/EquitySentimentService.cpp
@@ -0,0 +1,287 @@
+#include "services/equity/EquitySentimentService.h"
+
+#include "services/equity/EquityResearchService.h"
+#include "services/equity/MarketSentimentService.h"
+#include "services/news/NewsNlpService.h"
+
+#include <QDateTime>
+#include <QHash>
+#include <QTimer>
+
+#include <algorithm>
+
+namespace fincept::services::equity {
+
+namespace {
+
+// Blend weights (base, before confidence scaling) and label band. Tunable.
+constexpr double kBaseWeightNews = 0.5;
+constexpr double kBaseWeightPrice = 0.3;
+constexpr double kBaseWeightAdanos = 0.2;
+constexpr double kLabelThreshold = 0.15;
+
+// An available source always carries at least this much weight, so an all-NEUTRAL
+// reading still counts (→ NEUTRAL) instead of collapsing to "no signal".
+constexpr double kConfidenceFloor = 0.15;
+
+constexpr int kTimeoutMs = 15000;
+constexpr int kMaxArticles = 40;
+
+QString sentiment_label(double score) {
+ if (score >= kLabelThreshold)
+ return QStringLiteral("BULLISH");
+ if (score <= -kLabelThreshold)
+ return QStringLiteral("BEARISH");
+ return QStringLiteral("NEUTRAL");
+}
+
+} // namespace
+
+EquitySentimentService& EquitySentimentService::instance() {
+ static EquitySentimentService service;
+ return service;
+}
+
+EquitySentimentService::EquitySentimentService(QObject* parent) : QObject(parent) {
+ timeout_timer_ = new QTimer(this);
+ timeout_timer_->setSingleShot(true);
+ connect(timeout_timer_, &QTimer::timeout, this, [this]() {
+ if (finalized_)
+ return;
+ // Force completion with whatever legs resolved; unresolved sources stay
+ // unavailable and simply drop out of the blend.
+ news_.done = true;
+ price_.done = true;
+ adanos_.done = true;
+ finalize();
+ });
+
+ connect(&EquityResearchService::instance(), &EquityResearchService::news_loaded, this,
+ [this](const QString& symbol, const QVector<NewsArticle>& articles) { on_news_loaded(symbol, articles); });
+ connect(&EquityResearchService::instance(), &EquityResearchService::technicals_loaded, this,
+ [this](const TechnicalsData& data) { on_technicals_loaded(data); });
+ connect(&MarketSentimentService::instance(), &MarketSentimentService::snapshot_loaded, this,
+ [this](const QString& symbol, const MarketSentimentSnapshot& snap) { on_adanos_loaded(symbol, snap); });
+}
+
+void EquitySentimentService::fetch_sentiment(const QString& symbol) {
+ const QString sym = symbol.trimmed().toUpper();
+ if (sym.isEmpty())
+ return;
+
+ // New request: bump the id (drops stale callbacks) and reset all state
+ // BEFORE firing fetches — the underlying fetchers may emit synchronously on
+ // a cache hit, re-entering our slots within these calls.
+ ++active_request_id_;
+ active_symbol_ = sym;
+ finalized_ = false;
+ news_consumed_ = false;
+ tech_consumed_ = false;
+ adanos_consumed_ = false;
+ news_ = SourceState{};
+ price_ = SourceState{};
+ adanos_ = SourceState{};
+ bullish_ = 0;
+ bearish_ = 0;
+ neutral_ = 0;
+ engine_.clear();
+ articles_.clear();
+
+ need_adanos_ = MarketSentimentService::instance().is_configured();
+ adanos_.done = !need_adanos_; // not awaited when no key is configured
+
+ timeout_timer_->start(kTimeoutMs);
+
+ EquityResearchService::instance().fetch_news(sym);
+ EquityResearchService::instance().fetch_technicals(sym);
+ if (need_adanos_)
+ MarketSentimentService::instance().fetch_snapshot(sym);
+}
+
+void EquitySentimentService::on_news_loaded(const QString& symbol, const QVector<NewsArticle>& articles) {
+ if (symbol != active_symbol_ || news_consumed_)
+ return;
+ news_consumed_ = true;
+ const quint64 rid = active_request_id_;
+
+ if (articles.isEmpty()) {
+ news_.available = false;
+ news_.done = true;
+ try_finalize();
+ return;
+ }
+
+ // news_nlp.py reads headline/summary; equity articles use title/description.
+ // Map across, tagging a stable id so we can rejoin scores for display.
+ QVector<fincept::services::NewsArticle> mapped;
+ mapped.reserve(articles.size());
+ for (int i = 0; i < articles.size(); ++i) {
+ fincept::services::NewsArticle n;
+ n.id = QString::number(i);
+ n.headline = articles[i].title;
+ n.summary = articles[i].description;
+ mapped.append(n);
+ }
+ const QVector<NewsArticle> source_articles = articles;
+
+ NewsNlpService::instance().analyze_sentiment(
+ mapped, [this, rid, source_articles](bool ok, const NewsSentimentResult& result) {
+ if (rid != active_request_id_)
+ return; // superseded by a newer request
+ if (!ok) {
+ news_.available = false;
+ news_.done = true;
+ try_finalize();
+ return;
+ }
+
+ engine_ = result.engine;
+ bullish_ = result.bullish;
+ bearish_ = result.bearish;
+ neutral_ = result.neutral;
+
+ QHash<QString, ArticleSentimentResult> by_id;
+ by_id.reserve(result.per_article.size());
+ for (const auto& ar : result.per_article)
+ by_id.insert(ar.id, ar);
+
+ articles_.clear();
+ const int limit = std::min<int>(source_articles.size(), kMaxArticles);
+ for (int i = 0; i < limit; ++i) {
+ ArticleSentiment a;
+ a.title = source_articles[i].title;
+ a.publisher = source_articles[i].publisher;
+ a.published_date = source_articles[i].published_date;
+ a.url = source_articles[i].url;
+ const auto res = by_id.value(QString::number(i));
+ a.label = res.label.isEmpty() ? QStringLiteral("NEUTRAL") : res.label;
+ a.score = res.score;
+ articles_.append(a);
+ }
+
+ const int scored = result.bullish + result.bearish + result.neutral;
+ const int non_neutral = result.bullish + result.bearish;
+ news_.score = result.overall_score;
+ news_.confidence = scored > 0 ? static_cast<double>(non_neutral) / scored : 0.0;
+ news_.available = scored > 0;
+ news_.done = true;
+ try_finalize();
+ });
+}
+
+void EquitySentimentService::on_technicals_loaded(const TechnicalsData& data) {
+ if (data.symbol != active_symbol_ || tech_consumed_)
+ return;
+ tech_consumed_ = true;
+
+ const int total = data.strong_buy + data.buy + data.neutral + data.sell + data.strong_sell;
+ if (total > 0) {
+ const double raw =
+ (data.strong_buy + 0.5 * data.buy - 0.5 * data.sell - data.strong_sell) / static_cast<double>(total);
+ price_.score = std::clamp(raw, -1.0, 1.0);
+ const int non_neutral = data.strong_buy + data.buy + data.sell + data.strong_sell;
+ price_.confidence = static_cast<double>(non_neutral) / total;
+ price_.available = true;
+ }
+ price_.done = true;
+ try_finalize();
+}
+
+void EquitySentimentService::on_adanos_loaded(const QString& symbol, const MarketSentimentSnapshot& snapshot) {
+ if (!need_adanos_ || symbol != active_symbol_ || adanos_consumed_)
+ return;
+ adanos_consumed_ = true;
+
+ if (snapshot.configured && snapshot.available && snapshot.coverage > 0) {
+ adanos_.score = std::clamp((snapshot.average_bullish_pct - 50.0) / 50.0, -1.0, 1.0);
+ adanos_.confidence = 1.0;
+ adanos_.available = true;
+ }
+ adanos_.done = true;
+ try_finalize();
+}
+
+void EquitySentimentService::try_finalize() {
+ if (finalized_)
+ return;
+ if (!news_.done || !price_.done)
+ return;
+ if (need_adanos_ && !adanos_.done)
+ return;
+ finalize();
+}
+
+void EquitySentimentService::finalize() {
+ if (finalized_)
+ return;
+ finalized_ = true;
+ timeout_timer_->stop();
+
+ EquitySentimentSnapshot snap;
+ snap.symbol = active_symbol_;
+ snap.engine = engine_;
+ snap.bullish = bullish_;
+ snap.bearish = bearish_;
+ snap.neutral = neutral_;
+ snap.article_count = bullish_ + bearish_ + neutral_;
+ snap.articles = articles_;
+ snap.fetched_at = QDateTime::currentDateTimeUtc().toString(Qt::ISODate);
+
+ struct Contrib {
+ QString id;
+ QString label;
+ const SourceState* state;
+ double base;
+ bool include;
+ };
+ const Contrib contribs[] = {
+ {QStringLiteral("news"), QStringLiteral("News Sentiment"), &news_, kBaseWeightNews, true},
+ {QStringLiteral("price"), QStringLiteral("Price Momentum"), &price_, kBaseWeightPrice, true},
+ // Adanos row only shown/blended when a key is configured.
+ {QStringLiteral("adanos"), QStringLiteral("Adanos"), &adanos_, kBaseWeightAdanos, need_adanos_},
+ };
+
+ double weight_sum = 0.0;
+ for (const auto& c : contribs) {
+ if (c.include && c.state->available)
+ weight_sum += c.base * std::max(c.state->confidence, kConfidenceFloor);
+ }
+
+ double blended = 0.0;
+ double confidence_acc = 0.0;
+ for (const auto& c : contribs) {
+ if (!c.include)
+ continue;
+ SentimentSource src;
+ src.id = c.id;
+ src.label = c.label;
+ src.available = c.state->available;
+ src.score = c.state->score;
+ src.confidence = c.state->confidence;
+ if (c.state->available && weight_sum > 0.0) {
+ const double w = (c.base * std::max(c.state->confidence, kConfidenceFloor)) / weight_sum;
+ src.weight = w;
+ blended += w * c.state->score;
+ confidence_acc += w * c.state->confidence;
+ }
+ snap.sources.append(src);
+ }
+
+ if (weight_sum > 0.0) {
+ snap.available = true;
+ snap.status = QStringLiteral("ok");
+ snap.overall_score = std::clamp(blended, -1.0, 1.0);
+ snap.label = sentiment_label(snap.overall_score);
+ snap.confidence = std::clamp(confidence_acc, 0.0, 1.0);
+ } else {
+ snap.available = false;
+ snap.status = QStringLiteral("unavailable");
+ snap.label = QStringLiteral("NEUTRAL");
+ snap.message =
+ QStringLiteral("No sentiment signal yet — news and price momentum are unavailable for this symbol.");
+ }
+
+ emit sentiment_loaded(active_symbol_, snap);
+}
+
+} // namespace fincept::services::equity
diff --git a/fincept-qt/src/services/equity/EquitySentimentService.h b/fincept-qt/src/services/equity/EquitySentimentService.h
new file mode 100644
index 000000000..54e2bd352
--- /dev/null
+++ b/fincept-qt/src/services/equity/EquitySentimentService.h
@@ -0,0 +1,74 @@
+#pragma once
+
+#include "services/equity/EquityResearchModels.h"
+
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+class QTimer;
+
+namespace fincept::services::equity {
+
+// Computes the default, keyless Sentiment-tab content by blending free signals:
+// • News headline sentiment (GNews/yfinance → news_nlp.py, VADER or lexicon)
+// • Price/technical momentum (compute_technicals aggregate signal)
+// • Adanos Market Sentiment — only when an API key is configured
+//
+// Reuses EquityResearchService's cached fetchers rather than duplicating them;
+// resolves the async legs with per-source done flags guarded by a request id
+// (so a symbol change mid-flight drops stale callbacks), plus a timeout so a
+// dead Python leg never wedges the spinner.
+class EquitySentimentService : public QObject {
+ Q_OBJECT
+ public:
+ static EquitySentimentService& instance();
+
+ /// Kick off all source fetches for `symbol` and emit sentiment_loaded once
+ /// every awaited leg resolves (or the timeout fires).
+ void fetch_sentiment(const QString& symbol);
+
+ signals:
+ void sentiment_loaded(QString symbol, fincept::services::equity::EquitySentimentSnapshot snapshot);
+
+ private:
+ explicit EquitySentimentService(QObject* parent = nullptr);
+ Q_DISABLE_COPY(EquitySentimentService)
+
+ void on_news_loaded(const QString& symbol, const QVector<NewsArticle>& articles);
+ void on_technicals_loaded(const TechnicalsData& data);
+ void on_adanos_loaded(const QString& symbol, const MarketSentimentSnapshot& snapshot);
+ void try_finalize();
+ void finalize();
+
+ // Accumulated state for one contributing signal in the in-flight request.
+ struct SourceState {
+ bool done = false;
+ bool available = false;
+ double score = 0.0; // -1..1
+ double confidence = 0.0; // 0..1
+ };
+
+ quint64 active_request_id_ = 0;
+ QString active_symbol_;
+ bool finalized_ = false;
+
+ bool need_adanos_ = false;
+ bool news_consumed_ = false;
+ bool tech_consumed_ = false;
+ bool adanos_consumed_ = false;
+
+ SourceState news_;
+ SourceState price_;
+ SourceState adanos_;
+
+ int bullish_ = 0;
+ int bearish_ = 0;
+ int neutral_ = 0;
+ QString engine_;
+ QVector<ArticleSentiment> articles_;
+
+ QTimer* timeout_timer_ = nullptr;
+};
+
+} // namespace fincept::services::equity
diff --git a/fincept-qt/src/services/news/NewsNlpService.cpp b/fincept-qt/src/services/news/NewsNlpService.cpp
index 06a6733c3..b55c1bf1f 100644
--- a/fincept-qt/src/services/news/NewsNlpService.cpp
+++ b/fincept-qt/src/services/news/NewsNlpService.cpp
@@ -93,6 +93,50 @@ void NewsNlpService::extract_entities(const QVector<NewsArticle>& articles, Enti
});
}
+void NewsNlpService::analyze_sentiment(const QVector<NewsArticle>& articles, SentimentCallback cb) {
+ auto json_str = QString::fromUtf8(QJsonDocument(articles_to_json(articles)).toJson(QJsonDocument::Compact));
+
+ QPointer<NewsNlpService> self = this;
+ python::PythonRunner::instance().run(
+ "news_nlp.py", {"analyze_sentiment_batch", json_str}, [self, cb](python::PythonResult result) {
+ if (!self)
+ return;
+ if (!result.success) {
+ LOG_WARN("NewsNlpService", "Sentiment analysis failed: " + result.error);
+ cb(false, {});
+ return;
+ }
+
+ auto doc = QJsonDocument::fromJson(result.output.toUtf8());
+ auto obj = doc.object();
+ if (!obj["success"].toBool()) {
+ cb(false, {});
+ return;
+ }
+
+ NewsSentimentResult res;
+ res.engine = obj["engine"].toString();
+ res.overall_score = obj["overall_score"].toDouble();
+
+ const auto agg = obj["aggregate"].toObject();
+ res.bullish = agg["bullish"].toInt();
+ res.bearish = agg["bearish"].toInt();
+ res.neutral = agg["neutral"].toInt();
+
+ for (const auto& v : obj["results"].toArray()) {
+ auto r = v.toObject();
+ ArticleSentimentResult ar;
+ ar.id = r["id"].toString();
+ ar.label = r["sentiment"].toString();
+ ar.score = r["score"].toDouble();
+ ar.confidence = r["confidence"].toDouble();
+ res.per_article.append(ar);
+ }
+
+ cb(true, res);
+ });
+}
+
void NewsNlpService::cluster_semantic(const QVector<NewsArticle>& articles, SemanticClustersCallback cb) {
auto json_str = QString::fromUtf8(QJsonDocument(articles_to_json(articles)).toJson(QJsonDocument::Compact));
diff --git a/fincept-qt/src/services/news/NewsNlpService.h b/fincept-qt/src/services/news/NewsNlpService.h
index f599f43a8..eb016e7cf 100644
--- a/fincept-qt/src/services/news/NewsNlpService.h
+++ b/fincept-qt/src/services/news/NewsNlpService.h
@@ -59,6 +59,24 @@ struct InfrastructureItem {
double distance_km = 0;
};
+// ── Sentiment Types ───────────────────────────────────────────────────────────
+
+struct ArticleSentimentResult {
+ QString id;
+ QString label; // "BULLISH" | "BEARISH" | "NEUTRAL"
+ double score = 0.0; // -1..1
+ double confidence = 0.0; // 0..1
+};
+
+struct NewsSentimentResult {
+ QString engine; // "vader" | "lexicon"
+ double overall_score = 0.0; // -1..1
+ int bullish = 0;
+ int bearish = 0;
+ int neutral = 0;
+ QVector<ArticleSentimentResult> per_article;
+};
+
// ── Service ─────────────────────────────────────────────────────────────────
class NewsNlpService : public QObject {
@@ -69,12 +87,17 @@ class NewsNlpService : public QObject {
using InfraCallback = std::function<void(bool, QVector<InfrastructureItem>)>;
using TranslateCallback = std::function<void(bool, QString translated, QString detected_lang)>;
using SemanticClustersCallback = std::function<void(bool, QJsonArray clusters)>;
+ using SentimentCallback = std::function<void(bool, NewsSentimentResult)>;
static NewsNlpService& instance();
/// Extract entities (countries, orgs, people, tickers) from articles.
void extract_entities(const QVector<NewsArticle>& articles, EntitiesCallback cb);
+ /// Headline sentiment (VADER when available, keyword fallback) via
+ /// news_nlp.py. Per-article results are keyed by NewsArticle::id.
+ void analyze_sentiment(const QVector<NewsArticle>& articles, SentimentCallback cb);
+
/// Semantic clustering via TF-IDF cosine similarity.
void cluster_semantic(const QVector<NewsArticle>& articles, SemanticClustersCallback cb);
diff --git a/fincept-qt/src/services/portfolio/PortfolioService_Summary.cpp b/fincept-qt/src/services/portfolio/PortfolioService_Summary.cpp
index 17adb19e6..66372aef1 100644
--- a/fincept-qt/src/services/portfolio/PortfolioService_Summary.cpp
+++ b/fincept-qt/src/services/portfolio/PortfolioService_Summary.cpp
@@ -242,6 +242,7 @@ void PortfolioService::finalize_summary(const QString& portfolio_id,
double total_mv = 0;
double total_cost = 0;
double total_day = 0;
+ double total_prev = 0; // previous-close value of PRICED holdings only (day% base)
for (const auto& asset : assets) {
portfolio::HoldingWithQuote h;
@@ -260,6 +261,7 @@ void PortfolioService::finalize_summary(const QString& portfolio_id,
h.current_price = it->price;
h.day_change = it->change;
h.day_change_percent = it->change_pct;
+ total_prev += (h.current_price - h.day_change) * h.quantity; // priced holdings only
} else {
// Fallback to avg buy price if no quote (broker missed the symbol,
// or yfinance returned nothing).
@@ -292,8 +294,10 @@ void PortfolioService::finalize_summary(const QString& portfolio_id,
summary.total_unrealized_pnl = total_mv - total_cost;
summary.total_unrealized_pnl_percent = (total_cost > 0) ? ((total_mv - total_cost) / total_cost) * 100.0 : 0;
summary.total_day_change = total_day;
- summary.total_day_change_percent =
- (total_mv - total_day > 0) ? (total_day / (total_mv - total_day)) * 100.0 : 0;
+ // Percent off the previous-close base of PRICED holdings only. Using
+ // (total_mv − total_day) folded unpriced holdings' full stale value into the
+ // denominator, diluting the day % whenever any symbol failed to quote.
+ summary.total_day_change_percent = (total_prev > 0) ? (total_day / total_prev) * 100.0 : 0;
summary.total_positions = assets.size();
summary.last_updated = QDateTime::currentDateTimeUtc().toString(Qt::ISODate);
diff --git a/fincept-qt/src/services/updater/UpdateService.h b/fincept-qt/src/services/updater/UpdateService.h
index ae888bb8c..ec354e4f8 100644
--- a/fincept-qt/src/services/updater/UpdateService.h
+++ b/fincept-qt/src/services/updater/UpdateService.h
@@ -19,7 +19,7 @@ namespace fincept::services {
/// Manifest schema (see updates.json):
/// {
/// "updates": {
-/// "windows-x64": { "latest-version": "4.0.3", "download-url": "...", "sha256": "...", "open-url": "...", "changelog": "..." },
+/// "windows-x64": { "latest-version": "4.1.0", "download-url": "...", "sha256": "...", "open-url": "...", "changelog": "..." },
/// "windows-arm64":{ ... },
/// "linux-x64": { ... },
/// "macos-arm64": { ... },
diff --git a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
index 60c43dde6..015ce089d 100644
--- a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
+++ b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp
@@ -268,8 +268,19 @@ std::optional<PtPosition> PaperTradingRepository::find_position(const QString& p
}
Result<void> PaperTradingRepository::update_position(const QString& id, double quantity, double entry_price) {
- return exec_write("UPDATE pt_positions SET quantity = ?, entry_price = ? WHERE id = ?",
- {quantity, entry_price, id});
+ // Recompute unrealized_pnl in the same write. Previously this updated only
+ // quantity/entry_price, leaving unrealized_pnl stale after an averaging fill
+ // or a partial close until the next price tick — so a freshly averaged/reduced
+ // position showed P&L against the OLD entry/qty. Recompute against the last
+ // good current_price (guarded: a 0/unset mark keeps the existing value so we
+ // never surface a phantom full-notional P&L).
+ return exec_write(
+ "UPDATE pt_positions SET quantity = ?, entry_price = ?, "
+ "unrealized_pnl = CASE WHEN current_price > 0 THEN "
+ "(CASE WHEN side = 'long' THEN (current_price - ?) * ? ELSE (? - current_price) * ? END) "
+ "ELSE unrealized_pnl END "
+ "WHERE id = ?",
+ {quantity, entry_price, entry_price, quantity, entry_price, quantity, id});
}
Result<void> PaperTradingRepository::update_position_price(const QString& portfolio_id, const QString& symbol,
diff --git a/fincept-qt/src/storage/repositories/PortfolioRepository.cpp b/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
index 981318700..6ff3fce5f 100644
--- a/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
+++ b/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
@@ -151,7 +151,12 @@ Result<qint64> PortfolioRepository::add_asset(const QString& portfolio_id, const
if (existing.is_ok() && !existing.value().isEmpty()) {
auto& asset = existing.value().first();
double new_qty = asset.quantity + qty;
- double new_avg = ((asset.avg_buy_price * asset.quantity) + (price * qty)) / new_qty;
+ // Guard the weighted-average against a zero/near-zero total quantity — a
+ // 0/0 here would write NaN into avg_buy_price and poison every portfolio
+ // total downstream.
+ double new_avg = (new_qty > 1e-9)
+ ? ((asset.avg_buy_price * asset.quantity) + (price * qty)) / new_qty
+ : asset.avg_buy_price;
QString merged_sector = sector.isEmpty() ? asset.sector : sector;
QString merged_broker_symbol = broker_symbol.isEmpty() ? asset.broker_symbol : broker_symbol;
QString merged_exchange = exchange.isEmpty() ? asset.exchange : exchange;
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index f8a906718..aef137df8 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -9,6 +9,7 @@
#include "trading/instruments/InstrumentService.h"
#include "trading/brokers/alpaca/AlpacaWebSocket.h"
#include "trading/websocket/AliceBlueWebSocket.h"
+#include "trading/websocket/AngelOneWebSocket.h"
#include "trading/websocket/BrokerWebSocketBase.h"
#include "trading/websocket/DhanWebSocket.h"
#include "trading/websocket/FivePaisaWebSocket.h"
@@ -19,6 +20,7 @@
#include "trading/websocket/MotilalPoller.h"
#include "trading/websocket/ShoonyaWebSocket.h"
#include "trading/websocket/UpstoxWebSocket.h"
+#include "trading/websocket/ZerodhaWebSocket.h"
#include <QDate>
#include <QDateTime>
@@ -133,6 +135,15 @@ void AccountDataStream::resume() {
active_feed_timer_->start();
}
+void AccountDataStream::refresh_portfolio_now() {
+ if (!running_)
+ return;
+ async_fetch_positions();
+ async_fetch_holdings();
+ async_fetch_orders();
+ async_fetch_funds();
+}
+
// ── Symbol management ───────────────────────────────────────────────────────
void AccountDataStream::subscribe_symbols(const QString& consumer_id, const QStringList& symbols) {
@@ -348,6 +359,9 @@ void AccountDataStream::async_fetch_positions() {
self->check_token_expiry(result.error);
return;
}
+ // Success — log the count so an empty live blotter can be told apart from a
+ // token/error (which logs WARN above): 0 rows here = genuinely no positions.
+ LOG_INFO(ADS_TAG, QString("get_positions %1/%2 → %3 row(s)").arg(bid, acct_id).arg(result.data->size()));
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
if (!self) return;
self->positions_ = data;
@@ -375,6 +389,7 @@ void AccountDataStream::async_fetch_holdings() {
self->check_token_expiry(result.error);
return;
}
+ LOG_INFO(ADS_TAG, QString("get_holdings %1/%2 → %3 row(s)").arg(bid, acct_id).arg(result.data->size()));
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
if (!self) return;
self->holdings_ = data;
@@ -402,6 +417,7 @@ void AccountDataStream::async_fetch_orders() {
self->check_token_expiry(result.error);
return;
}
+ LOG_INFO(ADS_TAG, QString("get_orders %1/%2 → %3 row(s)").arg(bid, acct_id).arg(result.data->size()));
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
if (!self) return;
self->orders_ = data;
@@ -749,6 +765,17 @@ void AccountDataStream::wire_base_ws(BrokerWebSocketBase* ws) {
});
}
+// Map a normalised exchange string → Angel One SmartStream segment code.
+static AoExchangeType ao_exchange_type(const QString& exch) {
+ const QString e = exch.toUpper();
+ if (e == "NFO" || e == "NSE_FO") return AoExchangeType::NSE_FO;
+ if (e == "BSE") return AoExchangeType::BSE_CM;
+ if (e == "BFO" || e == "BSE_FO") return AoExchangeType::BSE_FO;
+ if (e == "MCX") return AoExchangeType::MCX_FO;
+ if (e == "CDS") return AoExchangeType::CDE_FO;
+ return AoExchangeType::NSE_CM; // NSE cash / default
+}
+
void AccountDataStream::ws_init() {
if (broker_id_ == "fyers") {
auto creds = AccountManager::instance().load_credentials(account_id_);
@@ -926,6 +953,54 @@ void AccountDataStream::ws_init() {
return;
}
+ if (broker_id_ == "zerodha") {
+ auto creds = AccountManager::instance().load_credentials(account_id_);
+ if (creds.api_key.isEmpty() || creds.access_token.isEmpty()) {
+ LOG_WARN(ADS_TAG, QString("Zerodha WS: missing api_key/access_token for %1").arg(account_id_));
+ return;
+ }
+ auto* zws = new ZerodhaWebSocket(creds.api_key, creds.access_token, this);
+ ws_ = zws;
+ connect(zws, &ZerodhaWebSocket::tick_received, this, [this](const ZerodhaTick& tick) {
+ // KiteTicker ticks are keyed by numeric instrument_token — reverse-map
+ // to the normalised symbol via the loaded Zerodha master. Drop ticks we
+ // can't resolve or with a non-positive LTP so a bad map never surfaces a
+ // wrong price under a wrong symbol (quotes fall back to REST instead).
+ auto inst = InstrumentService::instance().find_by_token(tick.instrument_token, broker_id_);
+ if (!inst.has_value() || inst->symbol.isEmpty() || tick.ltp <= 0.0)
+ return;
+ ++ws_tick_count_;
+ BrokerQuote q;
+ q.symbol = inst->symbol;
+ q.ltp = tick.ltp;
+ q.open = tick.open;
+ q.high = tick.high;
+ q.low = tick.low;
+ q.close = tick.close;
+ q.volume = tick.volume;
+ q.change = tick.close > 0 ? tick.ltp - tick.close : 0.0;
+ q.change_pct = tick.close > 0 ? (tick.ltp - tick.close) / tick.close * 100.0 : 0.0;
+ q.oi = tick.oi;
+ q.timestamp = tick.exchange_timestamp.isValid() ? tick.exchange_timestamp.toMSecsSinceEpoch() : 0;
+ quote_cache_[q.symbol] = q;
+ emit quote_updated(account_id_, q.symbol, q);
+ });
+ connect(zws, &ZerodhaWebSocket::connected, this, [this]() {
+ LOG_INFO(ADS_TAG, QString("Zerodha WS connected for %1").arg(account_id_));
+ emit connection_state_changed(account_id_, ConnectionState::Connected);
+ ws_resubscribe(); // resolves current symbols → tokens and subscribes
+ });
+ connect(zws, &ZerodhaWebSocket::disconnected, this, [this]() {
+ emit connection_state_changed(account_id_, ConnectionState::Disconnected);
+ });
+ connect(zws, &ZerodhaWebSocket::error_occurred, this, [this](const QString& e) {
+ LOG_ERROR(ADS_TAG, QString("Zerodha WS error: %1").arg(e));
+ check_token_expiry(e);
+ });
+ zws->open();
+ return;
+ }
+
// ── Phase 2 broker WebSocket adapters (shared BrokerWebSocketBase) ─────────
// Helper: collect the current selected + watchlist symbols (deduped).
auto current_symbols = [this]() {
@@ -1165,10 +1240,58 @@ void AccountDataStream::ws_init() {
auto obj = doc.object();
const QString feed_token = obj.value("feed_token").toString();
const QString client_code = obj.value("client_code").toString();
- if (feed_token.isEmpty() || client_code.isEmpty())
+ if (feed_token.isEmpty() || client_code.isEmpty()) {
+ LOG_WARN(ADS_TAG, QString("AngelOne WS: missing feed_token/client_code for %1").arg(account_id_));
return;
+ }
- LOG_INFO(ADS_TAG, QString("WebSocket available for account %1 (AngelOne) — deferred to screen wiring").arg(account_id_));
+ auto* aows = new AngelOneWebSocket(creds.api_key, client_code, feed_token, this);
+ ws_ = aows;
+ connect(aows, &AngelOneWebSocket::tick_received, this, [this](const AoTick& tick) {
+ // SmartStream ticks carry a token string (and the adapter may set
+ // tick.symbol). Resolve to a normalised symbol, preferring the adapter's
+ // value, else the master lookup. Drop unresolved / non-positive ticks.
+ QString sym = tick.symbol;
+ if (sym.isEmpty()) {
+ bool ok = false;
+ const quint32 tok = tick.token.toUInt(&ok);
+ if (ok) {
+ auto inst = InstrumentService::instance().find_by_token(tok, broker_id_);
+ if (inst.has_value())
+ sym = inst->symbol;
+ }
+ }
+ if (sym.isEmpty() || tick.ltp <= 0.0)
+ return;
+ ++ws_tick_count_;
+ BrokerQuote q;
+ q.symbol = sym;
+ q.ltp = tick.ltp;
+ q.open = tick.open;
+ q.high = tick.high;
+ q.low = tick.low;
+ q.close = tick.close;
+ q.volume = static_cast<double>(tick.volume);
+ q.change = tick.close > 0 ? tick.ltp - tick.close : 0.0;
+ q.change_pct = tick.close > 0 ? (tick.ltp - tick.close) / tick.close * 100.0 : 0.0;
+ q.oi = tick.oi;
+ q.timestamp = tick.exchange_timestamp.isValid() ? tick.exchange_timestamp.toMSecsSinceEpoch() : 0;
+ quote_cache_[q.symbol] = q;
+ emit quote_updated(account_id_, q.symbol, q);
+ });
+ connect(aows, &AngelOneWebSocket::connected, this, [this]() {
+ LOG_INFO(ADS_TAG, QString("AngelOne WS connected for %1").arg(account_id_));
+ emit connection_state_changed(account_id_, ConnectionState::Connected);
+ ws_resubscribe(); // resolves current symbols → {token, exchange_type} and subscribes
+ });
+ connect(aows, &AngelOneWebSocket::disconnected, this, [this]() {
+ emit connection_state_changed(account_id_, ConnectionState::Disconnected);
+ });
+ connect(aows, &AngelOneWebSocket::error_occurred, this, [this](const QString& e) {
+ LOG_ERROR(ADS_TAG, QString("AngelOne WS error: %1").arg(e));
+ check_token_expiry(e);
+ });
+ aows->open();
}
void AccountDataStream::ws_teardown() {
@@ -1187,6 +1310,10 @@ bool AccountDataStream::ws_active() const {
return fws->is_connected() && ws_tick_count_ > 0;
if (auto* aws = qobject_cast<AlpacaWebSocket*>(ws_))
return aws->is_connected() && ws_tick_count_ > 0;
+ if (auto* zws = qobject_cast<ZerodhaWebSocket*>(ws_))
+ return zws->is_connected() && ws_tick_count_ > 0;
+ if (auto* aows = qobject_cast<AngelOneWebSocket*>(ws_))
+ return aows->is_connected() && ws_tick_count_ > 0;
if (auto* b = qobject_cast<BrokerWebSocketBase*>(ws_))
return b->is_connected() && ws_tick_count_ > 0;
return false;
@@ -1201,6 +1328,10 @@ bool AccountDataStream::ws_connected() const {
return fws->is_connected();
if (auto* aws = qobject_cast<AlpacaWebSocket*>(ws_))
return aws->is_connected();
+ if (auto* zws = qobject_cast<ZerodhaWebSocket*>(ws_))
+ return zws->is_connected();
+ if (auto* aows = qobject_cast<AngelOneWebSocket*>(ws_))
+ return aows->is_connected();
if (auto* b = qobject_cast<BrokerWebSocketBase*>(ws_))
return b->is_connected();
return false;
@@ -1252,6 +1383,52 @@ void AccountDataStream::ws_resubscribe() {
aws->set_subscriptions(symbols);
}
+ // Zerodha KiteTicker — resolve current symbols → numeric instrument tokens.
+ if (auto* zws = qobject_cast<ZerodhaWebSocket*>(ws_)) {
+ QStringList symbols;
+ if (!selected_symbol_.isEmpty())
+ symbols.append(selected_symbol_);
+ for (const QString& s : subscribed_symbols())
+ if (!symbols.contains(s))
+ symbols.append(s);
+ symbols.removeDuplicates();
+ QVector<quint32> tokens;
+ auto& svc = InstrumentService::instance();
+ for (const auto& s : symbols) {
+ const QString exch = (s == selected_symbol_ && !selected_exchange_.isEmpty())
+ ? selected_exchange_
+ : QStringLiteral("NSE");
+ auto tok = svc.instrument_token(s, exch, broker_id_);
+ if (tok.has_value() && *tok > 0)
+ tokens.append(static_cast<quint32>(*tok));
+ }
+ zws->set_subscriptions(tokens);
+ return;
+ }
+
+ // Angel One SmartStream — resolve symbols → {token string, exchange segment}.
+ if (auto* aows = qobject_cast<AngelOneWebSocket*>(ws_)) {
+ QStringList symbols;
+ if (!selected_symbol_.isEmpty())
+ symbols.append(selected_symbol_);
+ for (const QString& s : subscribed_symbols())
+ if (!symbols.contains(s))
+ symbols.append(s);
+ symbols.removeDuplicates();
+ QVector<AngelOneWebSocket::Subscription> subs;
+ auto& svc = InstrumentService::instance();
+ for (const auto& s : symbols) {
+ const QString exch = (s == selected_symbol_ && !selected_exchange_.isEmpty())
+ ? selected_exchange_
+ : QStringLiteral("NSE");
+ auto tok = svc.instrument_token(s, exch, broker_id_);
+ if (tok.has_value() && *tok > 0)
+ subs.append({QString::number(*tok), ao_exchange_type(exch)});
+ }
+ aows->set_subscriptions(subs);
+ return;
+ }
+
// Generic Phase 2 adapters (shared BrokerWebSocketBase). Rebuild the symbol
// set wholesale: drop existing subscriptions, then subscribe the current set.
if (auto* b = qobject_cast<BrokerWebSocketBase*>(ws_)) {
diff --git a/fincept-qt/src/trading/AccountDataStream.h b/fincept-qt/src/trading/AccountDataStream.h
index 78e124589..1befc8d88 100644
--- a/fincept-qt/src/trading/AccountDataStream.h
+++ b/fincept-qt/src/trading/AccountDataStream.h
@@ -37,6 +37,15 @@ class AccountDataStream : public QObject {
void resume(); // Restart timers (screen shown)
bool is_running() const { return running_; }
+ // Force an immediate one-shot refresh of positions / holdings / orders /
+ // funds, bypassing the ADS_PORTFOLIO_POLL_MS (5-min) poll cadence. Called on
+ // UI transitions where the stream is already running so start()/resume()
+ // won't re-fetch on their own — screen reopen, account switch, paper↔live
+ // toggle. Without it the blotter shows stale (or, after a context clear,
+ // blank) data until the next poll. Each underlying fetch self-guards on
+ // credentials, so this is a no-op for an unconfigured account.
+ void refresh_portfolio_now();
+
// --- Symbol management (multi-consumer) ---
// Each consumer ("equity:watchlist", "algo:<deploymentId>", …) owns an
// independent symbol set. The WS/poll universe is the UNION across all
diff --git a/fincept-qt/src/trading/BrokerRegistry.cpp b/fincept-qt/src/trading/BrokerRegistry.cpp
index 7cf932769..010e5f464 100644
--- a/fincept-qt/src/trading/BrokerRegistry.cpp
+++ b/fincept-qt/src/trading/BrokerRegistry.cpp
@@ -1,4 +1,4 @@
-// Broker Registry — factory + lookup for all 16 broker implementations
+// Broker Registry — factory + lookup for all 22 broker implementations
#include "trading/BrokerRegistry.h"
diff --git a/fincept-qt/src/trading/DataStreamManager.cpp b/fincept-qt/src/trading/DataStreamManager.cpp
index 3e252a991..93beeb603 100644
--- a/fincept-qt/src/trading/DataStreamManager.cpp
+++ b/fincept-qt/src/trading/DataStreamManager.cpp
@@ -2,6 +2,7 @@
#include "core/logging/Logger.h"
#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
# include "datahub/DataHub.h"
# include "datahub/DataHubMetaTypes.h"
@@ -17,13 +18,14 @@ namespace fincept::trading {
namespace {
constexpr const char* DSM_TAG = "DataStreamManager";
-// Brokers whose tokens expire daily at ~3:00 AM IST. Crypto and international
-// brokers (alpaca, ibkr, tradier, saxo) are intentionally excluded.
-const QSet<QString>& indian_brokers() {
- static const QSet<QString> kSet = {
- "zerodha", "angelone", "upstox", "fyers", "dhan", "groww",
- "kotak", "iifl", "fivepaisa", "aliceblue", "shoonya", "motilal"};
- return kSet;
+// Brokers whose tokens expire daily at ~3:00 AM IST: every Indian-region broker.
+// Derived from each broker's own profile (region == "IN") rather than a
+// hand-maintained list, so newly-added Indian brokers (samco, flattrade, paytm,
+// tradejini, icicidirect, …) are covered automatically and can't silently drift
+// out of the sweep. International brokers (US/EU regions) are excluded by region.
+bool is_daily_expiring_broker(const QString& broker_id) {
+ auto* b = BrokerRegistry::instance().get(broker_id);
+ return b != nullptr && b->profile().region == QLatin1String("IN");
}
// Hourly cadence is enough to catch the 3:00 AM IST window without polling
@@ -80,7 +82,7 @@ void DataStreamManager::check_indian_token_expiry() {
for (const auto& acct : accounts) {
if (!acct.is_active || acct.trading_mode != "live")
continue;
- if (!indian_brokers().contains(acct.broker_id))
+ if (!is_daily_expiring_broker(acct.broker_id))
continue;
if (am.connection_state(acct.account_id) == ConnectionState::TokenExpired)
continue;
@@ -172,6 +174,11 @@ void DataStreamManager::resume_all() {
stream->resume();
}
+void DataStreamManager::refresh_portfolio(const QString& account_id) {
+ if (auto* s = stream_for(account_id))
+ s->refresh_portfolio_now();
+}
+
// ── Query ───────────────────────────────────────────────────────────────────
bool DataStreamManager::has_stream(const QString& account_id) const {
diff --git a/fincept-qt/src/trading/DataStreamManager.h b/fincept-qt/src/trading/DataStreamManager.h
index d6d8f024d..9dea10718 100644
--- a/fincept-qt/src/trading/DataStreamManager.h
+++ b/fincept-qt/src/trading/DataStreamManager.h
@@ -40,6 +40,12 @@ class DataStreamManager : public QObject
void pause_all(); // Screen hidden — pause all timers
void resume_all(); // Screen shown — resume all timers
+ // Force an immediate portfolio (positions/holdings/orders/funds) refetch for
+ // one account, bypassing the 5-min poll. No-op if no stream exists for the
+ // account. Used by UI transitions (reopen / account switch / mode toggle) so
+ // the blotter shows fresh broker data right away instead of stale-or-blank.
+ void refresh_portfolio(const QString& account_id);
+
// --- Query ---
bool has_stream(const QString& account_id) const;
QStringList active_stream_ids() const;
diff --git a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
index e63f6720e..702c5076c 100644
--- a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
+++ b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
@@ -381,6 +381,7 @@ ApiResponse<QVector<BrokerPosition>> AliceBlueBroker::get_positions(const Broker
pos.avg_price = p["dayBuyPrice"].toDouble() > 0 ? p["dayBuyPrice"].toDouble() : p["netAveragePrice"].toDouble();
pos.ltp = p["ltp"].toDouble();
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();
positions.append(pos);
}
@@ -422,9 +423,11 @@ ApiResponse<QVector<BrokerHolding>> AliceBlueBroker::get_holdings(const BrokerCr
continue;
QString exchange = nse_sym.isEmpty() ? "BSE" : "NSE";
- int qty = h["dpQuantity"].toInt();
+ // totalQuantity is the true total holding (settled + T1); dpQuantity is
+ // settled-only and would drop unsettled T1 quantity.
+ int qty = h["totalQuantity"].toInt();
if (qty == 0)
- qty = h["totalQuantity"].toInt();
+ qty = h["dpQuantity"].toInt();
double avg_price = h["averageTradedPrice"].toDouble();
if (avg_price == 0.0)
avg_price = h["investedPrice"].toDouble();
diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
index 6e9c732ff..6942c3be7 100644
--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
@@ -373,12 +373,12 @@ ApiResponse<QVector<BrokerPosition>> DhanBroker::get_positions(const BrokerCrede
pos.avg_price = p.value("avgCostPrice").toDouble();
// Positions don't carry an LTP field; callers wanting live MTM must
// refresh via /v2/marketfeed/ltp. Leave 0 here.
+ // TODO: hydrate LTP to populate pnl_pct
pos.ltp = 0.0;
pos.pnl = p.value("unrealizedProfit").toDouble();
pos.day_pnl = p.value("realizedProfit").toDouble();
pos.side = qty > 0 ? "LONG" : "SHORT";
- if (pos.avg_price > 0 && pos.ltp > 0)
- pos.pnl_pct = (pos.ltp - pos.avg_price) / pos.avg_price * 100.0;
+ pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
positions.append(pos);
}
return {true, positions, "", ts};
@@ -410,6 +410,7 @@ ApiResponse<QVector<BrokerHolding>> DhanBroker::get_holdings(const BrokerCredent
holding.avg_price = h.value("avgCostPrice").toDouble();
// /v2/holdings does NOT return an LTP field. Caller must hydrate via
// /v2/marketfeed/ltp using securityId — leave zero rather than fabricate.
+ // TODO: hydrate LTP to populate current_value/pnl
holding.ltp = 0.0;
holding.invested_value = holding.quantity * holding.avg_price;
holding.current_value = 0.0;
diff --git a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp
index 75da6b205..01bff4c48 100644
--- a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp
@@ -480,6 +480,7 @@ ApiResponse<QVector<BrokerPosition>> FivePaisaBroker::get_positions(const Broker
pos.avg_price = p["AvgRate"].toDouble();
pos.ltp = p["LTP"].toDouble();
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;
positions.append(pos);
}
@@ -519,7 +520,10 @@ ApiResponse<QVector<BrokerHolding>> FivePaisaBroker::get_holdings(const BrokerCr
holding.quantity = qty;
holding.avg_price = avg;
holding.ltp = ltp;
+ holding.invested_value = qty * avg;
+ holding.current_value = qty * ltp;
holding.pnl = (ltp - avg) * qty;
+ holding.pnl_pct = (holding.invested_value > 0.0) ? (holding.pnl / holding.invested_value) * 100.0 : 0.0;
holdings.append(holding);
}
diff --git a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
index 8fc8db762..c0bfca5b7 100644
--- a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
+++ b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp
@@ -387,6 +387,7 @@ ApiResponse<QVector<BrokerPosition>> FlattradeBroker::get_positions(const Broker
pos.avg_price = o.value("netavgprc").toString().toDouble();
pos.ltp = o.value("lp").toString().toDouble();
pos.pnl = o.value("urmtom").toString().toDouble() + o.value("rpnl").toString().toDouble();
+ pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.side = net_qty > 0 ? "LONG" : "SHORT";
positions.append(pos);
}
@@ -455,6 +456,8 @@ ApiResponse<QVector<BrokerHolding>> FlattradeBroker::get_holdings(const BrokerCr
h.exchange = exchange;
h.quantity = total_qty;
h.avg_price = o.value("upldprc").toString().toDouble();
+ // Holdings response carries no LTP field — hydrate via GetQuotes for live MTM.
+ // TODO: hydrate LTP to populate current_value/pnl
h.ltp = 0.0;
h.invested_value = total_qty * h.avg_price;
h.current_value = 0.0;
diff --git a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
index 0ebfcfbbe..ca7b13d62 100644
--- a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
+++ b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
@@ -346,6 +346,7 @@ ApiResponse<QVector<BrokerPosition>> FyersBroker::get_positions(const BrokerCred
pos.avg_price = p.value("netAvg").toDouble();
pos.ltp = p.value("ltp").toDouble();
pos.pnl = p.value("pl").toDouble();
+ pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.side = pos.quantity >= 0 ? "buy" : "sell";
positions.append(pos);
}
diff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
index b4c3f6a4b..428489da5 100644
--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp
@@ -534,6 +534,8 @@ ApiResponse<QVector<BrokerPosition>> GrowwBroker::get_positions(const BrokerCred
pos.ltp = 0.0; // Not returned by positions endpoint; query live-data/ltp separately if needed.
pos.pnl = p["realised_pnl"].toDouble();
pos.product_type = p["product"].toString();
+ // TODO: hydrate LTP to populate pnl_pct
+ pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
positions.append(pos);
}
return true;
@@ -568,8 +570,12 @@ ApiResponse<QVector<BrokerHolding>> GrowwBroker::get_holdings(const BrokerCreden
holding.exchange = h.contains("exchange") ? h["exchange"].toString() : QStringLiteral("NSE");
holding.quantity = h["quantity"].toInt();
holding.avg_price = h["average_price"].toDouble();
+ holding.invested_value = holding.quantity * holding.avg_price;
+ // TODO: hydrate LTP to populate current_value/pnl
holding.ltp = 0.0; // Not returned by holdings endpoint; query live-data/ltp separately if needed.
+ holding.current_value = 0.0;
holding.pnl = 0.0; // Derived value — compute in the service layer once LTP is fetched.
+ holding.pnl_pct = 0.0;
holdings.append(holding);
}
diff --git a/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp b/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp
index b899ca99f..1939feee6 100644
--- a/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp
+++ b/fincept-qt/src/trading/brokers/ibkr/IBKRBroker.cpp
@@ -406,8 +406,13 @@ ApiResponse<QVector<BrokerPosition>> IBKRBroker::get_positions(const BrokerCrede
pos.pnl = o.value("unrealizedPnl").toDouble();
pos.day_pnl = o.value("realizedPnl").toDouble();
pos.side = qty > 0 ? "LONG" : "SHORT";
- if (pos.avg_price > 0)
- pos.pnl_pct = (pos.ltp - pos.avg_price) / pos.avg_price * 100.0;
+ // avgCost is per-contract cost INCLUDING the contract multiplier (e.g. ×100
+ // for options) while mktPrice is the raw unit price — a price-based % mixes
+ // scales. Compute the % from values instead: invested = qty*avgCost (correctly
+ // scaled), current = API mktValue (already correctly scaled).
+ const double invested_value = qty * pos.avg_price;
+ const double current_value = o.value("mktValue").toDouble();
+ pos.pnl_pct = (invested_value > 0.0) ? ((current_value - invested_value) / invested_value) * 100.0 : 0.0;
positions.append(pos);
}
@@ -448,8 +453,10 @@ ApiResponse<QVector<BrokerHolding>> IBKRBroker::get_holdings(const BrokerCredent
h.pnl = o.value("unrealizedPnl").toDouble();
h.invested_value = qty * h.avg_price;
h.current_value = o.value("mktValue").toDouble();
- if (h.invested_value > 0)
- h.pnl_pct = h.pnl / h.invested_value * 100.0;
+ // avgCost bakes in the contract multiplier while mktPrice is the raw unit
+ // price, so a price-based % mixes scales. Derive the % from the (correctly
+ // scaled) values: invested = qty*avgCost, current = API mktValue.
+ h.pnl_pct = (h.invested_value > 0.0) ? ((h.current_value - h.invested_value) / h.invested_value) * 100.0 : 0.0;
holdings.append(h);
}
diff --git a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp
index 872092b58..2ba0a6ed8 100644
--- a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp
+++ b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp
@@ -440,6 +440,7 @@ ApiResponse<QVector<BrokerPosition>> IIFLBroker::get_positions(const BrokerCrede
pos.avg_price = o.value("AveragePrice").toDouble();
pos.ltp = o.value("LastPrice").toDouble();
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();
positions.append(pos);
}
@@ -485,7 +486,10 @@ ApiResponse<QVector<BrokerHolding>> IIFLBroker::get_holdings(const BrokerCredent
h.quantity = o.value("HoldingQuantity").toInt();
h.avg_price = o.value("BuyPrice").toDouble();
h.ltp = o.value("Price").toDouble();
+ h.invested_value = h.quantity * h.avg_price;
+ h.current_value = h.quantity * h.ltp;
h.pnl = (h.ltp - h.avg_price) * h.quantity;
+ h.pnl_pct = (h.invested_value > 0.0) ? (h.pnl / h.invested_value) * 100.0 : 0.0;
holdings.append(h);
}
diff --git a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
index b7cabb674..b56f46a82 100644
--- a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
+++ b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
@@ -580,11 +580,19 @@ ApiResponse<QVector<BrokerPosition>> KotakBroker::get_positions(const BrokerCred
pos.product_type = o.value("prod").toString();
pos.quantity = net_qty;
pos.avg_price = buy_qty > 0 ? buy_amt / buy_qty : 0.0;
+ // Net-short (sold more than bought; buy_qty may be 0) has no buy leg to
+ // derive an entry price from — fall back to the sell leg so avg_price and
+ // pnl_pct are meaningful instead of 0.
+ if (net_qty < 0)
+ pos.avg_price = sell_qty > 0 ? sell_amt / sell_qty : pos.avg_price;
pos.ltp = o.value("ltp").toString().toDouble();
pos.pnl = (pos.ltp * net_qty) - (buy_amt - sell_amt);
pos.side = net_qty > 0 ? "LONG" : "SHORT";
- if (pos.avg_price > 0)
- pos.pnl_pct = (pos.ltp - pos.avg_price) / pos.avg_price * 100.0;
+ // ltp is populated from the positions response above. Sign the % by side so
+ // a short shows a gain when price falls below the (sell-leg) entry price.
+ pos.pnl_pct = (pos.avg_price > 0.0)
+ ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 * (net_qty < 0 ? -1.0 : 1.0)
+ : 0.0;
positions.append(pos);
}
return {true, positions, "", ts};
diff --git a/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp b/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
index 2cb01d46a..afaf981c6 100644
--- a/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
+++ b/fincept-qt/src/trading/brokers/metaapi/MetaApiBroker.cpp
@@ -550,6 +550,10 @@ ApiResponse<QVector<BrokerHolding>> MetaApiBroker::get_holdings(const BrokerCred
h.avg_price = p.avg_price;
h.ltp = p.ltp;
h.pnl = p.pnl;
+ // TODO: invested/current ignore contract (lot) size; pnl from API 'profit' is authoritative.
+ // quantity is in lots (e.g. 0.10), not units, so price*lots is off by the
+ // contract size. The MetaAPI position payload carries no contract/lot-size
+ // field to scale by, so the arithmetic is left as-is.
h.invested_value = p.avg_price * p.quantity;
h.current_value = p.ltp * p.quantity;
holdings.append(h);
diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
index 4a056beb0..d8ebe679f 100644
--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
@@ -120,7 +120,7 @@ QMap<QString, QString> MotilalBroker::auth_headers(const BrokerCredentials& cred
{"devicemodel", "PC"},
{"manufacturer", "Generic"},
{"productname", "FinceptTerminal"},
- {"productversion", "4.0.3"},
+ {"productversion", "4.1.0"},
{"browsername", "Chrome"},
{"browserversion", "120.0"},
};
@@ -163,7 +163,7 @@ TokenExchangeResponse MotilalBroker::exchange_token(const QString& api_key, cons
{"devicemodel", "PC"},
{"manufacturer", "Generic"},
{"productname", "FinceptTerminal"},
- {"productversion", "4.0.3"},
+ {"productversion", "4.1.0"},
{"browsername", "Chrome"},
{"browserversion", "120.0"},
};
diff --git a/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp b/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp
index 1048b559f..ae725fb12 100644
--- a/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp
+++ b/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp
@@ -374,6 +374,7 @@ ApiResponse<QVector<BrokerPosition>> SamcoBroker::get_positions(const BrokerCred
pos.avg_price = samco_d(o.value("averagePrice"));
pos.ltp = samco_d(o.value("lastTradedPrice"));
pos.pnl = samco_d(o.value("realizedGainAndLoss")) + samco_d(o.value("mtmGainLoss"));
+ pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.side = net_qty > 0 ? "LONG" : "SHORT";
positions.append(pos);
}
diff --git a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
index 70259e09c..2b6b64830 100644
--- a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
+++ b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
@@ -359,6 +359,7 @@ ApiResponse<QVector<BrokerPosition>> TradejiniBroker::get_positions(const Broker
pos.avg_price = o.value("netAvgPrice").toVariant().toDouble();
pos.ltp = o.value("ltp").toVariant().toDouble();
pos.pnl = o.value("realizedPnl").toVariant().toDouble() + o.value("unrealizedPnl").toVariant().toDouble();
+ pos.pnl_pct = (pos.avg_price > 0.0) ? ((pos.ltp - pos.avg_price) / pos.avg_price) * 100.0 : 0.0;
pos.side = net_qty > 0 ? "LONG" : "SHORT";
positions.append(pos);
}
@@ -411,6 +412,8 @@ ApiResponse<QVector<BrokerHolding>> TradejiniBroker::get_holdings(const BrokerCr
h.pnl_pct = tj_first(o, "pnlPercent", "pnlpercent").toVariant().toDouble();
h.invested_value = h.quantity * h.avg_price;
h.current_value = h.quantity * h.ltp;
+ if (h.pnl_pct == 0.0 && h.invested_value > 0.0)
+ h.pnl_pct = (h.pnl / h.invested_value) * 100.0;
holdings.append(h);
}
diff --git a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
index 368887a5b..bdfa3b2d7 100644
--- a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
+++ b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp
@@ -332,8 +332,12 @@ ApiResponse<QVector<BrokerPosition>> TradierBroker::get_positions(const BrokerCr
pos.symbol = o.value("symbol").toString();
pos.exchange = "US";
pos.quantity = qty;
+ // avg_price = cost_basis / qty. For options this reflects the 100× contract
+ // multiplier (cost_basis is the full notional); we do NOT un-bake it here.
pos.avg_price = (qty != 0) ? o.value("cost_basis").toDouble() / qty : 0.0;
pos.side = qty > 0 ? "LONG" : "SHORT";
+ // TODO: hydrate LTP for current_value/pnl — the positions endpoint carries no
+ // price, so ltp/pnl/pnl_pct stay 0 (do not fabricate prices).
positions.append(pos);
}
@@ -374,8 +378,14 @@ ApiResponse<QVector<BrokerHolding>> TradierBroker::get_holdings(const BrokerCred
h.symbol = o.value("symbol").toString();
h.exchange = "US";
h.quantity = qty;
+ // avg_price = cost_basis / qty. For options this reflects the 100× contract
+ // multiplier (cost_basis is the full notional); we do NOT un-bake it here.
h.avg_price = (qty > 0) ? o.value("cost_basis").toDouble() / qty : 0.0;
- h.invested_value = o.value("cost_basis").toDouble();
+ // Prefer the API cost_basis; fall back to qty*avg_price when it's absent.
+ const double cost_basis = o.value("cost_basis").toDouble();
+ h.invested_value = (cost_basis != 0.0) ? cost_basis : h.quantity * h.avg_price;
+ // TODO: hydrate LTP for current_value/pnl — the positions endpoint carries no
+ // price, so ltp/current_value/pnl/pnl_pct stay 0 (do not fabricate prices).
holdings.append(h);
}
diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
index 4aabf57da..bb773073d 100644
--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
@@ -323,13 +323,21 @@ ApiResponse<QVector<BrokerHolding>> ZerodhaBroker::get_holdings(const BrokerCred
BrokerHolding hold;
hold.symbol = h.value("tradingsymbol").toString();
hold.exchange = h.value("exchange").toString();
- hold.quantity = h.value("quantity").toDouble();
+ // Total holding = settled (T+2) demat `quantity` + `t1_quantity` (bought,
+ // not yet settled). Using only `quantity` under-counts a stock bought in the
+ // last 1–2 sessions and makes qty/invested/value disagree with the Kite app.
+ hold.quantity = h.value("quantity").toDouble() + h.value("t1_quantity").toDouble();
hold.avg_price = h.value("average_price").toDouble();
hold.ltp = h.value("last_price").toDouble();
hold.invested_value = hold.quantity * hold.avg_price;
hold.current_value = hold.quantity * hold.ltp;
hold.pnl = h.value("pnl").toDouble();
hold.pnl_pct = hold.avg_price > 0 ? ((hold.ltp - hold.avg_price) / hold.avg_price) * 100.0 : 0.0;
+ // [TEMP DEBUG] Dump the full raw Zerodha holding object so we can diagnose the
+ // average_price mismatch between the Kite app and the terminal. Remove after diagnosis.
+ LOG_INFO("Zerodha", QString("HOLDINGS_RAW %1: %2")
+ .arg(hold.symbol,
+ QString::fromUtf8(QJsonDocument(h).toJson(QJsonDocument::Compact))));
holdings.append(hold);
}
return {true, holdings, "", ts};
diff --git a/fincept-qt/src/trading/replication/PortfolioReplicationService.cpp b/fincept-qt/src/trading/replication/PortfolioReplicationService.cpp
index 9348efec1..7e2e3e5ea 100644
--- a/fincept-qt/src/trading/replication/PortfolioReplicationService.cpp
+++ b/fincept-qt/src/trading/replication/PortfolioReplicationService.cpp
@@ -3,6 +3,8 @@
#include "trading/PaperTrading.h"
#include "trading/instruments/InstrumentService.h"
+#include <QSet>
+
#include <cmath>
namespace fincept::trading::replication {
@@ -151,12 +153,30 @@ SymbolResolver make_instrument_resolver(const QString& source_broker_id,
ReplicationResult execute_plan(const ReplicationPlan& plan) {
ReplicationResult res;
+
+ // Idempotency + no-close guard. Replication must ESTABLISH positions in the
+ // target — it must never trade AGAINST an existing one. Routing a sell (or a
+ // re-imported symbol) through the normal fill engine takes its close-netting
+ // leg and books phantom REALIZED P&L (e.g. a source short selling into a just-
+ // bought long), and re-running would double exposure. So we skip any symbol the
+ // target already holds. To intentionally re-replicate, clear the paper account
+ // first. (Matched on the broker-native/normalised symbol the order will use.)
+ QSet<QString> already_held;
+ for (const auto& p : pt_get_positions(plan.target_paper_portfolio_id))
+ already_held.insert(p.symbol.toUpper());
+
for (const auto& po : plan.orders) {
if (!po.included) {
++res.skipped;
res.rows.push_back({po.norm_symbol, false, po.warning.isEmpty() ? QStringLiteral("skipped") : po.warning});
continue;
}
+ if (already_held.contains(po.norm_symbol.toUpper())) {
+ ++res.skipped;
+ res.rows.push_back({po.norm_symbol, false,
+ QStringLiteral("already in target — skipped (clear paper account to re-replicate)")});
+ continue;
+ }
try {
std::optional<double> price_opt;
if (po.est_price > 0)
@@ -165,6 +185,7 @@ ReplicationResult execute_plan(const ReplicationPlan& plan) {
QStringLiteral("market"), po.quantity, price_opt, std::nullopt,
/*reduce_only=*/false, po.exchange, po.product);
pt_fill_order(ord.id, po.est_price);
+ already_held.insert(po.norm_symbol.toUpper()); // a later same-symbol leg must not net against this
++res.placed;
res.rows.push_back({po.norm_symbol, true, QString()});
} catch (const std::exception& e) {
diff --git a/fincept-qt/src/ui/navigation/StatusBar.cpp b/fincept-qt/src/ui/navigation/StatusBar.cpp
index 82c31c26a..f57ab3f87 100644
--- a/fincept-qt/src/ui/navigation/StatusBar.cpp
+++ b/fincept-qt/src/ui/navigation/StatusBar.cpp
@@ -25,7 +25,7 @@ StatusBar::StatusBar(QWidget* parent) : QWidget(parent) {
return l;
};
- hl->addWidget(mk("v4.0.3", "sbVersion"));
+ hl->addWidget(mk("v4.1.0", "sbVersion"));
hl->addWidget(mk(" | ", "sbSep"));
const char* feeds[] = {"EQ", "FX", "CM", "FI", "CR"};
for (auto& f : feeds) {