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.

Algo Tab Update

tilakpatel22fa7f840fb71b
diff --git a/.github/workflows/build-cpp.yml b/.github/workflows/build-cpp.yml
index 6f1791522..ddba67c2c 100644
--- a/.github/workflows/build-cpp.yml
+++ b/.github/workflows/build-cpp.yml
@@ -148,6 +148,11 @@ jobs:
set-env: false
dir: "${{ runner.temp }}/qt-host"
+ # ---- yt-dlp (bundled for dashboard video playback) ----
+ - name: Install yt-dlp
+ shell: bash
+ run: pip install yt-dlp
+
# ---- Configure CMake ----
- name: Configure CMake (Linux)
if: runner.os == 'Linux'
@@ -157,6 +162,7 @@ jobs:
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON \
${{ matrix.cmake_extra }}
- name: Configure CMake (Windows x64 / macOS x64 / macOS arm64)
@@ -172,6 +178,7 @@ jobs:
-DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} \
-DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
${OPENSSL_ARG} \
+ -DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON \
${{ runner.os == 'macOS' && '-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache' || '' }} \
${{ matrix.cmake_extra }}
@@ -191,6 +198,7 @@ jobs:
-DQT_HOST_PATH="${HOST_QT}" \
-T ClangCL \
${OPENSSL_ARG} \
+ -DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON \
${{ matrix.cmake_extra }}
# ---- Build ----
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 6e2e5dbd3..f55250975 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -67,6 +67,11 @@ jobs:
echo "QT_IFW_DIR=${IFW_DIR}" >> "$GITHUB_ENV"
echo "PATH=${IFW_DIR}/bin:${PATH}" >> "$GITHUB_ENV"
+ # ── yt-dlp (bundled for dashboard video playback) ────────────────────
+ - name: Install yt-dlp
+ shell: bash
+ run: pip install yt-dlp
+
# ── Configure + Build ─────────────────────────────────────────────────
- name: Configure CMake
shell: bash
@@ -77,7 +82,8 @@ jobs:
-DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
-DOPENSSL_ROOT_DIR="${OPENSSL_ROOT_DIR}" \
-DDEPLOY_QT=ON \
- -DFINCEPT_BUILD_INSTALLER=ON
+ -DFINCEPT_BUILD_INSTALLER=ON \
+ -DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON
- name: Build
shell: bash
@@ -294,6 +300,10 @@ jobs:
cache: true
cache-key-prefix: qt-linux-x64-release
+ # ── yt-dlp (bundled for dashboard video playback) ────────────────────
+ - name: Install yt-dlp
+ run: pip install yt-dlp
+
# ── Configure + Build ─────────────────────────────────────────────────
# No FINCEPT_BUILD_INSTALLER / no QtIFW on Linux — we ship an AppImage
# instead (see "Build AppImage" step below).
@@ -305,7 +315,8 @@ jobs:
-DCMAKE_PREFIX_PATH="${QT_ROOT_DIR}" \
-DOPENSSL_ROOT_DIR=/usr \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
- -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON
- name: Build
working-directory: fincept-qt
@@ -493,6 +504,93 @@ jobs:
zsyncmake "build/${OUTPUT}" -o "build/${OUTPUT}.zsync" || true
fi
+ # ── Build .deb package ────────────────────────────────────────────────
+ - name: Build .deb package
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ VERSION=$(grep -Po 'project\(FinceptTerminal VERSION \K[0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt)
+ DEB_NAME="fincept-terminal_${VERSION}_amd64"
+ DEB_ROOT="build/${DEB_NAME}"
+
+ mkdir -p "${DEB_ROOT}/DEBIAN"
+ mkdir -p "${DEB_ROOT}/usr"
+
+ cmake --install build --prefix "${DEB_ROOT}/usr"
+
+ cat > "${DEB_ROOT}/DEBIAN/control" <<EOF
+ Package: fincept-terminal
+ Version: ${VERSION}
+ Section: finance
+ Priority: optional
+ Architecture: amd64
+ Depends: libgl1, libxcb-cursor0, libxkbcommon0, libfontconfig1, libfreetype6, libdbus-1-3
+ Maintainer: Fincept Corporation <[email protected]>
+ Homepage: https://github.com/Fincept-Corporation/FinceptTerminal
+ Description: Professional financial intelligence terminal
+ Native C++20 desktop terminal with real-time market data, AI analytics,
+ multi-broker trading, portfolio management, and 1300+ Python scripts.
+ EOF
+ # Remove leading whitespace from control file (YAML heredoc indent)
+ sed -i 's/^ //' "${DEB_ROOT}/DEBIAN/control"
+
+ dpkg-deb --build --root-owner-group "${DEB_ROOT}"
+ mv "build/${DEB_NAME}.deb" "build/FinceptTerminal-${VERSION}-linux-x64.deb"
+ echo "Built: FinceptTerminal-${VERSION}-linux-x64.deb ($(du -sh "build/FinceptTerminal-${VERSION}-linux-x64.deb" | cut -f1))"
+
+ # ── Build .rpm package ────────────────────────────────────────────────
+ - name: Build .rpm package
+ working-directory: fincept-qt
+ run: |
+ set -euo pipefail
+ sudo apt-get install -y rpm -qq
+
+ VERSION=$(grep -Po 'project\(FinceptTerminal VERSION \K[0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt)
+ RPM_ROOT="build/rpm-root"
+
+ mkdir -p "${RPM_ROOT}/usr"
+ cmake --install build --prefix "${RPM_ROOT}/usr"
+
+ mkdir -p ~/rpmbuild/{SPECS,BUILDROOT}
+
+ cat > ~/rpmbuild/SPECS/fincept-terminal.spec <<EOF
+ Name: fincept-terminal
+ Version: ${VERSION}
+ Release: 1
+ Summary: Professional financial intelligence terminal
+ License: AGPL-3.0-or-later
+ URL: https://github.com/Fincept-Corporation/FinceptTerminal
+ AutoReqProv: no
+
+ %description
+ Native C++20 desktop terminal with real-time market data, AI analytics,
+ multi-broker trading, portfolio management, and 1300+ Python scripts.
+
+ %install
+ cp -a ${PWD}/${RPM_ROOT}/* %{buildroot}/
+
+ %files
+ /usr/bin/FinceptTerminal
+ /usr/bin/yt-dlp
+ /usr/share/fincept-terminal/
+ /usr/share/applications/fincept-terminal.desktop
+ /usr/share/metainfo/fincept-terminal.appdata.xml
+ /usr/share/icons/hicolor/256x256/apps/fincept-terminal.png
+ EOF
+ # Remove leading whitespace from spec file
+ sed -i 's/^ //' ~/rpmbuild/SPECS/fincept-terminal.spec
+
+ rpmbuild -bb ~/rpmbuild/SPECS/fincept-terminal.spec \
+ --buildroot "${PWD}/${RPM_ROOT}" \
+ --define "_rpmdir ${PWD}/build"
+
+ mv build/x86_64/fincept-terminal-${VERSION}-1.x86_64.rpm \
+ "build/FinceptTerminal-${VERSION}-linux-x64.rpm" 2>/dev/null || \
+ mv build/*/fincept-terminal-*.rpm \
+ "build/FinceptTerminal-${VERSION}-linux-x64.rpm"
+
+ echo "Built: FinceptTerminal-${VERSION}-linux-x64.rpm ($(du -sh "build/FinceptTerminal-${VERSION}-linux-x64.rpm" | cut -f1))"
+
# ── Upload ────────────────────────────────────────────────────────────
# Version-stamped filename so update-manifest regex picks it up.
- name: Upload artifact
@@ -502,6 +600,8 @@ jobs:
path: |
fincept-qt/build/FinceptTerminal-*-linux-x64-setup.run
fincept-qt/build/FinceptTerminal-*-linux-x64-setup.run.zsync
+ fincept-qt/build/FinceptTerminal-*-linux-x64.deb
+ fincept-qt/build/FinceptTerminal-*-linux-x64.rpm
retention-days: 30
# ═════════════════════════════════════════════════════════════════════════════
@@ -572,6 +672,10 @@ jobs:
echo "WARNING: No source icon — app will use generic icon"
fi
+ # ── yt-dlp (bundled for dashboard video playback) ────────────────────
+ - name: Install yt-dlp
+ run: pip install yt-dlp
+
# ── Configure + Build ─────────────────────────────────────────────────
# No FINCEPT_BUILD_INSTALLER on macOS — we ship a DMG built from the
# post-processed bundle (see "Generate Installer (DMG)" step below).
@@ -584,7 +688,8 @@ jobs:
-DCMAKE_OSX_ARCHITECTURES=arm64 \
-DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
- -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
+ -DFINCEPT_REQUIRE_BUNDLED_YTDLP=ON
- name: Build
working-directory: fincept-qt
@@ -1549,15 +1654,17 @@ jobs:
### Downloads
- | Platform | File | Notes |
- |----------|------|-------|
- | **Windows x64** | `FinceptTerminal-*-setup*.exe` | Run installer → `FinceptTerminal.exe` |
- | **Linux x64** | `FinceptTerminal-*.run` | `chmod +x` → run installer |
+ | Platform | File | Install |
+ |----------|------|---------|
+ | **Windows x64** | `FinceptTerminal-*-setup*.exe` | Run installer |
+ | **Linux (Debian/Ubuntu)** | `FinceptTerminal-*-linux-x64.deb` | `sudo dpkg -i *.deb` |
+ | **Linux (Fedora/RHEL)** | `FinceptTerminal-*-linux-x64.rpm` | `sudo dnf install *.rpm` |
+ | **Linux (portable)** | `FinceptTerminal-*-linux-x64-setup.run` | `chmod +x` then run |
| **macOS Apple Silicon** | `FinceptTerminal-*.dmg` or setup | Open DMG → drag to Applications |
### Requirements
- Windows 10/11 x64
- - Ubuntu 20.04+ / Debian 11+
+ - Ubuntu 20.04+ / Debian 11+ / Fedora 36+ / RHEL 9+
- macOS 13+ (Apple Silicon)
See the [README](https://github.com/Fincept-Corporation/FinceptTerminal#readme) for full installation instructions.
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 5e4cec8e6..f8aa0a20b 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -406,6 +406,12 @@ if(Qt6TextToSpeech_FOUND)
set(HAS_TTS TRUE)
endif()
+# Optional: WebEngineWidgets + WebChannel (KLineChart / JS-based charting)
+find_package(Qt6 ${_FINCEPT_QT_VER_ARGS} QUIET COMPONENTS WebEngineWidgets WebChannel)
+if(Qt6WebEngineWidgets_FOUND AND Qt6WebChannel_FOUND)
+ set(HAS_WEBENGINE TRUE)
+endif()
+
# Optional: WaylandClient — required to deploy Qt Wayland QPA plugin on Linux.
# Without this plugin, apps fall back to XWayland (often visually broken on
# fractional-scale Fedora/Ubuntu sessions) or fail outright on pure-Wayland
@@ -971,6 +977,7 @@ set(TRADING_SOURCES
src/trading/brokers/shoonya/ShoonyaBroker.cpp
# Global brokers
src/trading/brokers/alpaca/AlpacaBroker.cpp
+ src/trading/brokers/alpaca/AlpacaWebSocket.cpp
src/trading/brokers/ibkr/IBKRBroker.cpp
src/trading/brokers/tradier/TradierBroker.cpp
src/trading/brokers/saxo/SaxoBankBroker.cpp
@@ -985,6 +992,20 @@ set(TRADING_SOURCES
src/trading/instruments/SymbolResolver.cpp
)
+# Algo Engine (native C++ trading engine — replaces Python algo runner)
+set(ALGO_ENGINE_SOURCES
+ src/algo_engine/AlgoEngineTypes.cpp
+ src/algo_engine/CandleAggregator.cpp
+ src/algo_engine/IndicatorEngine.cpp
+ src/algo_engine/ConditionEvaluator.cpp
+ src/algo_engine/PositionManager.cpp
+ src/algo_engine/DeploymentRunner.cpp
+ src/algo_engine/AlgoEngine.cpp
+ src/algo_engine/AlgoEngineProducer.cpp
+ src/algo_engine/AlgoScanner.cpp
+ src/algo_engine/CandleDataFetcher.cpp
+)
+
# Services
set(SERVICE_SOURCES
src/services/akshare/AkShareService.cpp
@@ -1184,6 +1205,19 @@ set(UI_SOURCES
src/ui/widgets/LanguageSwitcher.cpp
src/ui/tables/DataTable.cpp
src/ui/charts/ChartFactory.cpp
+ src/ui/charts/ChartIndicators.cpp
+ src/ui/charts/OverlayLayer.cpp
+ src/ui/charts/SeriesLayer.cpp
+ src/ui/charts/HorizontalLineLayer.cpp
+ src/ui/charts/ChartOverlayManager.cpp
+ src/ui/charts/IndicatorPicker.cpp
+ src/ui/charts/IndicatorParamDialog.cpp
+ src/ui/charts/layers/EmaLayer.cpp
+ src/ui/charts/layers/VwapLayer.cpp
+ src/ui/charts/layers/BollingerLayer.cpp
+ src/ui/charts/layers/SupportResistanceLayer.cpp
+ src/ui/charts/layers/PivotLayer.cpp
+ src/ui/charts/KLineChartWidget.cpp
src/ui/navigation/NavigationBar.cpp
src/ui/navigation/FKeyBar.cpp
src/ui/navigation/StatusBar.cpp
@@ -1210,6 +1244,13 @@ set(UI_SOURCES
src/ui/widgets/NotifToast.cpp
src/ui/widgets/NotifBell.cpp
src/ui/widgets/NotifPanel.cpp
+
+ # Algo Trading visual strategy builder widgets
+ src/ui/widgets/algo/ConditionBlock.cpp
+ src/ui/widgets/algo/LogicConnectorWidget.cpp
+ src/ui/widgets/algo/ConditionSection.cpp
+ src/ui/widgets/algo/RiskManagementPanel.cpp
+ src/ui/widgets/algo/SymbolSearchCombo.cpp
)
# Screens
@@ -1514,6 +1555,7 @@ set(SCREEN_SOURCES
src/screens/algo_trading/StrategyListPanel.cpp
src/screens/algo_trading/ScannerPanel.cpp
src/screens/algo_trading/DeploymentDashboard.cpp
+ src/screens/algo_trading/AlgoDeployDialog.cpp
# Data Mapping (partial-class split; see DataMappingScreen.cpp header).
src/screens/data_mapping/DataMappingScreen.cpp
@@ -1773,6 +1815,7 @@ set_source_files_properties(
src/screens/algo_trading/ScannerPanel.cpp
src/screens/algo_trading/StrategyBuilderPanel.cpp
src/screens/algo_trading/StrategyListPanel.cpp
+ src/screens/algo_trading/AlgoDeployDialog.cpp
src/screens/alpha_arena/AlphaArenaScreen.cpp
src/screens/alpha_arena/panels/LeaderboardPanel.cpp
src/screens/alpha_arena/panels/ModelChatPanel.cpp
@@ -2189,6 +2232,7 @@ set_source_files_properties(
src/trading/brokers/motilal/MotilalBroker.cpp
src/trading/brokers/shoonya/ShoonyaBroker.cpp
src/trading/brokers/alpaca/AlpacaBroker.cpp
+ src/trading/brokers/alpaca/AlpacaWebSocket.cpp
src/trading/brokers/ibkr/IBKRBroker.cpp
src/trading/brokers/tradier/TradierBroker.cpp
src/trading/brokers/saxo/SaxoBankBroker.cpp
@@ -2309,6 +2353,7 @@ set_source_files_properties(
src/trading/brokers/motilal/MotilalBroker.cpp
src/trading/brokers/shoonya/ShoonyaBroker.cpp
src/trading/brokers/alpaca/AlpacaBroker.cpp
+ src/trading/brokers/alpaca/AlpacaWebSocket.cpp
src/trading/brokers/ibkr/IBKRBroker.cpp
src/trading/brokers/tradier/TradierBroker.cpp
src/trading/brokers/saxo/SaxoBankBroker.cpp
@@ -2384,6 +2429,7 @@ add_executable(FinceptTerminal ${_FINCEPT_EXE_FLAGS}
${AI_CHAT_SCREEN_SOURCES}
${MCP_SOURCES}
${TRADING_SOURCES}
+ ${ALGO_ENGINE_SOURCES}
${SERVICE_SOURCES}
${UI_SOURCES}
${SCREEN_SOURCES}
@@ -2803,6 +2849,11 @@ if(HAS_TTS)
target_compile_definitions(FinceptTerminal PRIVATE HAS_QT_TTS)
endif()
+if(HAS_WEBENGINE)
+ target_link_libraries(FinceptTerminal PRIVATE Qt6::WebEngineWidgets Qt6::WebChannel)
+ target_compile_definitions(FinceptTerminal PRIVATE HAS_QT_WEBENGINE)
+endif()
+
# ── Copy qgeoview DLL next to the exe so it's found at runtime ────────────────
if(WIN32)
add_custom_command(TARGET FinceptTerminal POST_BUILD
@@ -2908,6 +2959,16 @@ add_custom_command(TARGET FinceptTerminal POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_CURRENT_SOURCE_DIR}/resources/wallet/vendor"
"$<TARGET_FILE_DIR:FinceptTerminal>/resources/wallet/vendor"
+ COMMAND ${CMAKE_COMMAND} -E make_directory
+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/charts"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/charts/klinechart.html"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/charts/klinechart.html"
+ COMMAND ${CMAKE_COMMAND} -E make_directory
+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/charts/vendor"
+ COMMAND ${CMAKE_COMMAND} -E copy_directory
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/charts/vendor"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/charts/vendor"
COMMENT "Copying requirements files to build output..."
)
diff --git a/fincept-qt/resources/charts/klinechart.html b/fincept-qt/resources/charts/klinechart.html
new file mode 100644
index 000000000..a38eeec07
--- /dev/null
+++ b/fincept-qt/resources/charts/klinechart.html
@@ -0,0 +1,318 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<meta http-equiv="Content-Security-Policy"
+ content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';">
+<title>KLineChart</title>
+<script src="vendor/klinecharts.min.js"></script>
+<style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ html, body { width: 100%; height: 100%; overflow: hidden; background: #080808; font-family: Consolas, 'Courier New', monospace; }
+ #app { display: flex; flex-direction: column; height: 100%; }
+ #toolbar { display: flex; align-items: center; gap: 2px; padding: 3px 6px; background: #0a0a0a; border-bottom: 1px solid #1a1a1a; flex-shrink: 0; flex-wrap: wrap; }
+ #chart { flex: 1; min-height: 0; }
+ .tb-group { display: flex; align-items: center; gap: 1px; margin-right: 6px; }
+ .tb-sep { width: 1px; height: 18px; background: #222; margin: 0 4px; }
+ .tb-btn { background: transparent; border: 1px solid transparent; color: #808080; font: 10px Consolas; padding: 2px 6px; cursor: pointer; border-radius: 2px; white-space: nowrap; }
+ .tb-btn:hover { background: #161616; color: #e5e5e5; border-color: #333; }
+ .tb-btn.active { background: #1a1a1a; color: #d97706; border-color: #d97706; }
+ .tb-dropdown { position: relative; display: inline-block; }
+ .tb-dropdown-content { display: none; position: absolute; top: 100%; left: 0; background: #111; border: 1px solid #222; min-width: 140px; z-index: 100; max-height: 300px; overflow-y: auto; }
+ .tb-dropdown:hover .tb-dropdown-content { display: block; }
+ .tb-dropdown-content .tb-btn { display: block; width: 100%; text-align: left; border: none; padding: 4px 10px; border-radius: 0; }
+ .tb-dropdown-content .tb-btn:hover { background: #1a1a1a; }
+ .tb-dropdown-content .section { color: #d97706; font-size: 9px; padding: 6px 10px 2px; font-weight: 700; letter-spacing: 0.5px; }
+ #debug { position: fixed; bottom: 2px; left: 4px; color: #525252; font: 9px Consolas; z-index: 999; pointer-events: none; }
+</style>
+</head>
+<body>
+<div id="app">
+ <div id="toolbar">
+ <!-- Chart Type -->
+ <div class="tb-group">
+ <div class="tb-dropdown">
+ <button class="tb-btn" id="chartTypeBtn">Candle ▾</button>
+ <div class="tb-dropdown-content">
+ <button class="tb-btn" onclick="setChartType('candle_solid')">Candle Solid</button>
+ <button class="tb-btn" onclick="setChartType('candle_stroke')">Candle Stroke</button>
+ <button class="tb-btn" onclick="setChartType('candle_up_stroke')">Candle Up Stroke</button>
+ <button class="tb-btn" onclick="setChartType('ohlc')">OHLC</button>
+ <button class="tb-btn" onclick="setChartType('area')">Area</button>
+ </div>
+ </div>
+ </div>
+ <div class="tb-sep"></div>
+
+ <!-- Indicators -->
+ <div class="tb-group">
+ <div class="tb-dropdown">
+ <button class="tb-btn">Indicators ▾</button>
+ <div class="tb-dropdown-content">
+ <div class="section">OVERLAY (on chart)</div>
+ <button class="tb-btn" onclick="toggleIndicator('MA','candle_pane')">MA</button>
+ <button class="tb-btn" onclick="toggleIndicator('EMA','candle_pane')">EMA</button>
+ <button class="tb-btn" onclick="toggleIndicator('SMA','candle_pane')">SMA</button>
+ <button class="tb-btn" onclick="toggleIndicator('BOLL','candle_pane')">Bollinger</button>
+ <button class="tb-btn" onclick="toggleIndicator('SAR','candle_pane')">Parabolic SAR</button>
+
+ <div class="section">SUB-PANEL</div>
+ <button class="tb-btn" onclick="toggleIndicator('VOL')">Volume</button>
+ <button class="tb-btn" onclick="toggleIndicator('MACD')">MACD</button>
+ <button class="tb-btn" onclick="toggleIndicator('RSI')">RSI</button>
+ <button class="tb-btn" onclick="toggleIndicator('KDJ')">KDJ</button>
+ <button class="tb-btn" onclick="toggleIndicator('WR')">Williams %R</button>
+ <button class="tb-btn" onclick="toggleIndicator('OBV')">OBV</button>
+ <button class="tb-btn" onclick="toggleIndicator('DMI')">DMI</button>
+ <button class="tb-btn" onclick="toggleIndicator('CR')">CR</button>
+ <button class="tb-btn" onclick="toggleIndicator('PSY')">PSY</button>
+ <button class="tb-btn" onclick="toggleIndicator('DMA')">DMA</button>
+ <button class="tb-btn" onclick="toggleIndicator('TRIX')">TRIX</button>
+ <button class="tb-btn" onclick="toggleIndicator('BRAR')">BRAR</button>
+ <button class="tb-btn" onclick="toggleIndicator('VR')">VR</button>
+ <button class="tb-btn" onclick="toggleIndicator('EMV')">EMV</button>
+ <button class="tb-btn" onclick="toggleIndicator('AO')">Awesome Osc</button>
+ <button class="tb-btn" onclick="toggleIndicator('ROC')">ROC</button>
+ <button class="tb-btn" onclick="toggleIndicator('PVT')">PVT</button>
+ <button class="tb-btn" onclick="toggleIndicator('AVP')">AVP</button>
+ </div>
+ </div>
+ </div>
+ <div class="tb-sep"></div>
+
+ <!-- Drawing Tools -->
+ <div class="tb-group">
+ <div class="tb-dropdown">
+ <button class="tb-btn">Drawing ▾</button>
+ <div class="tb-dropdown-content">
+ <div class="section">LINES</div>
+ <button class="tb-btn" onclick="addOverlay('horizontalStraightLine')">Horizontal Line</button>
+ <button class="tb-btn" onclick="addOverlay('verticalStraightLine')">Vertical Line</button>
+ <button class="tb-btn" onclick="addOverlay('straightLine')">Trend Line</button>
+ <button class="tb-btn" onclick="addOverlay('rayLine')">Ray</button>
+ <button class="tb-btn" onclick="addOverlay('segment')">Segment</button>
+ <button class="tb-btn" onclick="addOverlay('horizontalRayLine')">Horizontal Ray</button>
+ <button class="tb-btn" onclick="addOverlay('horizontalSegment')">Horizontal Segment</button>
+ <button class="tb-btn" onclick="addOverlay('priceChannelLine')">Price Channel</button>
+ <button class="tb-btn" onclick="addOverlay('parallelStraightLine')">Parallel Lines</button>
+
+ <div class="section">FIBONACCI</div>
+ <button class="tb-btn" onclick="addOverlay('fibonacciLine')">Fibonacci Retrace</button>
+
+ <div class="section">SHAPES</div>
+ <button class="tb-btn" onclick="addOverlay('rect')">Rectangle</button>
+ <button class="tb-btn" onclick="addOverlay('circle')">Circle</button>
+ <button class="tb-btn" onclick="addOverlay('triangle')">Triangle</button>
+
+ <div class="section">ANNOTATIONS</div>
+ <button class="tb-btn" onclick="addOverlay('simpleAnnotation')">Annotation</button>
+ <button class="tb-btn" onclick="addOverlay('simpleTag')">Tag</button>
+ </div>
+ </div>
+ </div>
+ <div class="tb-sep"></div>
+
+ <!-- Quick Actions -->
+ <div class="tb-group">
+ <button class="tb-btn" onclick="toggleIndicator('MA','candle_pane')" title="Moving Average">MA</button>
+ <button class="tb-btn" onclick="toggleIndicator('VOL')" title="Volume">VOL</button>
+ <button class="tb-btn" onclick="toggleIndicator('MACD')" title="MACD">MACD</button>
+ <button class="tb-btn" onclick="toggleIndicator('RSI')" title="RSI">RSI</button>
+ <button class="tb-btn" onclick="toggleIndicator('BOLL','candle_pane')" title="Bollinger Bands">BOLL</button>
+ </div>
+ <div class="tb-sep"></div>
+
+ <!-- Utilities -->
+ <div class="tb-group">
+ <button class="tb-btn" onclick="removeAllOverlays()" title="Clear drawings">Clear Draw</button>
+ <button class="tb-btn" onclick="removeAllIndicators()" title="Clear indicators">Clear Ind</button>
+ <button class="tb-btn" onclick="chart.zoomAtCoordinate(0.8)" title="Zoom In">+</button>
+ <button class="tb-btn" onclick="chart.zoomAtCoordinate(1.2)" title="Zoom Out">−</button>
+ </div>
+ </div>
+
+ <div id="chart"></div>
+</div>
+<div id="debug"></div>
+
+<script>
+(function() {
+ 'use strict';
+
+ var dbg = document.getElementById('debug');
+ function log(msg) { dbg.textContent = msg; }
+
+ var chart;
+ try {
+ chart = klinecharts.init('chart', {
+ styles: {
+ grid: {
+ show: true,
+ horizontal: { show: true, size: 1, color: '#1a1a1a', style: 'dashed' },
+ vertical: { show: true, size: 1, color: '#1a1a1a', style: 'dashed' }
+ },
+ candle: {
+ type: 'candle_solid',
+ bar: {
+ upColor: '#16a34a', downColor: '#dc2626', noChangeColor: '#888888',
+ upBorderColor: '#16a34a', downBorderColor: '#dc2626', noChangeBorderColor: '#888888',
+ upWickColor: '#16a34a', downWickColor: '#dc2626', noChangeWickColor: '#888888'
+ },
+ priceMark: {
+ show: true,
+ high: { show: true, color: '#e5e5e5', textSize: 10 },
+ low: { show: true, color: '#e5e5e5', textSize: 10 },
+ last: {
+ show: true, upColor: '#16a34a', downColor: '#dc2626', noChangeColor: '#888888',
+ line: { show: true, style: 'dashed', size: 1 },
+ text: { show: true, size: 10, paddingLeft: 4, paddingRight: 4, paddingTop: 2, paddingBottom: 2, color: '#fff' }
+ }
+ },
+ tooltip: {
+ showRule: 'always', showType: 'standard',
+ text: { size: 11, color: '#e5e5e5', family: 'Consolas, Courier New, monospace', weight: 'normal' }
+ }
+ },
+ indicator: {
+ ohlc: { upColor: '#16a34a', downColor: '#dc2626', noChangeColor: '#888888' },
+ lastValueMark: { show: true, text: { color: '#fff', size: 10 } },
+ tooltip: { showRule: 'always', text: { size: 11, color: '#e5e5e5', family: 'Consolas, monospace' } }
+ },
+ xAxis: {
+ show: true,
+ axisLine: { show: true, color: '#1a1a1a', size: 1 },
+ tickLine: { show: true, color: '#1a1a1a', size: 1 },
+ tickText: { show: true, color: '#808080', size: 10, family: 'Consolas, Courier New, monospace' }
+ },
+ yAxis: {
+ show: true, position: 'right',
+ axisLine: { show: true, color: '#1a1a1a', size: 1 },
+ tickLine: { show: true, color: '#1a1a1a', size: 1 },
+ tickText: { show: true, color: '#808080', size: 10, family: 'Consolas, Courier New, monospace' }
+ },
+ separator: { size: 2, color: '#1a1a1a', activeBackgroundColor: '#333' },
+ crosshair: {
+ show: true,
+ horizontal: {
+ show: true,
+ line: { show: true, style: 'dashed', size: 1, color: '#d97706' },
+ text: { show: true, color: '#080808', size: 10, family: 'Consolas, monospace',
+ backgroundColor: '#d97706', paddingLeft: 4, paddingRight: 4, paddingTop: 2, paddingBottom: 2 }
+ },
+ vertical: {
+ show: true,
+ line: { show: true, style: 'dashed', size: 1, color: '#d97706' },
+ text: { show: true, color: '#080808', size: 10, family: 'Consolas, monospace',
+ backgroundColor: '#d97706', paddingLeft: 4, paddingRight: 4, paddingTop: 2, paddingBottom: 2 }
+ }
+ },
+ overlay: {
+ point: { color: '#d97706', borderColor: '#d97706', activeColor: '#d97706', activeBorderColor: '#d97706' },
+ line: { color: '#d97706', size: 1 },
+ rect: { color: 'rgba(217,119,6,0.1)', borderColor: '#d97706', borderSize: 1 },
+ text: { color: '#e5e5e5', size: 11, family: 'Consolas, monospace' }
+ }
+ }
+ });
+ window.chart = chart;
+ log('ready');
+ } catch (e) {
+ log('INIT ERROR: ' + e.message);
+ return;
+ }
+
+ // Default: add volume sub-panel
+ chart.createIndicator('VOL');
+
+ window.addEventListener('resize', function() { chart.resize(); });
+
+ // --- Track active indicators for toggle behavior ---
+ var activeIndicators = {};
+
+ window.toggleIndicator = function(name, paneId) {
+ var key = name + (paneId || '');
+ if (activeIndicators[key]) {
+ chart.removeIndicator(name, paneId || activeIndicators[key]);
+ delete activeIndicators[key];
+ } else {
+ var id;
+ if (paneId === 'candle_pane') {
+ id = chart.createIndicator(name, { isStack: true, pane: { id: 'candle_pane' } });
+ } else {
+ id = chart.createIndicator(name);
+ }
+ activeIndicators[key] = id || paneId || true;
+ }
+ };
+
+ window.addOverlay = function(name) {
+ chart.createOverlay(name);
+ };
+
+ window.removeAllOverlays = function() {
+ chart.removeOverlay();
+ };
+
+ window.removeAllIndicators = function() {
+ var keys = Object.keys(activeIndicators);
+ for (var i = 0; i < keys.length; i++) {
+ var k = keys[i];
+ // Extract indicator name (remove pane suffix)
+ var name = k.replace('candle_pane', '');
+ chart.removeIndicator(name);
+ }
+ activeIndicators = {};
+ // Re-add volume
+ chart.createIndicator('VOL');
+ };
+
+ window.setChartType = function(type) {
+ chart.setStyles({ candle: { type: type } });
+ var labels = {
+ 'candle_solid': 'Candle', 'candle_stroke': 'Stroke', 'candle_up_stroke': 'Up Stroke',
+ 'ohlc': 'OHLC', 'area': 'Area'
+ };
+ document.getElementById('chartTypeBtn').textContent = (labels[type] || type) + ' ▾';
+ };
+
+ // --- API exposed to C++ via runJavaScript() ---
+
+ window.setCandles = function(data) {
+ try {
+ if (!Array.isArray(data) || data.length === 0) {
+ log('no data');
+ return;
+ }
+ chart.applyNewData(data);
+ log(data.length + ' bars loaded');
+ } catch (e) {
+ log('ERROR: ' + e.message);
+ }
+ };
+
+ window.updateCandle = function(candle) {
+ try { chart.updateData(candle); } catch (e) { log('update err: ' + e.message); }
+ };
+
+ window.addIndicator = function(name, paneId) {
+ try { window.toggleIndicator(name, paneId); } catch (e) { log('ind err: ' + e.message); }
+ };
+
+ window.removeIndicator = function(name, paneId) {
+ try { chart.removeIndicator(name, paneId); } catch (e) {}
+ };
+
+ window.clearChart = function() {
+ chart.clearData();
+ };
+
+ window.setTheme = function(styles) {
+ chart.setStyles(styles);
+ };
+
+ window._chartReady = true;
+})();
+</script>
+</body>
+</html>
diff --git a/fincept-qt/resources/charts/vendor/klinecharts.min.js b/fincept-qt/resources/charts/vendor/klinecharts.min.js
new file mode 100644
index 000000000..da9d9dec0
--- /dev/null
+++ b/fincept-qt/resources/charts/vendor/klinecharts.min.js
@@ -0,0 +1,7 @@
+/**
+ * @license
+ * KLineChart v9.8.10
+ * Copyright (c) 2019 lihu.
+ * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0
+ */
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).klinecharts={})}(this,(function(t){"use strict";var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])},e(t,i)};function i(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var n,o,r,a,s,l,c,u,h,d=function(){return d=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++)for(var o in e=arguments[i])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},d.apply(this,arguments)};function p(t,e,i,n){return new(i||(i=Promise))((function(o,r){function a(t){try{l(n.next(t))}catch(t){r(t)}}function s(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(a,s)}l((n=n.apply(t,e||[])).next())}))}function g(t,e){var i,n,o,r,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(s){return function(l){return function(s){if(i)throw new TypeError("Generator is already executing.");for(;r&&(r=0,s[0]&&(a=0)),a;)try{if(i=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],n=0}finally{i=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}}function v(t){var e="function"==typeof Symbol&&Symbol.iterator,i=e&&t[e],n=0;if(i)return i.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function f(t,e){var i="function"==typeof Symbol&&t[Symbol.iterator];if(!i)return t;var n,o,r=i.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=r.next()).done;)a.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return a}function y(t,e,i){if(i||2===arguments.length)for(var n,o=0,r=e.length;o<r;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError,t.LineType=void 0,(n=t.LineType||(t.LineType={})).Dashed="dashed",n.Solid="solid",t.PolygonType=void 0,(o=t.PolygonType||(t.PolygonType={})).Stroke="stroke",o.Fill="fill",o.StrokeFill="stroke_fill",t.TooltipShowRule=void 0,(r=t.TooltipShowRule||(t.TooltipShowRule={})).Always="always",r.FollowCross="follow_cross",r.None="none",t.TooltipShowType=void 0,(a=t.TooltipShowType||(t.TooltipShowType={})).Standard="standard",a.Rect="rect",t.TooltipIconPosition=void 0,(s=t.TooltipIconPosition||(t.TooltipIconPosition={})).Left="left",s.Middle="middle",s.Right="right",t.CandleTooltipRectPosition=void 0,(l=t.CandleTooltipRectPosition||(t.CandleTooltipRectPosition={})).Fixed="fixed",l.Pointer="pointer",t.CandleType=void 0,(c=t.CandleType||(t.CandleType={})).CandleSolid="candle_solid",c.CandleStroke="candle_stroke",c.CandleUpStroke="candle_up_stroke",c.CandleDownStroke="candle_down_stroke",c.Ohlc="ohlc",c.Area="area",t.YAxisPosition=void 0,(u=t.YAxisPosition||(t.YAxisPosition={})).Left="left",u.Right="right",t.YAxisType=void 0,(h=t.YAxisType||(t.YAxisType={})).Normal="normal",h.Percentage="percentage",h.Log="log";var m="#F92855",_="rgba(249, 40, 85, .7)",x="#2DC08E",S="rgba(45, 192, 142, .7)",C="#888888",b="#FFFFFF",T="#1677FF",w="#76808F",E="#DDDDDD";function I(t){return"rgba(22, 119, 255, ".concat(t,")")}function P(){function e(){return{show:!0,size:1,color:"#EDEDED",style:t.LineType.Dashed,dashedValue:[2,2]}}return{show:!0,horizontal:e(),vertical:e()}}function D(){return{show:!0,size:"auto",axisLine:{show:!0,color:E,size:1},tickText:{show:!0,color:w,size:12,family:"Helvetica Neue",weight:"normal",marginStart:4,marginEnd:4},tickLine:{show:!0,size:1,length:3,color:E}}}function M(){function e(){return{show:!0,line:{show:!0,style:t.LineType.Dashed,dashedValue:[4,2],size:1,color:w},text:{show:!0,style:t.PolygonType.Fill,color:b,size:12,family:"Helvetica Neue",weight:"normal",borderStyle:t.LineType.Solid,borderDashedValue:[2,2],borderSize:1,borderColor:w,borderRadius:2,paddingLeft:4,paddingRight:4,paddingTop:4,paddingBottom:4,backgroundColor:w}}}return{show:!0,horizontal:e(),vertical:e()}}function k(){var e=I(.35),i=I(.25);function n(){return{style:t.PolygonType.Fill,color:b,size:12,family:"Helvetica Neue",weight:"normal",borderStyle:t.LineType.Solid,borderDashedValue:[2,2],borderSize:1,borderRadius:2,borderColor:T,paddingLeft:4,paddingRight:4,paddingTop:4,paddingBottom:4,backgroundColor:T}}return{point:{color:T,borderColor:e,borderSize:1,radius:5,activeColor:T,activeBorderColor:e,activeBorderSize:3,activeRadius:5},line:{style:t.LineType.Solid,smooth:!1,color:T,size:1,dashedValue:[2,2]},rect:{style:t.PolygonType.Fill,color:i,borderColor:T,borderSize:1,borderRadius:0,borderStyle:t.LineType.Solid,borderDashedValue:[2,2]},polygon:{style:t.PolygonType.Fill,color:T,borderColor:T,borderSize:1,borderStyle:t.LineType.Solid,borderDashedValue:[2,2]},circle:{style:t.PolygonType.Fill,color:i,borderColor:T,borderSize:1,borderStyle:t.LineType.Solid,borderDashedValue:[2,2]},arc:{style:t.LineType.Solid,color:T,size:1,dashedValue:[2,2]},text:n(),rectText:n()}}function A(t,e){if(B(t)||B(e))for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){var n=t[i],o=e[i];B(o)&&B(n)?A(n,o):V(e[i])&&(t[i]=F(e[i]))}}function F(t){if(!B(t))return t;var e;for(var i in e=L(t)?[]:{},t)if(Object.prototype.hasOwnProperty.call(t,i)){var n=t[i];B(n)?e[i]=F(n):e[i]=n}return e}function L(t){return"[object Array]"===Object.prototype.toString.call(t)}function R(t){return"function"==typeof t}function B(t){return"object"==typeof t&&V(t)}function O(t){return"number"==typeof t&&!isNaN(t)}function V(t){return null!=t}function N(t){return"boolean"==typeof t}function W(t){return"string"==typeof t}var z,Y,H=/\\(\\)?/g,X=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g");function G(t,e,i){if(V(t)){var n=[];e.replace(X,(function(t){for(var e=[],i=1;i<arguments.length;i++)e[i-1]=arguments[i];var o=t;return V(e[1])?o=e[2].replace(H,"$1"):V(e[0])&&(o=e[0].trim()),n.push(o),""}));for(var o=t,r=0,a=n.length;V(o)&&r<a;)o=null==o?void 0:o[n[r++]];return V(o)?o:null!=i?i:"--"}return null!=i?i:"--"}function j(t,e,i){var n={};return t.formatToParts(new Date(e)).forEach((function(t){var e=t.type,i=t.value;switch(e){case"year":n.YYYY=i;break;case"month":n.MM=i;break;case"day":n.DD=i;break;case"hour":n.HH="24"===i?"00":i;break;case"minute":n.mm=i;break;case"second":n.ss=i}})),i.replace(/YYYY|MM|DD|HH|mm|ss/g,(function(t){return n[t]}))}function K(t,e){var i=+t;return O(i)?i.toFixed(null!=e?e:2):"".concat(t)}function Z(t){var e=+t;if(O(e)){if(e>1e9)return"".concat(+(e/1e9).toFixed(3),"B");if(e>1e6)return"".concat(+(e/1e6).toFixed(3),"M");if(e>1e3)return"".concat(+(e/1e3).toFixed(3),"K")}return"".concat(t)}function U(t,e){var i="".concat(t);if(0===e.length)return i;if(i.includes(".")){var n=i.split(".");return"".concat(n[0].replace(/(\d)(?=(\d{3})+$)/g,(function(t){return"".concat(t).concat(e)})),".").concat(n[1])}return i.replace(/(\d)(?=(\d{3})+$)/g,(function(t){return"".concat(t).concat(e)}))}function q(t,e){var i="".concat(t);if(new RegExp("\\.0{"+e+",}[1-9][0-9]*$").test(i)){var n=i.split("."),o=n[n.length-1],r=o.match(/0*/);if(V(r)){var a=r[0].length;return n[n.length-1]=o.replace(/0*/,"0{".concat(a,"}")),n.join(".")}}return i}function $(t){var e,i,n;return null!==(n=null===(i=null===(e=t.ownerDocument)||void 0===e?void 0:e.defaultView)||void 0===i?void 0:i.devicePixelRatio)&&void 0!==n?n:1}function Q(t,e,i){return"".concat(null!=e?e:"normal"," ").concat(null!=t?t:12,"px ").concat(null!=i?i:"Helvetica Neue")}function J(t,e,i,n){if(!V(z)){var o=document.createElement("canvas"),r=$(o);(z=o.getContext("2d")).scale(r,r)}return z.font=Q(e,i,n),Math.round(z.measureText(t).width)}t.ActionType=void 0,(Y=t.ActionType||(t.ActionType={})).OnDataReady="onDataReady",Y.OnZoom="onZoom",Y.OnScroll="onScroll",Y.OnVisibleRangeChange="onVisibleRangeChange",Y.OnTooltipIconClick="onTooltipIconClick",Y.OnCrosshairChange="onCrosshairChange",Y.OnCandleBarClick="onCandleBarClick",Y.OnPaneDrag="onPaneDrag";var tt,et=function(){function t(){this._callbacks=[]}return t.prototype.subscribe=function(t){var e;(null!==(e=this._callbacks.indexOf(t))&&void 0!==e?e:-1)<0&&this._callbacks.push(t)},t.prototype.unsubscribe=function(t){var e;if(R(t)){var i=null!==(e=this._callbacks.indexOf(t))&&void 0!==e?e:-1;i>-1&&this._callbacks.splice(i,1)}else this._callbacks=[]},t.prototype.execute=function(t){this._callbacks.forEach((function(e){e(t)}))},t.prototype.isEmpty=function(){return 0===this._callbacks.length},t}();function it(t,e,i,n,o){var r,a=e.result,s=e.figures,l=e.styles,c=G(l,"circles",n.circles),u=c.length,h=G(l,"bars",n.bars),p=h.length,g=G(l,"lines",n.lines),v=g.length,f=0,y=0,m=0,_=0;s.forEach((function(s){var l;switch(s.type){case"circle":_=f;var x=c[f%u];r=d(d({},x),{color:x.noChangeColor}),f++;break;case"bar":_=y;var S=h[y%p];r=d(d({},S),{color:S.noChangeColor}),y++;break;case"line":_=m,r=g[m%v],m++}if(V(r)){var C={prev:{kLineData:t[i-1],indicatorData:a[i-1]},current:{kLineData:t[i],indicatorData:a[i]},next:{kLineData:t[i+1],indicatorData:a[i+1]}},b=null===(l=s.styles)||void 0===l?void 0:l.call(s,C,e,n);o(s,d(d({},r),b),_)}}))}t.IndicatorSeries=void 0,(tt=t.IndicatorSeries||(t.IndicatorSeries={})).Normal="normal",tt.Price="price",tt.Volume="volume";var nt,ot=function(){function e(e){this.result=[],this._precisionFlag=!1;var i=e.name,n=e.shortName,o=e.series,r=e.calcParams,a=e.figures,s=e.precision,l=e.shouldOhlc,c=e.shouldFormatBigNumber,u=e.visible,h=e.zLevel,d=e.minValue,p=e.maxValue,g=e.styles,v=e.extendData,f=e.regenerateFigures,y=e.createTooltipDataSource,m=e.draw;this.name=i,this.shortName=null!=n?n:i,this.series=null!=o?o:t.IndicatorSeries.Normal,this.precision=null!=s?s:4,this.calcParams=null!=r?r:[],this.figures=null!=a?a:[],this.shouldOhlc=null!=l&&l,this.shouldFormatBigNumber=null!=c&&c,this.visible=null==u||u,this.zLevel=null!=h?h:0,this.minValue=null!=d?d:null,this.maxValue=null!=p?p:null,this.styles=F(null!=g?g:{}),this.extendData=v,this.regenerateFigures=null!=f?f:null,this.createTooltipDataSource=null!=y?y:null,this.draw=null!=m?m:null}return e.prototype.setShortName=function(t){return this.shortName!==t&&(this.shortName=t,!0)},e.prototype.setSeries=function(t){return this.series!==t&&(this.series=t,!0)},e.prototype.setPrecision=function(t,e){var i=null!=e&&e,n=Math.floor(t);return!(!(n!==this.precision&&t>=0)||i&&(!i||this._precisionFlag))&&(this.precision=n,i||(this._precisionFlag=!0),!0)},e.prototype.setCalcParams=function(t){var e,i;return this.calcParams=t,this.figures=null!==(i=null===(e=this.regenerateFigures)||void 0===e?void 0:e.call(this,t))&&void 0!==i?i:this.figures,!0},e.prototype.setShouldOhlc=function(t){return this.shouldOhlc!==t&&(this.shouldOhlc=t,!0)},e.prototype.setShouldFormatBigNumber=function(t){return this.shouldFormatBigNumber!==t&&(this.shouldFormatBigNumber=t,!0)},e.prototype.setVisible=function(t){return this.visible!==t&&(this.visible=t,!0)},e.prototype.setZLevel=function(t){return this.zLevel!==t&&(this.zLevel=t,!0)},e.prototype.setStyles=function(t){return A(this.styles,t),!0},e.prototype.setExtendData=function(t){return this.extendData!==t&&(this.extendData=t,!0)},e.prototype.setFigures=function(t){return this.figures!==t&&(this.figures=t,!0)},e.prototype.setMinValue=function(t){return this.minValue!==t&&(this.minValue=t,!0)},e.prototype.setMaxValue=function(t){return this.maxValue!==t&&(this.maxValue=t,!0)},e.prototype.setRegenerateFigures=function(t){return this.regenerateFigures!==t&&(this.regenerateFigures=t,!0)},e.prototype.setCreateTooltipDataSource=function(t){return this.createTooltipDataSource!==t&&(this.createTooltipDataSource=t,!0)},e.prototype.setDraw=function(t){return this.draw!==t&&(this.draw=t,!0)},e.prototype.calcIndicator=function(t){return p(this,void 0,void 0,(function(){var e;return g(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.calc(t,this)];case 1:return e=i.sent(),this.result=e,[2,!0];case 2:return i.sent(),[2,!1];case 3:return[2]}}))}))},e.extend=function(t){return function(e){function n(){return e.call(this,t)||this}return i(n,e),n.prototype.calc=function(e,i){return t.calc(e,i)},n}(e)},e}();t.OverlayMode=void 0,(nt=t.OverlayMode||(t.OverlayMode={})).Normal="normal",nt.WeakMagnet="weak_magnet",nt.StrongMagnet="strong_magnet";var rt,at="overlay_figure_",st=Number.MAX_SAFE_INTEGER,lt=function(){function e(e){this.currentStep=1,this.points=[],this._prevPressedPoint=null,this._prevPressedPoints=[];var i=e.mode,n=e.modeSensitivity,o=e.extendData,r=e.styles,a=e.name,s=e.totalStep,l=e.lock,c=e.visible,u=e.zLevel,h=e.needDefaultPointFigure,d=e.needDefaultXAxisFigure,p=e.needDefaultYAxisFigure,g=e.createPointFigures,v=e.createXAxisFigures,f=e.createYAxisFigures,y=e.performEventPressedMove,m=e.performEventMoveForDrawing,_=e.onDrawStart,x=e.onDrawing,S=e.onDrawEnd,C=e.onClick,b=e.onDoubleClick,T=e.onRightClick,w=e.onPressedMoveStart,E=e.onPressedMoving,I=e.onPressedMoveEnd,P=e.onMouseEnter,D=e.onMouseLeave,M=e.onRemoved,k=e.onSelected,A=e.onDeselected;this.name=a,this.totalStep=!O(s)||s<2?1:s,this.lock=null!=l&&l,this.visible=null==c||c,this.zLevel=null!=u?u:0,this.needDefaultPointFigure=null!=h&&h,this.needDefaultXAxisFigure=null!=d&&d,this.needDefaultYAxisFigure=null!=p&&p,this.mode=null!=i?i:t.OverlayMode.Normal,this.modeSensitivity=null!=n?n:8,this.extendData=o,this.styles=F(null!=r?r:{}),this.createPointFigures=null!=g?g:null,this.createXAxisFigures=null!=v?v:null,this.createYAxisFigures=null!=f?f:null,this.performEventPressedMove=null!=y?y:null,this.performEventMoveForDrawing=null!=m?m:null,this.onDrawStart=null!=_?_:null,this.onDrawing=null!=x?x:null,this.onDrawEnd=null!=S?S:null,this.onClick=null!=C?C:null,this.onDoubleClick=null!=b?b:null,this.onRightClick=null!=T?T:null,this.onPressedMoveStart=null!=w?w:null,this.onPressedMoving=null!=E?E:null,this.onPressedMoveEnd=null!=I?I:null,this.onMouseEnter=null!=P?P:null,this.onMouseLeave=null!=D?D:null,this.onRemoved=null!=M?M:null,this.onSelected=null!=k?k:null,this.onDeselected=null!=A?A:null}return e.prototype.setId=function(t){return!W(this.id)&&(this.id=t,!0)},e.prototype.setGroupId=function(t){return!W(this.groupId)&&(this.groupId=t,!0)},e.prototype.setPaneId=function(t){this.paneId=t},e.prototype.setExtendData=function(t){return t!==this.extendData&&(this.extendData=t,!0)},e.prototype.setStyles=function(t){return A(this.styles,t),!0},e.prototype.setPoints=function(t){if(t.length>0){var e=void 0;if(this.points=y([],f(t),!1),t.length>=this.totalStep-1?(this.currentStep=-1,e=this.totalStep-1):(this.currentStep=t.length+1,e=t.length),null!==this.performEventMoveForDrawing)for(var i=0;i<e;i++)this.performEventMoveForDrawing({currentStep:i+2,mode:this.mode,points:this.points,performPointIndex:i,performPoint:this.points[i]});return-1===this.currentStep&&null!==this.performEventPressedMove&&this.performEventPressedMove({currentStep:this.currentStep,mode:this.mode,points:this.points,performPointIndex:this.points.length-1,performPoint:this.points[this.points.length-1]}),!0}return!1},e.prototype.setLock=function(t){return this.lock!==t&&(this.lock=t,!0)},e.prototype.setVisible=function(t){return this.visible!==t&&(this.visible=t,!0)},e.prototype.setZLevel=function(t){return this.zLevel!==t&&(this.zLevel=t,!0)},e.prototype.setMode=function(t){return this.mode!==t&&(this.mode=t,!0)},e.prototype.setModeSensitivity=function(t){return this.modeSensitivity!==t&&(this.modeSensitivity=t,!0)},e.prototype.setOnDrawStartCallback=function(t){return this.onDrawStart!==t&&(this.onDrawStart=t,!0)},e.prototype.setOnDrawingCallback=function(t){return this.onDrawing!==t&&(this.onDrawing=t,!0)},e.prototype.setOnDrawEndCallback=function(t){return this.onDrawEnd!==t&&(this.onDrawEnd=t,!0)},e.prototype.setOnClickCallback=function(t){return this.onClick!==t&&(this.onClick=t,!0)},e.prototype.setOnDoubleClickCallback=function(t){return this.onDoubleClick!==t&&(this.onDoubleClick=t,!0)},e.prototype.setOnRightClickCallback=function(t){return this.onRightClick!==t&&(this.onRightClick=t,!0)},e.prototype.setOnPressedMoveStartCallback=function(t){return this.onPressedMoveStart!==t&&(this.onPressedMoveStart=t,!0)},e.prototype.setOnPressedMovingCallback=function(t){return this.onPressedMoving!==t&&(this.onPressedMoving=t,!0)},e.prototype.setOnPressedMoveEndCallback=function(t){return this.onPressedMoveEnd!==t&&(this.onPressedMoveEnd=t,!0)},e.prototype.setOnMouseEnterCallback=function(t){return this.onMouseEnter!==t&&(this.onMouseEnter=t,!0)},e.prototype.setOnMouseLeaveCallback=function(t){return this.onMouseLeave!==t&&(this.onMouseLeave=t,!0)},e.prototype.setOnRemovedCallback=function(t){return this.onRemoved!==t&&(this.onRemoved=t,!0)},e.prototype.setOnSelectedCallback=function(t){return this.onSelected!==t&&(this.onSelected=t,!0)},e.prototype.setOnDeselectedCallback=function(t){return this.onDeselected!==t&&(this.onDeselected=t,!0)},e.prototype.nextStep=function(){this.currentStep===this.totalStep-1?this.currentStep=-1:this.currentStep++},e.prototype.forceComplete=function(){this.currentStep=-1},e.prototype.isDrawing=function(){return-1!==this.currentStep},e.prototype.isStart=function(){return 1===this.currentStep},e.prototype.eventMoveForDrawing=function(t){var e,i=this.currentStep-1,n={};O(t.timestamp)&&(n.timestamp=t.timestamp),O(t.dataIndex)&&(n.dataIndex=t.dataIndex),O(t.value)&&(n.value=t.value),this.points[i]=n,null===(e=this.performEventMoveForDrawing)||void 0===e||e.call(this,{currentStep:this.currentStep,mode:this.mode,points:this.points,performPointIndex:i,performPoint:n})},e.prototype.eventPressedPointMove=function(t,e){var i;O(t.dataIndex)&&(this.points[e].dataIndex=t.dataIndex,this.points[e].timestamp=t.timestamp),O(t.value)&&(this.points[e].value=t.value),null===(i=this.performEventPressedMove)||void 0===i||i.call(this,{currentStep:this.currentStep,points:this.points,mode:this.mode,performPointIndex:e,performPoint:this.points[e]})},e.prototype.startPressedMove=function(t){this._prevPressedPoint=d({},t),this._prevPressedPoints=F(this.points)},e.prototype.eventPressedOtherMove=function(t,e){var i,n;null!==this._prevPressedPoint&&(O(t.dataIndex)&&O(this._prevPressedPoint.dataIndex)&&(i=t.dataIndex-this._prevPressedPoint.dataIndex),O(t.value)&&O(this._prevPressedPoint.value)&&(n=t.value-this._prevPressedPoint.value),this.points=this._prevPressedPoints.map((function(t){var o;O(t.timestamp)&&(t.dataIndex=e.timestampToDataIndex(t.timestamp));var r=d({},t);return O(i)&&O(t.dataIndex)&&(r.dataIndex=t.dataIndex+i,r.timestamp=null!==(o=e.dataIndexToTimestamp(r.dataIndex))&&void 0!==o?o:void 0),O(n)&&O(t.value)&&(r.value=t.value+n),r})))},e.extend=function(t){return function(e){function n(){return e.call(this,t)||this}return i(n,e),n}(e)},e}();t.FormatDateType=void 0,(rt=t.FormatDateType||(t.FormatDateType={}))[rt.Tooltip=0]="Tooltip",rt[rt.Crosshair=1]="Crosshair",rt[rt.XAxis=2]="XAxis";function ct(t){return R(window.requestAnimationFrame)?window.requestAnimationFrame(t):window.setTimeout(t,20)}function ut(t){R(window.cancelAnimationFrame)?window.cancelAnimationFrame(t):window.clearTimeout(t)}var ht,dt=function(){function t(t){this._options={duration:500,iterationCount:1},this._currentIterationCount=0,this._running=!1,this._time=0,A(this._options,t)}return t.prototype._loop=function(){var t=this;this._running=!0;var e=function(){var i;if(t._running){var n=(new Date).getTime()-t._time;n<t._options.duration?(null===(i=t._doFrameCallback)||void 0===i||i.call(t,n),ct(e)):(t.stop(),t._currentIterationCount++,t._currentIterationCount<t._options.iterationCount&&t.start())}};ct(e)},t.prototype.doFrame=function(t){return this._doFrameCallback=t,this},t.prototype.setDuration=function(t){return this._options.duration=t,this},t.prototype.setIterationCount=function(t){return this._options.iterationCount=t,this},t.prototype.start=function(){this._running||(this._time=(new Date).getTime(),this._loop())},t.prototype.stop=function(){var t;this._running&&(null===(t=this._doFrameCallback)||void 0===t||t.call(this,this._options.duration)),this._running=!1},t}(),pt=1,gt=(new Date).getTime();function vt(t){var e=(new Date).getTime();return e===gt?++pt:pt=1,gt=e,"".concat(null!=t?t:"").concat(e,"_").concat(pt)}function ft(t,e){var i,n=document.createElement(t),o=null!=e?e:{};for(var r in o)n.style[r]=null!==(i=o[r])&&void 0!==i?i:"";return n}function yt(t,e,i){var n=0,o=0;for(o=t.length-1;n!==o;){var r=Math.floor((o+n)/2),a=o-n,s=t[r][e];if(i===t[n][e])return n;if(i===t[o][e])return o;if(i===s)return r;if(i>s?n=r:o=r,a<=2)break}return n}function mt(t,e){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),+(+t).toFixed(e)}function _t(t,e,i){var n=[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER];return t.forEach((function(t){var o,r;n[0]=Math.max(null!==(o=t[e])&&void 0!==o?o:t,n[0]),n[1]=Math.min(null!==(r=t[i])&&void 0!==r?r:t,n[1])})),n}function xt(t){return Math.log(t)/Math.log(10)}function St(t){return Math.pow(10,t)}!function(t){t.Init="init",t.Forward="forward",t.Backward="backward"}(ht||(ht={}));var Ct=1,bt=50,Tt=function(){function e(t){this._dateTimeFormat=this._buildDateTimeFormat(),this._zoomEnabled=!0,this._scrollEnabled=!0,this._totalBarSpace=0,this._barSpace=8,this._offsetRightDistance=80,this._startLastBarRightSideDiffBarCount=0,this._scrollLimitRole=0,this._minVisibleBarCount={left:2,right:2},this._maxOffsetDistance={left:50,right:50},this._visibleRange={from:0,to:0,realFrom:0,realTo:0},this._chartStore=t,this._gapBarSpace=this._calcGapBarSpace(),this._lastBarRightSideDiffBarCount=this._offsetRightDistance/this._barSpace}return e.prototype._calcGapBarSpace=function(){var t;return this._barSpace>3?t=Math.floor(.88*this._barSpace):(t=Math.floor(this._barSpace))===this._barSpace&&t--,t%2==0&&t--,t=Math.max(1,t)},e.prototype.adjustVisibleRange=function(){var e,i,n,o,r=this._chartStore.getDataList(),a=r.length,s=this._totalBarSpace/this._barSpace;1===this._scrollLimitRole?(n=(this._totalBarSpace-this._maxOffsetDistance.right)/this._barSpace,o=(this._totalBarSpace-this._maxOffsetDistance.left)/this._barSpace):(n=this._minVisibleBarCount.left,o=this._minVisibleBarCount.right),n=Math.max(0,n),o=Math.max(0,o);var l=s-Math.min(n,a);this._lastBarRightSideDiffBarCount>l&&(this._lastBarRightSideDiffBarCount=l);var c=-a+Math.min(o,a);this._lastBarRightSideDiffBarCount<c&&(this._lastBarRightSideDiffBarCount=c);var u=Math.round(this._lastBarRightSideDiffBarCount+a+.5),h=u;u>a&&(u=a);var d=Math.round(u-s)-1;d<0&&(d=0);var p=this._lastBarRightSideDiffBarCount>0?Math.round(a+this._lastBarRightSideDiffBarCount-s)-1:d;if(this._visibleRange={from:d,to:u,realFrom:p,realTo:h},this._chartStore.getActionStore().execute(t.ActionType.OnVisibleRangeChange,this._visibleRange),this._chartStore.adjustVisibleDataList(),0===d){var g=r[0];this._chartStore.executeLoadMoreCallback(null!==(e=null==g?void 0:g.timestamp)&&void 0!==e?e:null),this._chartStore.executeLoadDataCallback({type:ht.Forward,data:null!=g?g:null})}u===a&&this._chartStore.executeLoadDataCallback({type:ht.Backward,data:null!==(i=r[a-1])&&void 0!==i?i:null})},e.prototype.getDateTimeFormat=function(){return this._dateTimeFormat},e.prototype._buildDateTimeFormat=function(t){var e={hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"};W(t)&&(e.timeZone=t);var i=null;try{i=new Intl.DateTimeFormat("en",e)}catch(t){}return i},e.prototype.setTimezone=function(t){var e=this._buildDateTimeFormat(t);null!==e&&(this._dateTimeFormat=e)},e.prototype.getTimezone=function(){return this._dateTimeFormat.resolvedOptions().timeZone},e.prototype.getBarSpace=function(){return{bar:this._barSpace,halfBar:this._barSpace/2,gapBar:this._gapBarSpace,halfGapBar:Math.floor(this._gapBarSpace/2)}},e.prototype.setBarSpace=function(t,e){t<Ct||t>bt||this._barSpace===t||(this._barSpace=t,this._gapBarSpace=this._calcGapBarSpace(),null==e||e(),this.adjustVisibleRange(),this._chartStore.getTooltipStore().recalculateCrosshair(!0),this._chartStore.getChart().adjustPaneViewport(!1,!0,!0,!0))},e.prototype.setTotalBarSpace=function(t){return this._totalBarSpace!==t&&(this._totalBarSpace=t,this.adjustVisibleRange(),this._chartStore.getTooltipStore().recalculateCrosshair(!0)),this},e.prototype.setOffsetRightDistance=function(t,e){return this._offsetRightDistance=1===this._scrollLimitRole?Math.min(this._maxOffsetDistance.right,t):t,this._lastBarRightSideDiffBarCount=this._offsetRightDistance/this._barSpace,null!=e&&e&&(this.adjustVisibleRange(),this._chartStore.getTooltipStore().recalculateCrosshair(!0),this._chartStore.getChart().adjustPaneViewport(!1,!0,!0,!0)),this},e.prototype.resetOffsetRightDistance=function(){this.setOffsetRightDistance(this._offsetRightDistance)},e.prototype.getInitialOffsetRightDistance=function(){return this._offsetRightDistance},e.prototype.getOffsetRightDistance=function(){return Math.max(0,this._lastBarRightSideDiffBarCount*this._barSpace)},e.prototype.getLastBarRightSideDiffBarCount=function(){return this._lastBarRightSideDiffBarCount},e.prototype.setLastBarRightSideDiffBarCount=function(t){return this._lastBarRightSideDiffBarCount=t,this},e.prototype.setMaxOffsetLeftDistance=function(t){return this._scrollLimitRole=1,this._maxOffsetDistance.left=t,this},e.prototype.setMaxOffsetRightDistance=function(t){return this._scrollLimitRole=1,this._maxOffsetDistance.right=t,this},e.prototype.setLeftMinVisibleBarCount=function(t){return this._scrollLimitRole=0,this._minVisibleBarCount.left=t,this},e.prototype.setRightMinVisibleBarCount=function(t){return this._scrollLimitRole=0,this._minVisibleBarCount.right=t,this},e.prototype.getVisibleRange=function(){return this._visibleRange},e.prototype.startScroll=function(){this._startLastBarRightSideDiffBarCount=this._lastBarRightSideDiffBarCount},e.prototype.scroll=function(e){if(this._scrollEnabled){var i=e/this._barSpace,n=this._lastBarRightSideDiffBarCount*this._barSpace;this._lastBarRightSideDiffBarCount=this._startLastBarRightSideDiffBarCount-i,this.adjustVisibleRange(),this._chartStore.getTooltipStore().recalculateCrosshair(!0),this._chartStore.getChart().adjustPaneViewport(!1,!0,!0,!0);var o=Math.round(n-this._lastBarRightSideDiffBarCount*this._barSpace);0!==o&&this._chartStore.getActionStore().execute(t.ActionType.OnScroll,{distance:o})}},e.prototype.getDataByDataIndex=function(t){var e;return null!==(e=this._chartStore.getDataList()[t])&&void 0!==e?e:null},e.prototype.coordinateToFloatIndex=function(t){var e=this._chartStore.getDataList().length,i=(this._totalBarSpace-t)/this._barSpace,n=e+this._lastBarRightSideDiffBarCount-i;return Math.round(1e6*n)/1e6},e.prototype.dataIndexToTimestamp=function(t){var e,i=this.getDataByDataIndex(t);return null!==(e=null==i?void 0:i.timestamp)&&void 0!==e?e:null},e.prototype.timestampToDataIndex=function(t){var e=this._chartStore.getDataList();return 0===e.length?0:yt(e,"timestamp",t)},e.prototype.dataIndexToCoordinate=function(t){var e=this._chartStore.getDataList().length+this._lastBarRightSideDiffBarCount-t;return Math.floor(this._totalBarSpace-(e-.5)*this._barSpace)},e.prototype.coordinateToDataIndex=function(t){return Math.ceil(this.coordinateToFloatIndex(t))-1},e.prototype.zoom=function(e,i){var n,o=this;if(this._zoomEnabled){var r=null!=i?i:null;if(!O(null==r?void 0:r.x)){var a=this._chartStore.getTooltipStore().getCrosshair();r={x:null!==(n=null==a?void 0:a.x)&&void 0!==n?n:this._totalBarSpace/2}}var s=r.x,l=this.coordinateToFloatIndex(s),c=this._barSpace,u=this._barSpace+e*(this._barSpace/10);this.setBarSpace(u,(function(){o._lastBarRightSideDiffBarCount+=l-o.coordinateToFloatIndex(s)}));var h=this._barSpace/c;1!==h&&this._chartStore.getActionStore().execute(t.ActionType.OnZoom,{scale:h})}},e.prototype.setZoomEnabled=function(t){return this._zoomEnabled=t,this},e.prototype.getZoomEnabled=function(){return this._zoomEnabled},e.prototype.setScrollEnabled=function(t){return this._scrollEnabled=t,this},e.prototype.getScrollEnabled=function(){return this._scrollEnabled},e.prototype.clear=function(){this._visibleRange={from:0,to:0,realFrom:0,realTo:0}},e}(),wt={name:"AVP",shortName:"AVP",series:t.IndicatorSeries.Price,precision:2,figures:[{key:"avp",title:"AVP: ",type:"line"}],calc:function(t){var e=0,i=0;return t.map((function(t){var n,o,r={},a=null!==(n=null==t?void 0:t.turnover)&&void 0!==n?n:0,s=null!==(o=null==t?void 0:t.volume)&&void 0!==o?o:0;return e+=a,0!==(i+=s)&&(r.avp=e/i),r}))}},Et={name:"AO",shortName:"AO",calcParams:[5,34],figures:[{key:"ao",title:"AO: ",type:"bar",baseValue:0,styles:function(e,i,n){var o,r,a,s,l,c=e.prev,u=e.current,h=null!==(r=null===(o=c.indicatorData)||void 0===o?void 0:o.ao)&&void 0!==r?r:Number.MIN_SAFE_INTEGER,d=null!==(s=null===(a=u.indicatorData)||void 0===a?void 0:a.ao)&&void 0!==s?s:Number.MIN_SAFE_INTEGER;return{color:l=d>h?G(i.styles,"bars[0].upColor",n.bars[0].upColor):G(i.styles,"bars[0].downColor",n.bars[0].downColor),style:d>h?t.PolygonType.Stroke:t.PolygonType.Fill,borderColor:l}}}],calc:function(t,e){var i=e.calcParams,n=Math.max(i[0],i[1]),o=0,r=0,a=0,s=0;return t.map((function(e,l){var c={},u=(e.low+e.high)/2;if(o+=u,r+=u,l>=i[0]-1){a=o/i[0];var h=t[l-(i[0]-1)];o-=(h.low+h.high)/2}if(l>=i[1]-1){s=r/i[1];h=t[l-(i[1]-1)];r-=(h.low+h.high)/2}return l>=n-1&&(c.ao=a-s),c}))}};var It={name:"BOLL",shortName:"BOLL",series:t.IndicatorSeries.Price,calcParams:[20,2],precision:2,shouldOhlc:!0,figures:[{key:"up",title:"UP: ",type:"line"},{key:"mid",title:"MID: ",type:"line"},{key:"dn",title:"DN: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=i[0]-1,o=0;return t.map((function(e,r){var a=e.close,s={};if(o+=a,r>=n){s.mid=o/i[0];var l=function(t,e){var i=t.length,n=0;return t.forEach((function(t){var i=t.close-e;n+=i*i})),n=Math.abs(n),Math.sqrt(n/i)}(t.slice(r-n,r+1),s.mid);s.up=s.mid+i[1]*l,s.dn=s.mid-i[1]*l,o-=t[r-n].close}return s}))}},Pt={name:"BBI",shortName:"BBI",series:t.IndicatorSeries.Price,precision:2,calcParams:[3,6,12,24],shouldOhlc:!0,figures:[{key:"bbi",title:"BBI: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=Math.max.apply(Math,y([],f(i),!1)),o=[],r=[];return t.map((function(e,a){var s={},l=e.close;if(i.forEach((function(e,i){var n;o[i]=(null!==(n=o[i])&&void 0!==n?n:0)+l,a>=e-1&&(r[i]=o[i]/e,o[i]-=t[a-(e-1)].close)})),a>=n-1){var c=0;r.forEach((function(t){c+=t})),s.bbi=c/4}return s}))}},Dt={name:"CCI",shortName:"CCI",calcParams:[20],figures:[{key:"cci",title:"CCI: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=i[0]-1,o=0,r=[];return t.map((function(e,a){var s={},l=(e.high+e.low+e.close)/3;if(o+=l,r.push(l),a>=n){var c=o/i[0],u=r.slice(a-n,a+1),h=0;u.forEach((function(t){h+=Math.abs(t-c)}));var d=h/i[0];s.cci=0!==d?(l-c)/d/.015:0;var p=(t[a-n].high+t[a-n].low+t[a-n].close)/3;o-=p}return s}))}},Mt={name:"CR",shortName:"CR",calcParams:[26,10,20,40,60],figures:[{key:"cr",title:"CR: ",type:"line"},{key:"ma1",title:"MA1: ",type:"line"},{key:"ma2",title:"MA2: ",type:"line"},{key:"ma3",title:"MA3: ",type:"line"},{key:"ma4",title:"MA4: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=Math.ceil(i[1]/2.5+1),o=Math.ceil(i[2]/2.5+1),r=Math.ceil(i[3]/2.5+1),a=Math.ceil(i[4]/2.5+1),s=0,l=[],c=0,u=[],h=0,d=[],p=0,g=[],v=[];return t.forEach((function(e,f){var y,m,_,x,S,C={},b=null!==(y=t[f-1])&&void 0!==y?y:e,T=(b.high+b.close+b.low+b.open)/4,w=Math.max(0,e.high-T),E=Math.max(0,T-e.low);f>=i[0]-1&&(C.cr=0!==E?w/E*100:0,s+=C.cr,c+=C.cr,h+=C.cr,p+=C.cr,f>=i[0]+i[1]-2&&(l.push(s/i[1]),f>=i[0]+i[1]+n-3&&(C.ma1=l[l.length-1-n]),s-=null!==(m=v[f-(i[1]-1)].cr)&&void 0!==m?m:0),f>=i[0]+i[2]-2&&(u.push(c/i[2]),f>=i[0]+i[2]+o-3&&(C.ma2=u[u.length-1-o]),c-=null!==(_=v[f-(i[2]-1)].cr)&&void 0!==_?_:0),f>=i[0]+i[3]-2&&(d.push(h/i[3]),f>=i[0]+i[3]+r-3&&(C.ma3=d[d.length-1-r]),h-=null!==(x=v[f-(i[3]-1)].cr)&&void 0!==x?x:0),f>=i[0]+i[4]-2&&(g.push(p/i[4]),f>=i[0]+i[4]+a-3&&(C.ma4=g[g.length-1-a]),p-=null!==(S=v[f-(i[4]-1)].cr)&&void 0!==S?S:0)),v.push(C)})),v}},kt={name:"DMA",shortName:"DMA",calcParams:[10,50,10],figures:[{key:"dma",title:"DMA: ",type:"line"},{key:"ama",title:"AMA: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=Math.max(i[0],i[1]),o=0,r=0,a=0,s=[];return t.forEach((function(e,l){var c,u={},h=e.close;o+=h,r+=h;var d=0,p=0;if(l>=i[0]-1&&(d=o/i[0],o-=t[l-(i[0]-1)].close),l>=i[1]-1&&(p=r/i[1],r-=t[l-(i[1]-1)].close),l>=n-1){var g=d-p;u.dma=g,a+=g,l>=n+i[2]-2&&(u.ama=a/i[2],a-=null!==(c=s[l-(i[2]-1)].dma)&&void 0!==c?c:0)}s.push(u)})),s}},At={name:"DMI",shortName:"DMI",calcParams:[14,6],figures:[{key:"pdi",title:"PDI: ",type:"line"},{key:"mdi",title:"MDI: ",type:"line"},{key:"adx",title:"ADX: ",type:"line"},{key:"adxr",title:"ADXR: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=0,r=0,a=0,s=0,l=0,c=0,u=0,h=[];return t.forEach((function(e,d){var p,g,v={},f=null!==(p=t[d-1])&&void 0!==p?p:e,y=f.close,m=e.high,_=e.low,x=m-_,S=Math.abs(m-y),C=Math.abs(y-_),b=m-f.high,T=f.low-_,w=Math.max(Math.max(x,S),C),E=b>0&&b>T?b:0,I=T>0&&T>b?T:0;if(n+=w,o+=E,r+=I,d>=i[0]-1){d>i[0]-1?(a=a-a/i[0]+w,s=s-s/i[0]+E,l=l-l/i[0]+I):(a=n,s=o,l=r);var P=0,D=0;0!==a&&(P=100*s/a,D=100*l/a),v.pdi=P,v.mdi=D;var M=0;D+P!==0&&(M=Math.abs(D-P)/(D+P)*100),c+=M,d>=2*i[0]-2&&(u=d>2*i[0]-2?(u*(i[0]-1)+M)/i[0]:c/i[0],v.adx=u,d>=2*i[0]+i[1]-3&&(v.adxr=((null!==(g=h[d-(i[1]-1)].adx)&&void 0!==g?g:0)+u)/2))}h.push(v)})),h}},Ft={name:"EMA",shortName:"EMA",series:t.IndicatorSeries.Price,calcParams:[6,12,20],precision:2,shouldOhlc:!0,figures:[{key:"ema1",title:"EMA6: ",type:"line"},{key:"ema2",title:"EMA12: ",type:"line"},{key:"ema3",title:"EMA20: ",type:"line"}],regenerateFigures:function(t){return t.map((function(t,e){return{key:"ema".concat(e+1),title:"EMA".concat(t,": "),type:"line"}}))},calc:function(t,e){var i=e.calcParams,n=e.figures,o=0,r=[];return t.map((function(t,e){var a={},s=t.close;return o+=s,i.forEach((function(t,i){e>=t-1&&(r[i]=e>t-1?(2*s+(t-1)*r[i])/(t+1):o/t,a[n[i].key]=r[i])})),a}))}},Lt={name:"MA",shortName:"MA",series:t.IndicatorSeries.Price,calcParams:[5,10,30,60],precision:2,shouldOhlc:!0,figures:[{key:"ma5",title:"MA5: ",type:"line"},{key:"ma10",title:"MA10: ",type:"line"},{key:"ma30",title:"MA30: ",type:"line"},{key:"ma60",title:"MA60: ",type:"line"}],regenerateFigures:function(t){return t.map((function(t,e){return{key:"ma".concat(e+1),title:"MA".concat(t,": "),type:"line"}}))},calc:function(t,e){var i=e.calcParams,n=e.figures,o=[];return t.map((function(e,r){var a={},s=e.close;return i.forEach((function(e,i){var l;o[i]=(null!==(l=o[i])&&void 0!==l?l:0)+s,r>=e-1&&(a[n[i].key]=o[i]/e,o[i]-=t[r-(e-1)].close)})),a}))}},Rt={name:"MACD",shortName:"MACD",calcParams:[12,26,9],figures:[{key:"dif",title:"DIF: ",type:"line"},{key:"dea",title:"DEA: ",type:"line"},{key:"macd",title:"MACD: ",type:"bar",baseValue:0,styles:function(e,i,n){var o,r,a,s,l,c=e.prev,u=e.current,h=null!==(r=null===(o=c.indicatorData)||void 0===o?void 0:o.macd)&&void 0!==r?r:Number.MIN_SAFE_INTEGER,d=null!==(s=null===(a=u.indicatorData)||void 0===a?void 0:a.macd)&&void 0!==s?s:Number.MIN_SAFE_INTEGER;return l=d>0?G(i.styles,"bars[0].upColor",n.bars[0].upColor):d<0?G(i.styles,"bars[0].downColor",n.bars[0].downColor):G(i.styles,"bars[0].noChangeColor",n.bars[0].noChangeColor),{style:h<d?t.PolygonType.Stroke:t.PolygonType.Fill,color:l,borderColor:l}}}],calc:function(t,e){var i,n,o=e.calcParams,r=0,a=0,s=0,l=0,c=Math.max(o[0],o[1]);return t.map((function(t,e){var u={},h=t.close;return r+=h,e>=o[0]-1&&(i=e>o[0]-1?(2*h+(o[0]-1)*i)/(o[0]+1):r/o[0]),e>=o[1]-1&&(n=e>o[1]-1?(2*h+(o[1]-1)*n)/(o[1]+1):r/o[1]),e>=c-1&&(a=i-n,u.dif=a,s+=a,e>=c+o[2]-2&&(l=e>c+o[2]-2?(2*a+l*(o[2]-1))/(o[2]+1):s/o[2],u.macd=2*(a-l),u.dea=l)),u}))}},Bt={name:"RSI",shortName:"RSI",calcParams:[6,12,24],figures:[{key:"rsi1",title:"RSI1: ",type:"line"},{key:"rsi2",title:"RSI2: ",type:"line"},{key:"rsi3",title:"RSI3: ",type:"line"}],regenerateFigures:function(t){return t.map((function(t,e){var i=e+1;return{key:"rsi".concat(i),title:"RSI".concat(i,": "),type:"line"}}))},calc:function(t,e){var i=e.calcParams,n=e.figures,o=[],r=[];return t.map((function(e,a){var s,l={},c=(null!==(s=t[a-1])&&void 0!==s?s:e).close,u=e.close-c;return i.forEach((function(e,i){var s,c,h;if(u>0?o[i]=(null!==(s=o[i])&&void 0!==s?s:0)+u:r[i]=(null!==(c=r[i])&&void 0!==c?c:0)+Math.abs(u),a>=e-1){0!==r[i]?l[n[i].key]=100-100/(1+o[i]/r[i]):l[n[i].key]=0;var d=t[a-(e-1)],p=null!==(h=t[a-e])&&void 0!==h?h:d,g=d.close-p.close;g>0?o[i]-=g:r[i]-=Math.abs(g)}})),l}))}},Ot={name:"SMA",shortName:"SMA",series:t.IndicatorSeries.Price,calcParams:[12,2],precision:2,figures:[{key:"sma",title:"SMA: ",type:"line"}],shouldOhlc:!0,calc:function(t,e){var i=e.calcParams,n=0,o=0;return t.map((function(t,e){var r={},a=t.close;return n+=a,e>=i[0]-1&&(o=e>i[0]-1?(a*i[1]+o*(i[0]-i[1]+1))/(i[0]+1):n/i[0],r.sma=o),r}))}},Vt={name:"KDJ",shortName:"KDJ",calcParams:[9,3,3],figures:[{key:"k",title:"K: ",type:"line"},{key:"d",title:"D: ",type:"line"},{key:"j",title:"J: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=[];return t.forEach((function(e,o){var r,a,s,l,c={},u=e.close;if(o>=i[0]-1){var h=_t(t.slice(o-(i[0]-1),o+1),"high","low"),d=h[0],p=h[1],g=d-p,v=(u-p)/(0===g?1:g)*100;c.k=((i[1]-1)*(null!==(a=null===(r=n[o-1])||void 0===r?void 0:r.k)&&void 0!==a?a:50)+v)/i[1],c.d=((i[2]-1)*(null!==(l=null===(s=n[o-1])||void 0===s?void 0:s.d)&&void 0!==l?l:50)+c.k)/i[2],c.j=3*c.k-2*c.d}n.push(c)})),n}},Nt={name:"SAR",shortName:"SAR",series:t.IndicatorSeries.Price,calcParams:[2,2,20],precision:2,shouldOhlc:!0,figures:[{key:"sar",title:"SAR: ",type:"circle",styles:function(t,e,i){var n,o,r=t.current,a=null!==(o=null===(n=r.indicatorData)||void 0===n?void 0:n.sar)&&void 0!==o?o:Number.MIN_SAFE_INTEGER,s=r.kLineData;return{color:a<((null==s?void 0:s.high)+(null==s?void 0:s.low))/2?G(e.styles,"circles[0].upColor",i.circles[0].upColor):G(e.styles,"circles[0].downColor",i.circles[0].downColor)}}}],calc:function(t,e){var i=e.calcParams,n=i[0]/100,o=i[1]/100,r=i[2]/100,a=n,s=-100,l=!1,c=0;return t.map((function(e,i){var u=c,h=e.high,d=e.low;if(l){(-100===s||s<h)&&(s=h,a=Math.min(a+o,r)),c=u+a*(s-u);var p=Math.min(t[Math.max(1,i)-1].low,d);c>e.low?(c=s,a=n,s=-100,l=!l):c>p&&(c=p)}else{(-100===s||s>d)&&(s=d,a=Math.min(a+o,r)),c=u+a*(s-u);var g=Math.max(t[Math.max(1,i)-1].high,h);c<e.high?(c=s,a=0,s=-100,l=!l):c<g&&(c=g)}return{sar:c}}))}};function Wt(){return{key:"volume",title:"VOLUME: ",type:"bar",baseValue:0,styles:function(t,e,i){var n=t.current.kLineData,o=G(e.styles,"bars[0].noChangeColor",i.bars[0].noChangeColor);return V(n)&&(n.close>n.open?o=G(e.styles,"bars[0].upColor",i.bars[0].upColor):n.close<n.open&&(o=G(e.styles,"bars[0].downColor",i.bars[0].downColor))),{color:o}}}}var zt={name:"VOL",shortName:"VOL",series:t.IndicatorSeries.Volume,calcParams:[5,10,20],shouldFormatBigNumber:!0,precision:0,minValue:0,figures:[{key:"ma1",title:"MA5: ",type:"line"},{key:"ma2",title:"MA10: ",type:"line"},{key:"ma3",title:"MA20: ",type:"line"},Wt()],regenerateFigures:function(t){var e=t.map((function(t,e){return{key:"ma".concat(e+1),title:"MA".concat(t,": "),type:"line"}}));return e.push(Wt()),e},calc:function(t,e){var i=e.calcParams,n=e.figures,o=[];return t.map((function(e,r){var a,s=null!==(a=e.volume)&&void 0!==a?a:0,l={volume:s};return i.forEach((function(e,i){var a,c;o[i]=(null!==(a=o[i])&&void 0!==a?a:0)+s,r>=e-1&&(l[n[i].key]=o[i]/e,o[i]-=null!==(c=t[r-(e-1)].volume)&&void 0!==c?c:0)})),l}))}},Yt={name:"WR",shortName:"WR",calcParams:[6,10,14],figures:[{key:"wr1",title:"WR1: ",type:"line"},{key:"wr2",title:"WR2: ",type:"line"},{key:"wr3",title:"WR3: ",type:"line"}],regenerateFigures:function(t){return t.map((function(t,e){return{key:"wr".concat(e+1),title:"WR".concat(e+1,": "),type:"line"}}))},calc:function(t,e){var i=e.calcParams,n=e.figures;return t.map((function(e,o){var r={},a=e.close;return i.forEach((function(e,i){var s=e-1;if(o>=s){var l=_t(t.slice(o-s,o+1),"high","low"),c=l[0],u=c-l[1];r[n[i].key]=0===u?0:(a-c)/u*100}})),r}))}},Ht={},Xt=[wt,Et,{name:"BIAS",shortName:"BIAS",calcParams:[6,12,24],figures:[{key:"bias1",title:"BIAS6: ",type:"line"},{key:"bias2",title:"BIAS12: ",type:"line"},{key:"bias3",title:"BIAS24: ",type:"line"}],regenerateFigures:function(t){return t.map((function(t,e){return{key:"bias".concat(e+1),title:"BIAS".concat(t,": "),type:"line"}}))},calc:function(t,e){var i=e.calcParams,n=e.figures,o=[];return t.map((function(e,r){var a={},s=e.close;return i.forEach((function(e,l){var c;if(o[l]=(null!==(c=o[l])&&void 0!==c?c:0)+s,r>=e-1){var u=o[l]/i[l];a[n[l].key]=(s-u)/u*100,o[l]-=t[r-(e-1)].close}})),a}))}},It,{name:"BRAR",shortName:"BRAR",calcParams:[26],figures:[{key:"br",title:"BR: ",type:"line"},{key:"ar",title:"AR: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=0,r=0,a=0;return t.map((function(e,s){var l,c,u={},h=e.high,d=e.low,p=e.open,g=(null!==(l=t[s-1])&&void 0!==l?l:e).close;if(r+=h-p,a+=p-d,n+=h-g,o+=g-d,s>=i[0]-1){u.ar=0!==a?r/a*100:0,u.br=0!==o?n/o*100:0;var v=t[s-(i[0]-1)],f=v.high,y=v.low,m=v.open,_=(null!==(c=t[s-i[0]])&&void 0!==c?c:t[s-(i[0]-1)]).close;n-=f-_,o-=_-y,r-=f-m,a-=m-y}return u}))}},Pt,Dt,Mt,kt,At,{name:"EMV",shortName:"EMV",calcParams:[14,9],figures:[{key:"emv",title:"EMV: ",type:"line"},{key:"maEmv",title:"MAEMV: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=[];return t.map((function(e,r){var a,s={};if(r>0){var l=t[r-1],c=e.high,u=e.low,h=null!==(a=e.volume)&&void 0!==a?a:0,d=(c+u)/2-(l.high+l.low)/2;if(0===h||c-u==0)s.emv=0;else{var p=h/1e8/(c-u);s.emv=d/p}n+=s.emv,o.push(s.emv),r>=i[0]&&(s.maEmv=n/i[0],n-=o[r-i[0]])}return s}))}},Ft,{name:"MTM",shortName:"MTM",calcParams:[12,6],figures:[{key:"mtm",title:"MTM: ",type:"line"},{key:"maMtm",title:"MAMTM: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=[];return t.forEach((function(e,r){var a,s={};if(r>=i[0]){var l=e.close,c=t[r-i[0]].close;s.mtm=l-c,n+=s.mtm,r>=i[0]+i[1]-1&&(s.maMtm=n/i[1],n-=null!==(a=o[r-(i[1]-1)].mtm)&&void 0!==a?a:0)}o.push(s)})),o}},Lt,Rt,{name:"OBV",shortName:"OBV",calcParams:[30],figures:[{key:"obv",title:"OBV: ",type:"line"},{key:"maObv",title:"MAOBV: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=0,r=[];return t.forEach((function(e,a){var s,l,c,u,h=null!==(s=t[a-1])&&void 0!==s?s:e;e.close<h.close?o-=null!==(l=e.volume)&&void 0!==l?l:0:e.close>h.close&&(o+=null!==(c=e.volume)&&void 0!==c?c:0);var d={obv:o};n+=o,a>=i[0]-1&&(d.maObv=n/i[0],n-=null!==(u=r[a-(i[0]-1)].obv)&&void 0!==u?u:0),r.push(d)})),r}},{name:"PVT",shortName:"PVT",figures:[{key:"pvt",title:"PVT: ",type:"line"}],calc:function(t){var e=0;return t.map((function(i,n){var o,r,a={},s=i.close,l=null!==(o=i.volume)&&void 0!==o?o:1,c=(null!==(r=t[n-1])&&void 0!==r?r:i).close,u=0,h=c*l;return 0!==h&&(u=(s-c)/h),e+=u,a.pvt=e,a}))}},{name:"PSY",shortName:"PSY",calcParams:[12,6],figures:[{key:"psy",title:"PSY: ",type:"line"},{key:"maPsy",title:"MAPSY: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=0,r=[],a=[];return t.forEach((function(e,s){var l,c,u={},h=(null!==(l=t[s-1])&&void 0!==l?l:e).close,d=e.close-h>0?1:0;r.push(d),n+=d,s>=i[0]-1&&(u.psy=n/i[0]*100,o+=u.psy,s>=i[0]+i[1]-2&&(u.maPsy=o/i[1],o-=null!==(c=a[s-(i[1]-1)].psy)&&void 0!==c?c:0),n-=r[s-(i[0]-1)]),a.push(u)})),a}},{name:"ROC",shortName:"ROC",calcParams:[12,6],figures:[{key:"roc",title:"ROC: ",type:"line"},{key:"maRoc",title:"MAROC: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=[],o=0;return t.forEach((function(e,r){var a,s,l={};if(r>=i[0]-1){var c=e.close,u=(null!==(a=t[r-i[0]])&&void 0!==a?a:t[r-(i[0]-1)]).close;l.roc=0!==u?(c-u)/u*100:0,o+=l.roc,r>=i[0]-1+i[1]-1&&(l.maRoc=o/i[1],o-=null!==(s=n[r-(i[1]-1)].roc)&&void 0!==s?s:0)}n.push(l)})),n}},Bt,Ot,Vt,Nt,{name:"TRIX",shortName:"TRIX",calcParams:[12,9],figures:[{key:"trix",title:"TRIX: ",type:"line"},{key:"maTrix",title:"MATRIX: ",type:"line"}],calc:function(t,e){var i,n,o,r=e.calcParams,a=0,s=0,l=0,c=0,u=[];return t.forEach((function(t,e){var h,d={},p=t.close;if(a+=p,e>=r[0]-1&&(i=e>r[0]-1?(2*p+(r[0]-1)*i)/(r[0]+1):a/r[0],s+=i,e>=2*r[0]-2&&(n=e>2*r[0]-2?(2*i+(r[0]-1)*n)/(r[0]+1):s/r[0],l+=n,e>=3*r[0]-3))){var g=void 0,v=0;e>3*r[0]-3?v=((g=(2*n+(r[0]-1)*o)/(r[0]+1))-o)/o*100:g=l/r[0],o=g,d.trix=v,c+=v,e>=3*r[0]+r[1]-4&&(d.maTrix=c/r[1],c-=null!==(h=u[e-(r[1]-1)].trix)&&void 0!==h?h:0)}u.push(d)})),u}},zt,{name:"VR",shortName:"VR",calcParams:[26,6],figures:[{key:"vr",title:"VR: ",type:"line"},{key:"maVr",title:"MAVR: ",type:"line"}],calc:function(t,e){var i=e.calcParams,n=0,o=0,r=0,a=0,s=[];return t.forEach((function(e,l){var c,u,h,d,p,g={},v=e.close,f=(null!==(c=t[l-1])&&void 0!==c?c:e).close,y=null!==(u=e.volume)&&void 0!==u?u:0;if(v>f?n+=y:v<f?o+=y:r+=y,l>=i[0]-1){var m=r/2;g.vr=o+m===0?0:(n+m)/(o+m)*100,a+=g.vr,l>=i[0]+i[1]-2&&(g.maVr=a/i[1],a-=null!==(h=s[l-(i[1]-1)].vr)&&void 0!==h?h:0);var _=t[l-(i[0]-1)],x=null!==(d=t[l-i[0]])&&void 0!==d?d:_,S=_.close,C=null!==(p=_.volume)&&void 0!==p?p:0;S>x.close?n-=C:S<x.close?o-=C:r-=C}s.push(g)})),s}},Yt];function Gt(t){var e;return null!==(e=Ht[t])&&void 0!==e?e:null}Xt.forEach((function(t){Ht[t.name]=ot.extend(t)}));var jt=function(){function e(t){this._instances=new Map,this._chartStore=t}return e.prototype._overrideInstance=function(t,e){var i=e.shortName,n=e.series,o=e.calcParams,r=e.precision,a=e.figures,s=e.minValue,l=e.maxValue,c=e.shouldOhlc,u=e.shouldFormatBigNumber,h=e.visible,d=e.zLevel,p=e.styles,g=e.extendData,v=e.regenerateFigures,f=e.createTooltipDataSource,y=e.draw,m=e.calc,_=!1;W(i)&&t.setShortName(i)&&(_=!0),V(n)&&t.setSeries(n)&&(_=!0);var x=!1;L(o)&&t.setCalcParams(o)&&(_=!0,x=!0),L(a)&&t.setFigures(a)&&(_=!0,x=!0),void 0!==s&&t.setMinValue(s)&&(_=!0),void 0!==l&&t.setMinValue(l)&&(_=!0),O(r)&&t.setPrecision(r)&&(_=!0),N(c)&&t.setShouldOhlc(c)&&(_=!0),N(u)&&t.setShouldFormatBigNumber(u)&&(_=!0),N(h)&&t.setVisible(h)&&(_=!0);var S=!1;return O(d)&&t.setZLevel(d)&&(_=!0,S=!0),V(p)&&t.setStyles(p)&&(_=!0),void 0!==g&&t.setExtendData(g)&&(_=!0,x=!0),void 0!==v&&t.setRegenerateFigures(v)&&(_=!0),void 0!==f&&t.setCreateTooltipDataSource(f)&&(_=!0),void 0!==y&&t.setDraw(y)&&(_=!0),R(m)&&(t.calc=m,x=!0),[_,x,S]},e.prototype._sort=function(t){var e;W(t)?null===(e=this._instances.get(t))||void 0===e||e.sort((function(t,e){return t.zLevel-e.zLevel})):this._instances.forEach((function(t){t.sort((function(t,e){return t.zLevel-e.zLevel}))}))},e.prototype.addInstance=function(t,e,i){return p(this,void 0,void 0,(function(){var n,o,r,a;return g(this,(function(s){switch(s.label){case 0:return n=t.name,V(o=this._instances.get(e))?V(o.find((function(t){return t.name===n})))?[4,Promise.reject(new Error("Duplicate indicators."))]:[3,2]:[3,2];case 1:case 3:return[2,s.sent()];case 2:return V(o)||(o=[]),r=Gt(n),a=new r,this.synchronizeSeriesPrecision(a),this._overrideInstance(a,t),i||(o=[]),o.push(a),this._instances.set(e,o),this._sort(e),[4,a.calcIndicator(this._chartStore.getDataList())]}}))}))},e.prototype.getInstances=function(t){var e;return null!==(e=this._instances.get(t))&&void 0!==e?e:[]},e.prototype.removeInstance=function(t,e){var i,n=!1,o=this._instances.get(t);if(V(o)){if(W(e)){var r=o.findIndex((function(t){return t.name===e}));r>-1&&(o.splice(r,1),n=!0)}else this._instances.set(t,[]),n=!0;0===(null===(i=this._instances.get(t))||void 0===i?void 0:i.length)&&this._instances.delete(t)}return n},e.prototype.hasInstances=function(t){return this._instances.has(t)},e.prototype.calcInstance=function(t,e){return p(this,void 0,void 0,(function(){var i,n,o,r=this;return g(this,(function(a){switch(a.label){case 0:return i=[],W(t)?W(e)?V(n=this._instances.get(e))&&V(o=n.find((function(e){return e.name===t})))&&i.push(o.calcIndicator(this._chartStore.getDataList())):this._instances.forEach((function(e){var n=e.find((function(e){return e.name===t}));V(n)&&i.push(n.calcIndicator(r._chartStore.getDataList()))})):this._instances.forEach((function(t){t.forEach((function(t){i.push(t.calcIndicator(r._chartStore.getDataList()))}))})),[4,Promise.all(i)];case 1:return[2,a.sent().includes(!0)]}}))}))},e.prototype.getInstanceByPaneId=function(t,e){var i,n,o=function(t){var e=new Map;return t.forEach((function(t){e.set(t.name,t)})),e};if(W(t)){var r=null!==(i=this._instances.get(t))&&void 0!==i?i:[];return W(e)?null!==(n=null==r?void 0:r.find((function(t){return t.name===e})))&&void 0!==n?n:null:o(r)}var a=new Map;return this._instances.forEach((function(t,e){a.set(e,o(t))})),a},e.prototype.synchronizeSeriesPrecision=function(e){var i=this._chartStore.getPrecision(),n=i.price,o=i.volume,r=function(e){switch(e.series){case t.IndicatorSeries.Price:e.setPrecision(n,!0);break;case t.IndicatorSeries.Volume:e.setPrecision(o,!0)}};V(e)?r(e):this._instances.forEach((function(t){t.forEach((function(t){r(t)}))}))},e.prototype.override=function(t,e){return p(this,void 0,void 0,(function(){var i,n,o,r,a,s,l,c=this;return g(this,(function(u){switch(u.label){case 0:return i=t.name,n=new Map,null!==e?V(o=this._instances.get(e))&&n.set(e,o):n=this._instances,r=!1,a=[],s=!1,n.forEach((function(e){var n=e.find((function(t){return t.name===i}));if(V(n)){var o=c._overrideInstance(n,t);o[2]&&(s=!0),o[1]?a.push(n.calcIndicator(c._chartStore.getDataList())):o[0]&&(r=!0)}})),s&&this._sort(),[4,Promise.all(a)];case 1:return l=u.sent(),[2,[r,l.includes(!0)]]}}))}))},e}(),Kt=function(){function t(t){this._crosshair={},this._activeIcon=null,this._chartStore=t}return t.prototype.setCrosshair=function(t,e){var i,n,o=this._chartStore.getDataList(),r=null!=t?t:{},a=o[n=O(r.x)?(i=this._chartStore.getTimeScaleStore().coordinateToDataIndex(r.x))<0?0:i>o.length-1?o.length-1:i:i=o.length-1],s=this._chartStore.getTimeScaleStore().dataIndexToCoordinate(i),l=this._crosshair.x,c=this._crosshair.y,u=this._crosshair.paneId;this._crosshair=d(d({},r),{realX:s,kLineData:a,realDataIndex:i,dataIndex:n}),l===r.x&&c===r.y&&u===r.paneId||(null!==a&&this._chartStore.getChart().crosshairChange(this._crosshair),null!=e&&e||this._chartStore.getChart().updatePane(1))},t.prototype.recalculateCrosshair=function(t){this.setCrosshair(this._crosshair,t)},t.prototype.getCrosshair=function(){return this._crosshair},t.prototype.setActiveIcon=function(t){this._activeIcon=null!=t?t:null},t.prototype.getActiveIcon=function(){return this._activeIcon},t.prototype.clear=function(){this.setCrosshair({},!0),this.setActiveIcon()},t}(),Zt={name:"fibonacciLine",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e,i=t.coordinates,n=t.bounding,o=t.overlay,r=t.precision,a=t.thousandsSeparator,s=t.decimalFoldThreshold,l=t.yAxis,c=o.points;if(i.length>0){var u=null===(e=null==l?void 0:l.isInCandle())||void 0===e||e?r.price:r.excludePriceVolumeMax,h=[],d=[],p=n.width;if(i.length>1&&O(c[0].value)&&O(c[1].value)){var g=i[0].y-i[1].y,v=c[0].value-c[1].value;[1,.786,.618,.5,.382,.236,0].forEach((function(t){var e,n=i[1].y+g*t,o=q(U(((null!==(e=c[1].value)&&void 0!==e?e:0)+v*t).toFixed(u),a),s);h.push({coordinates:[{x:0,y:n},{x:p,y:n}]}),d.push({x:0,y:n,text:"".concat(o," (").concat((100*t).toFixed(1),"%)"),baseline:"bottom"})}))}return[{type:"line",attrs:h},{type:"text",isCheckEvent:!1,attrs:d}]}return[]}},Ut={name:"horizontalRayLine",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates,i=t.bounding,n={x:0,y:e[0].y};return V(e[1])&&e[0].x<e[1].x&&(n.x=i.width),[{type:"line",attrs:{coordinates:[e[0],n]}}]},performEventPressedMove:function(t){var e=t.points,i=t.performPoint;e[0].value=i.value,e[1].value=i.value},performEventMoveForDrawing:function(t){var e=t.currentStep,i=t.points,n=t.performPoint;2===e&&(i[0].value=n.value)}},qt=function(){function t(){this._children=[],this._callbacks=new Map}return t.prototype.registerEvent=function(t,e){return this._callbacks.set(t,e),this},t.prototype.onEvent=function(t,e,i){var n=this._callbacks.get(t);return!(!V(n)||!this.checkEventOn(e))&&n(e,i)},t.prototype.checkEventOn=function(t){var e,i;try{for(var n=v(this._children),o=n.next();!o.done;o=n.next()){if(o.value.checkEventOn(t))return!0}}catch(t){e={error:t}}finally{try{o&&!o.done&&(i=n.return)&&i.call(n)}finally{if(e)throw e.error}}return!1},t.prototype.dispatchEvent=function(t,e,i){var n=this._children.length-1;if(n>-1)for(var o=n;o>-1;o--)if(this._children[o].dispatchEvent(t,e,i))return!0;return this.onEvent(t,e,i)},t.prototype.addChild=function(t){return this._children.push(t),this},t.prototype.clear=function(){this._children=[]},t}(),$t=function(t){function e(e){var i=t.call(this)||this;return i.attrs=e.attrs,i.styles=e.styles,i}return i(e,t),e.prototype.checkEventOn=function(t){return this.checkEventOnImp(t,this.attrs,this.styles)},e.prototype.setAttrs=function(t){return this.attrs=t,this},e.prototype.setStyles=function(t){return this.styles=t,this},e.prototype.draw=function(t){this.drawImp(t,this.attrs,this.styles)},e.extend=function(t){var n=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.checkEventOnImp=function(e,i,n){return t.checkEventOn(e,i,n)},n.prototype.drawImp=function(e,i,n){t.draw(e,i,n)},n}(e);return n},e}(qt);function Qt(t,e){var i=[];i=i.concat(e);for(var n=0;n<i.length;n++){var o=i[n].coordinates;if(o.length>1)for(var r=1;r<o.length;r++){var a=o[r-1],s=o[r];if(a.x===s.x){if(Math.abs(a.y-t.y)+Math.abs(s.y-t.y)-Math.abs(a.y-s.y)<4&&Math.abs(t.x-a.x)<2)return!0}else{var l=ee(a,s),c=Jt(l,t),u=Math.abs(c-t.y);if(Math.abs(a.x-t.x)+Math.abs(s.x-t.x)-Math.abs(a.x-s.x)<4&&u*u/(l[0]*l[0]+1)<4)return!0}}}return!1}function Jt(t,e){return null!==t?e.x*t[0]+t[1]:e.y}function te(t,e,i){return Jt(ee(t,e),i)}function ee(t,e){var i=t.x-e.x;if(0!==i){var n=(t.y-e.y)/i;return[n,t.y-n*t.x]}return null}function ie(t,e,i){var n=e.length,o=O(i)?i>0&&i<1?i:0:i?.5:0;if(o>0&&n>2){for(var r=e[0].x,a=e[0].y,s=1;s<n-1;s++){var l=e[s-1],c=e[s],u=e[s+1],h=c.x-l.x,d=c.y-l.y,p=u.x-c.x,g=u.y-c.y,v=u.x-l.x,f=u.y-l.y,y=Math.sqrt(h*h+d*d),m=Math.sqrt(p*p+g*g),_=m/(m+y),x=c.x+v*o*_,S=c.y+f*o*_;x=Math.min(x,Math.max(u.x,c.x)),S=Math.min(S,Math.max(u.y,c.y)),x=Math.max(x,Math.min(u.x,c.x)),S=Math.max(S,Math.min(u.y,c.y)),v=x-c.x,f=S-c.y;var C=c.x-v*y/m,b=c.y-f*y/m;C=Math.min(C,Math.max(l.x,c.x)),b=Math.min(b,Math.max(l.y,c.y)),C=Math.max(C,Math.min(l.x,c.x)),b=Math.max(b,Math.min(l.y,c.y)),v=c.x-C,f=c.y-b,x=c.x+v*m/y,S=c.y+f*m/y,t.bezierCurveTo(r,a,C,b,c.x,c.y),r=x,a=S}var T=e[n-1];t.bezierCurveTo(r,a,T.x,T.y,T.x,T.y)}else for(s=1;s<n;s++)t.lineTo(e[s].x,e[s].y)}function ne(e,i,n){var o=[];o=o.concat(i);var r=n.style,a=void 0===r?t.LineType.Solid:r,s=n.smooth,l=void 0!==s&&s,c=n.size,u=void 0===c?1:c,h=n.color,d=void 0===h?"currentColor":h,p=n.dashedValue,g=void 0===p?[2,2]:p;e.lineWidth=u,e.strokeStyle=d,a===t.LineType.Dashed?e.setLineDash(g):e.setLineDash([]);var v=u%2==1?.5:0;o.forEach((function(t){var i=t.coordinates;i.length>1&&(2!==i.length||i[0].x!==i[1].x&&i[0].y!==i[1].y?(e.save(),u%2==1&&e.translate(.5,.5),e.beginPath(),e.moveTo(i[0].x,i[0].y),ie(e,i,l),e.stroke(),e.closePath(),e.restore()):(e.beginPath(),i[0].x===i[1].x?(e.moveTo(i[0].x+v,i[0].y),e.lineTo(i[1].x+v,i[1].y)):(e.moveTo(i[0].x,i[0].y+v),e.lineTo(i[1].x,i[1].y+v)),e.stroke(),e.closePath()))}))}var oe={name:"line",checkEventOn:Qt,draw:function(t,e,i){ne(t,e,i)}};function re(t,e,i){var n=null!=i?i:0,o=[];if(t.length>1)if(t[0].x===t[1].x){var r=e.height;if(o.push({coordinates:[{x:t[0].x,y:0},{x:t[0].x,y:r}]}),t.length>2){o.push({coordinates:[{x:t[2].x,y:0},{x:t[2].x,y:r}]});for(var a=t[0].x-t[2].x,s=0;s<n;s++){var l=a*(s+1);o.push({coordinates:[{x:t[0].x+l,y:0},{x:t[0].x+l,y:r}]})}}}else{var c=e.width,u=ee(t[0],t[1]),h=u[0],d=u[1];if(o.push({coordinates:[{x:0,y:0*h+d},{x:c,y:c*h+d}]}),t.length>2){var p=t[2].y-h*t[2].x;o.push({coordinates:[{x:0,y:0*h+p},{x:c,y:c*h+p}]});for(a=d-p,s=0;s<n;s++){var g=d+a*(s+1);o.push({coordinates:[{x:0,y:0*h+g},{x:c,y:c*h+g}]})}}}return o}var ae={name:"parallelStraightLine",totalStep:4,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){return[{type:"line",attrs:re(t.coordinates,t.bounding)}]}},se={name:"priceChannelLine",totalStep:4,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){return[{type:"line",attrs:re(t.coordinates,t.bounding,1)}]}},le={name:"priceLine",totalStep:2,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e,i=t.coordinates,n=t.bounding,o=t.precision,r=t.overlay,a=t.thousandsSeparator,s=t.decimalFoldThreshold,l=t.yAxis,c=r.points[0].value,u=void 0===c?0:c,h=null===(e=null==l?void 0:l.isInCandle())||void 0===e||e?o.price:o.excludePriceVolumeMax;return[{type:"line",attrs:{coordinates:[i[0],{x:n.width,y:i[0].y}]}},{type:"text",ignoreEvent:!0,attrs:{x:i[0].x,y:i[0].y,text:q(U(u.toFixed(h),a),s),baseline:"bottom"}}]}};function ce(t,e){if(t.length>1){var i=void 0;return i=t[0].x===t[1].x&&t[0].y!==t[1].y?t[0].y<t[1].y?{x:t[0].x,y:e.height}:{x:t[0].x,y:0}:t[0].x>t[1].x?{x:0,y:te(t[0],t[1],{x:0,y:t[0].y})}:{x:e.width,y:te(t[0],t[1],{x:e.width,y:t[0].y})},{coordinates:[t[0],i]}}return[]}var ue={name:"rayLine",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){return[{type:"line",attrs:ce(t.coordinates,t.bounding)}]}},he={name:"straightLine",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates,i=t.bounding;return 2===e.length?e[0].x===e[1].x?[{type:"line",attrs:{coordinates:[{x:e[0].x,y:0},{x:e[0].x,y:i.height}]}}]:[{type:"line",attrs:{coordinates:[{x:0,y:te(e[0],e[1],{x:0,y:e[0].y})},{x:i.width,y:te(e[0],e[1],{x:i.width,y:e[0].y})}]}}]:[]}},de={name:"simpleAnnotation",totalStep:2,styles:{line:{style:t.LineType.Dashed}},createPointFigures:function(t){var e,i,n=t.overlay,o=t.coordinates;V(n.extendData)&&(i=R(n.extendData)?n.extendData(n):null!==(e=n.extendData)&&void 0!==e?e:"");var r=o[0].x,a=o[0].y-6,s=a-50,l=s-5;return[{type:"line",attrs:{coordinates:[{x:r,y:a},{x:r,y:s}]},ignoreEvent:!0},{type:"polygon",attrs:{coordinates:[{x:r,y:s},{x:r-4,y:l},{x:r+4,y:l}]},ignoreEvent:!0},{type:"text",attrs:{x:r,y:l,text:null!=i?i:"",align:"center",baseline:"bottom"},ignoreEvent:!0}]}},pe={name:"simpleTag",totalStep:2,styles:{line:{style:t.LineType.Dashed}},createPointFigures:function(t){var e=t.bounding,i=t.coordinates;return{type:"line",attrs:{coordinates:[{x:0,y:i[0].y},{x:e.width,y:i[0].y}]},ignoreEvent:!0}},createYAxisFigures:function(t){var e,i,n,o,r,a=t.overlay,s=t.coordinates,l=t.bounding,c=t.yAxis,u=t.precision;return null!==(e=null==c?void 0:c.isFromZero())&&void 0!==e&&e?(n="left",o=0):(n="right",o=l.width),V(a.extendData)&&(r=R(a.extendData)?a.extendData(a):null!==(i=a.extendData)&&void 0!==i?i:""),!V(r)&&O(a.points[0].value)&&(r=K(a.points[0].value,u.price)),{type:"text",attrs:{x:o,y:s[0].y,text:null!=r?r:"",align:n,baseline:"middle"}}}},ge={};function ve(t){var e;return null!==(e=ge[t])&&void 0!==e?e:null}[Zt,Ut,{name:"horizontalSegment",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates,i=[];return 2===e.length&&i.push({coordinates:e}),[{type:"line",attrs:i}]},performEventPressedMove:function(t){var e=t.points,i=t.performPoint;e[0].value=i.value,e[1].value=i.value},performEventMoveForDrawing:function(t){var e=t.currentStep,i=t.points,n=t.performPoint;2===e&&(i[0].value=n.value)}},{name:"horizontalStraightLine",totalStep:2,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates,i=t.bounding;return[{type:"line",attrs:{coordinates:[{x:0,y:e[0].y},{x:i.width,y:e[0].y}]}}]}},ae,se,le,ue,{name:"segment",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates;return 2===e.length?[{type:"line",attrs:{coordinates:e}}]:[]}},he,{name:"verticalRayLine",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates,i=t.bounding;if(2===e.length){var n={x:e[0].x,y:0};return e[0].y<e[1].y&&(n.y=i.height),[{type:"line",attrs:{coordinates:[e[0],n]}}]}return[]},performEventPressedMove:function(t){var e=t.points,i=t.performPoint;e[0].timestamp=i.timestamp,e[0].dataIndex=i.dataIndex,e[1].timestamp=i.timestamp,e[1].dataIndex=i.dataIndex},performEventMoveForDrawing:function(t){var e=t.currentStep,i=t.points,n=t.performPoint;2===e&&(i[0].timestamp=n.timestamp,i[0].dataIndex=n.dataIndex)}},{name:"verticalSegment",totalStep:3,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates;return 2===e.length?[{type:"line",attrs:{coordinates:e}}]:[]},performEventPressedMove:function(t){var e=t.points,i=t.performPoint;e[0].timestamp=i.timestamp,e[0].dataIndex=i.dataIndex,e[1].timestamp=i.timestamp,e[1].dataIndex=i.dataIndex},performEventMoveForDrawing:function(t){var e=t.currentStep,i=t.points,n=t.performPoint;2===e&&(i[0].timestamp=n.timestamp,i[0].dataIndex=n.dataIndex)}},{name:"verticalStraightLine",totalStep:2,needDefaultPointFigure:!0,needDefaultXAxisFigure:!0,needDefaultYAxisFigure:!0,createPointFigures:function(t){var e=t.coordinates,i=t.bounding;return[{type:"line",attrs:{coordinates:[{x:e[0].x,y:0},{x:e[0].x,y:i.height}]}}]}},de,pe].forEach((function(t){ge[t.name]=lt.extend(t)}));var fe="candle_pane",ye="indicator_pane_",me="x_axis_pane",_e=function(){function t(t){this._instances=new Map,this._progressInstanceInfo=null,this._pressedInstanceInfo={paneId:"",instance:null,figureType:0,figureKey:"",figureIndex:-1,attrsIndex:-1},this._hoverInstanceInfo={paneId:"",instance:null,figureType:0,figureKey:"",figureIndex:-1,attrsIndex:-1},this._clickInstanceInfo={paneId:"",instance:null,figureType:0,figureKey:"",figureIndex:-1,attrsIndex:-1},this._chartStore=t}return t.prototype._overrideInstance=function(t,e){var i=e.id,n=e.groupId,o=e.points,r=e.styles,a=e.lock,s=e.visible,l=e.zLevel,c=e.mode,u=e.modeSensitivity,h=e.extendData,d=e.onDrawStart,p=e.onDrawing,g=e.onDrawEnd,v=e.onClick,f=e.onDoubleClick,y=e.onRightClick,m=e.onPressedMoveStart,_=e.onPressedMoving,x=e.onPressedMoveEnd,S=e.onMouseEnter,C=e.onMouseLeave,b=e.onRemoved,T=e.onSelected,w=e.onDeselected,E=!1,I=!1;return W(i)&&t.setId(i),W(n)&&t.setGroupId(n),L(o)&&t.setPoints(o)&&(E=!0),V(r)&&t.setStyles(r)&&(E=!0),N(a)&&t.setLock(a),N(s)&&t.setVisible(s)&&(E=!0),O(l)&&t.setZLevel(l)&&(E=!0,I=!0),V(c)&&t.setMode(c),O(u)&&t.setModeSensitivity(u),void 0!==h&&t.setExtendData(h)&&(E=!0),void 0!==d&&t.setOnDrawStartCallback(d),void 0!==p&&t.setOnDrawingCallback(p),void 0!==g&&t.setOnDrawEndCallback(g),void 0!==v&&t.setOnClickCallback(v),void 0!==f&&t.setOnDoubleClickCallback(f),void 0!==y&&t.setOnRightClickCallback(y),void 0!==m&&t.setOnPressedMoveStartCallback(m),void 0!==_&&t.setOnPressedMovingCallback(_),void 0!==x&&t.setOnPressedMoveEndCallback(x),void 0!==S&&t.setOnMouseEnterCallback(S),void 0!==C&&t.setOnMouseLeaveCallback(C),void 0!==b&&t.setOnRemovedCallback(b),void 0!==T&&t.setOnSelectedCallback(T),void 0!==w&&t.setOnDeselectedCallback(w),[E,I]},t.prototype.getInstanceById=function(t){var e,i;try{for(var n=v(this._instances),o=n.next();!o.done;o=n.next()){var r=o.value[1].find((function(e){return e.id===t}));if(V(r))return r}}catch(t){e={error:t}}finally{try{o&&!o.done&&(i=n.return)&&i.call(n)}finally{if(e)throw e.error}}return null!==this._progressInstanceInfo&&this._progressInstanceInfo.instance.id===t?this._progressInstanceInfo.instance:null},t.prototype._sort=function(t){var e;W(t)?null===(e=this._instances.get(t))||void 0===e||e.sort((function(t,e){return t.zLevel-e.zLevel})):this._instances.forEach((function(t){t.sort((function(t,e){return t.zLevel-e.zLevel}))}))},t.prototype.addInstances=function(t,e,i){var n=this,o=t.map((function(t){var o,r,a,s,l=null!==(o=t.id)&&void 0!==o?o:vt("overlay_");if(null===n.getInstanceById(l)){var c=ve(t.name);if(null!==c){var u=new c;u.setPaneId(e);var h=null!==(r=t.groupId)&&void 0!==r?r:l;return t.id=l,t.groupId=h,n._overrideInstance(u,t),u.isDrawing()?n._progressInstanceInfo={paneId:e,instance:u,appointPaneFlag:i}:(n._instances.has(e)||n._instances.set(e,[]),null===(a=n._instances.get(e))||void 0===a||a.push(u)),u.isStart()&&(null===(s=u.onDrawStart)||void 0===s||s.call(u,{overlay:u})),l}}return null}));if(o.some((function(t){return null!==t}))){this._sort();var r=this._chartStore.getChart();r.updatePane(1,e),r.updatePane(1,me)}return o},t.prototype.getProgressInstanceInfo=function(){return this._progressInstanceInfo},t.prototype.progressInstanceComplete=function(){var t;if(null!==this._progressInstanceInfo){var e=this._progressInstanceInfo,i=e.instance,n=e.paneId;i.isDrawing()||(this._instances.has(n)||this._instances.set(n,[]),null===(t=this._instances.get(n))||void 0===t||t.push(i),this._sort(n),this._progressInstanceInfo=null)}},t.prototype.updateProgressInstanceInfo=function(t,e){null!==this._progressInstanceInfo&&(N(e)&&e&&(this._progressInstanceInfo.appointPaneFlag=e),this._progressInstanceInfo.paneId=t,this._progressInstanceInfo.instance.setPaneId(t))},t.prototype.getInstances=function(t){var e;if(!W(t)){var i=[];return this._instances.forEach((function(t){i=i.concat(t)})),i}return null!==(e=this._instances.get(t))&&void 0!==e?e:[]},t.prototype.override=function(t){var e=this,i=t.id,n=t.groupId,o=t.name,r=!1,a=!1,s=function(i){var n=e._overrideInstance(i,t);n[0]&&(r=!0),n[1]&&(a=!0)};if(W(i)){var l=this.getInstanceById(i);null!==l&&s(l)}else{var c=W(o),u=W(n);if(this._instances.forEach((function(t){t.forEach((function(t){(c&&t.name===o||u&&t.groupId===n||!c&&!u)&&s(t)}))})),null!==this._progressInstanceInfo){var h=this._progressInstanceInfo.instance;(c&&h.name===o||u&&h.groupId===n||!c&&!u)&&s(h)}}a&&this._sort(),r&&this._chartStore.getChart().updatePane(1)},t.prototype.removeInstance=function(t){var e,i,n,o=function(t,e){if(W(t.id)){if(e.id!==t.id)return!1}else if(W(t.groupId)){if(e.groupId!==t.groupId)return!1}else if(W(t.name)&&e.name!==t.name)return!1;return!0},r=[],a=V(t);if(null!==this._progressInstanceInfo){var s=this._progressInstanceInfo.instance;(!a||a&&o(t,s))&&(r.push(this._progressInstanceInfo.paneId),null===(n=s.onRemoved)||void 0===n||n.call(s,{overlay:s}),this._progressInstanceInfo=null)}if(a){var l=new Map,c=function(e){var i=e[1].filter((function(i){var n;return!o(t,i)||(r.includes(e[0])||r.push(e[0]),null===(n=i.onRemoved)||void 0===n||n.call(i,{overlay:i}),!1)}));i.length>0&&l.set(e[0],i)};try{for(var u=v(this._instances),h=u.next();!h.done;h=u.next()){c(h.value)}}catch(t){e={error:t}}finally{try{h&&!h.done&&(i=u.return)&&i.call(u)}finally{if(e)throw e.error}}this._instances=l}else this._instances.forEach((function(t,e){r.push(e),t.forEach((function(t){var e;null===(e=t.onRemoved)||void 0===e||e.call(t,{overlay:t})}))})),this._instances.clear();if(r.length>0){var d=this._chartStore.getChart();r.forEach((function(t){d.updatePane(1,t)})),d.updatePane(1,me)}},t.prototype.setPressedInstanceInfo=function(t){this._pressedInstanceInfo=t},t.prototype.getPressedInstanceInfo=function(){return this._pressedInstanceInfo},t.prototype.updatePointPosition=function(t,e){if(t>0){var i=this._chartStore.getDataList();this._instances.forEach((function(n){n.forEach((function(n){n.points.forEach((function(n){if(!V(n.timestamp)&&V(n.dataIndex)){e===ht.Forward&&(n.dataIndex=n.dataIndex+t);var o=i[n.dataIndex];n.timestamp=null==o?void 0:o.timestamp}}))}))}))}},t.prototype.setHoverInstanceInfo=function(t,e){var i,n,o=this._hoverInstanceInfo,r=o.instance,a=o.figureType,s=o.figureKey,l=o.figureIndex;if(((null==r?void 0:r.id)!==(null===(i=t.instance)||void 0===i?void 0:i.id)||a!==t.figureType||l!==t.figureIndex)&&(this._hoverInstanceInfo=t,(null==r?void 0:r.id)!==(null===(n=t.instance)||void 0===n?void 0:n.id))){var c=!1,u=!1;null!==r&&(u=!0,R(r.onMouseLeave)&&(r.onMouseLeave(d({overlay:r,figureKey:s,figureIndex:l},e)),c=!0)),null!==t.instance&&(u=!0,t.instance.setZLevel(st),R(t.instance.onMouseEnter)&&(t.instance.onMouseEnter(d({overlay:t.instance,figureKey:t.figureKey,figureIndex:t.figureIndex},e)),c=!0)),u&&this._sort(),c||this._chartStore.getChart().updatePane(1)}},t.prototype.getHoverInstanceInfo=function(){return this._hoverInstanceInfo},t.prototype.setClickInstanceInfo=function(t,e){var i,n,o,r,a,s,l,c,u,h=this._clickInstanceInfo,p=h.paneId,g=h.instance,v=h.figureType,f=h.figureKey,y=h.figureIndex;if(null!==(n=null===(i=t.instance)||void 0===i?void 0:i.isDrawing())&&void 0!==n&&n||null===(r=null===(o=t.instance)||void 0===o?void 0:o.onClick)||void 0===r||r.call(o,d({overlay:t.instance,figureKey:t.figureKey,figureIndex:t.figureIndex},e)),((null==g?void 0:g.id)!==(null===(a=t.instance)||void 0===a?void 0:a.id)||v!==t.figureType||y!==t.figureIndex)&&(this._clickInstanceInfo=t,(null==g?void 0:g.id)!==(null===(s=t.instance)||void 0===s?void 0:s.id))){null===(l=null==g?void 0:g.onDeselected)||void 0===l||l.call(g,d({overlay:g,figureKey:f,figureIndex:y},e)),null===(u=null===(c=t.instance)||void 0===c?void 0:c.onSelected)||void 0===u||u.call(c,d({overlay:t.instance,figureKey:t.figureKey,figureIndex:t.figureIndex},e));var m=this._chartStore.getChart();m.updatePane(1,t.paneId),p!==t.paneId&&m.updatePane(1,p),m.updatePane(1,me)}},t.prototype.getClickInstanceInfo=function(){return this._clickInstanceInfo},t.prototype.isEmpty=function(){return 0===this._instances.size&&null===this._progressInstanceInfo},t.prototype.isDrawing=function(){var t,e;return null!==this._progressInstanceInfo&&null!==(e=null===(t=this._progressInstanceInfo)||void 0===t?void 0:t.instance.isDrawing())&&void 0!==e&&e},t}(),xe=function(){function t(){this._actions=new Map}return t.prototype.execute=function(t,e){var i;null===(i=this._actions.get(t))||void 0===i||i.execute(e)},t.prototype.subscribe=function(t,e){var i;this._actions.has(t)||this._actions.set(t,new et),null===(i=this._actions.get(t))||void 0===i||i.subscribe(e)},t.prototype.unsubscribe=function(t,e){var i=this._actions.get(t);V(i)&&(i.unsubscribe(e),i.isEmpty()&&this._actions.delete(t))},t.prototype.has=function(t){var e=this._actions.get(t);return V(e)&&!e.isEmpty()},t}(),Se={light:{grid:{horizontal:{color:"#EDEDED"},vertical:{color:"#EDEDED"}},candle:{priceMark:{high:{color:"#76808F"},low:{color:"#76808F"}},tooltip:{rect:{color:"#FEFEFE",borderColor:"#F2F3F5"},text:{color:"#76808F"}}},indicator:{tooltip:{text:{color:"#76808F"}}},xAxis:{axisLine:{color:"#DDDDDD"},tickText:{color:"#76808F"},tickLine:{color:"#DDDDDD"}},yAxis:{axisLine:{color:"#DDDDDD"},tickText:{color:"#76808F"},tickLine:{color:"#DDDDDD"}},separator:{color:"#DDDDDD"},crosshair:{horizontal:{line:{color:"#76808F"},text:{borderColor:"#686D76",backgroundColor:"#686D76"}},vertical:{line:{color:"#76808F"},text:{borderColor:"#686D76",backgroundColor:"#686D76"}}}},dark:{grid:{horizontal:{color:"#292929"},vertical:{color:"#292929"}},candle:{priceMark:{high:{color:"#929AA5"},low:{color:"#929AA5"}},tooltip:{rect:{color:"rgba(10, 10, 10, .6)",borderColor:"rgba(10, 10, 10, .6)"},text:{color:"#929AA5"}}},indicator:{tooltip:{text:{color:"#929AA5"}}},xAxis:{axisLine:{color:"#333333"},tickText:{color:"#929AA5"},tickLine:{color:"#333333"}},yAxis:{axisLine:{color:"#333333"},tickText:{color:"#929AA5"},tickLine:{color:"#333333"}},separator:{color:"#333333"},crosshair:{horizontal:{line:{color:"#929AA5"},text:{borderColor:"#373a40",backgroundColor:"#373a40"}},vertical:{line:{color:"#929AA5"},text:{borderColor:"#373a40",backgroundColor:"#373a40"}}}}};function Ce(t){var e;return null!==(e=Se[t])&&void 0!==e?e:null}var be=function(){function e(e,i){var n,o,r;this._styles={grid:P(),candle:(r={show:!0,color:w,textOffset:5,textSize:10,textFamily:"Helvetica Neue",textWeight:"normal"},{type:t.CandleType.CandleSolid,bar:{upColor:x,downColor:m,noChangeColor:C,upBorderColor:x,downBorderColor:m,noChangeBorderColor:C,upWickColor:x,downWickColor:m,noChangeWickColor:C},area:{lineSize:2,lineColor:T,smooth:!1,value:"close",backgroundColor:[{offset:0,color:I(.01)},{offset:1,color:I(.2)}],point:{show:!0,color:T,radius:4,rippleColor:I(.3),rippleRadius:8,animation:!0,animationDuration:1e3}},priceMark:{show:!0,high:d({},r),low:d({},r),last:{show:!0,upColor:x,downColor:m,noChangeColor:C,line:{show:!0,style:t.LineType.Dashed,dashedValue:[4,4],size:1},text:{show:!0,style:t.PolygonType.Fill,size:12,paddingLeft:4,paddingTop:4,paddingRight:4,paddingBottom:4,borderColor:"transparent",borderStyle:t.LineType.Solid,borderSize:0,borderDashedValue:[2,2],color:b,family:"Helvetica Neue",weight:"normal",borderRadius:2}}},tooltip:{offsetLeft:4,offsetTop:6,offsetRight:4,offsetBottom:6,showRule:t.TooltipShowRule.Always,showType:t.TooltipShowType.Standard,custom:[{title:"time",value:"{time}"},{title:"open",value:"{open}"},{title:"high",value:"{high}"},{title:"low",value:"{low}"},{title:"close",value:"{close}"},{title:"volume",value:"{volume}"}],defaultValue:"n/a",rect:{position:t.CandleTooltipRectPosition.Fixed,paddingLeft:4,paddingRight:4,paddingTop:4,paddingBottom:4,offsetLeft:4,offsetTop:4,offsetRight:4,offsetBottom:4,borderRadius:4,borderSize:1,borderColor:"#F2F3F5",color:"#FEFEFE"},text:{size:12,family:"Helvetica Neue",weight:"normal",color:w,marginLeft:8,marginTop:4,marginRight:8,marginBottom:4},icons:[]}}),indicator:(o=["#FF9600","#935EBD",T,"#E11D74","#01C5C4"].map((function(e){return{style:t.LineType.Solid,smooth:!1,size:1,dashedValue:[2,2],color:e}})),{ohlc:{upColor:S,downColor:_,noChangeColor:C},bars:[{style:t.PolygonType.Fill,borderStyle:t.LineType.Solid,borderSize:1,borderDashedValue:[2,2],upColor:S,downColor:_,noChangeColor:C}],lines:o,circles:[{style:t.PolygonType.Fill,borderStyle:t.LineType.Solid,borderSize:1,borderDashedValue:[2,2],upColor:S,downColor:_,noChangeColor:C}],lastValueMark:{show:!1,text:{show:!1,style:t.PolygonType.Fill,color:b,size:12,family:"Helvetica Neue",weight:"normal",borderStyle:t.LineType.Solid,borderColor:"transparent",borderSize:0,borderDashedValue:[2,2],paddingLeft:4,paddingTop:4,paddingRight:4,paddingBottom:4,borderRadius:2}},tooltip:{offsetLeft:4,offsetTop:6,offsetRight:4,offsetBottom:6,showRule:t.TooltipShowRule.Always,showType:t.TooltipShowType.Standard,showName:!0,showParams:!0,defaultValue:"n/a",text:{size:12,family:"Helvetica Neue",weight:"normal",color:w,marginLeft:8,marginTop:4,marginRight:8,marginBottom:4},icons:[]}}),xAxis:D(),yAxis:(n=D(),n.type=t.YAxisType.Normal,n.position=t.YAxisPosition.Right,n.inside=!1,n.reverse=!1,n),separator:{size:1,color:E,fill:!0,activeBackgroundColor:I(.08)},crosshair:M(),overlay:k()},this._customApi={formatDate:j,formatBigNumber:Z},this._locale="en-US",this._precision={price:2,volume:0},this._thousandsSeparator=",",this._decimalFoldThreshold=3,this._dataList=[],this._loadMoreCallback=null,this._loadDataCallback=null,this._loading=!0,this._forwardMore=!0,this._backwardMore=!0,this._timeScaleStore=new Tt(this),this._indicatorStore=new jt(this),this._overlayStore=new _e(this),this._tooltipStore=new Kt(this),this._actionStore=new xe,this._visibleDataList=[],this._chart=e,this.setOptions(i)}return e.prototype.adjustVisibleDataList=function(){this._visibleDataList=[];for(var t=this._timeScaleStore.getVisibleRange(),e=t.realFrom,i=t.realTo,n=e;n<i;n++){var o=this._dataList[n],r=this._timeScaleStore.dataIndexToCoordinate(n);this._visibleDataList.push({dataIndex:n,x:r,data:o})}},e.prototype.setOptions=function(t){var e,i,n,o;if(V(t)){var r=t.locale,a=t.timezone,s=t.styles,l=t.customApi,c=t.thousandsSeparator,u=t.decimalFoldThreshold;if(W(r)&&(this._locale=r),W(a)&&this._timeScaleStore.setTimezone(a),V(s)){var h=null;h=W(s)?Ce(s):s,A(this._styles,h),L(null===(i=null===(e=null==h?void 0:h.candle)||void 0===e?void 0:e.tooltip)||void 0===i?void 0:i.custom)&&(this._styles.candle.tooltip.custom=null===(o=null===(n=null==h?void 0:h.candle)||void 0===n?void 0:n.tooltip)||void 0===o?void 0:o.custom)}V(l)&&A(this._customApi,l),W(c)&&(this._thousandsSeparator=c),O(u)&&u>0&&(this._decimalFoldThreshold=u)}return this},e.prototype.getStyles=function(){return this._styles},e.prototype.getLocale=function(){return this._locale},e.prototype.getCustomApi=function(){return this._customApi},e.prototype.getThousandsSeparator=function(){return this._thousandsSeparator},e.prototype.getDecimalFoldThreshold=function(){return this._decimalFoldThreshold},e.prototype.getPrecision=function(){return this._precision},e.prototype.setPrecision=function(t){return this._precision=t,this._indicatorStore.synchronizeSeriesPrecision(),this},e.prototype.getDataList=function(){return this._dataList},e.prototype.getVisibleFirstData=function(){var t,e=this._timeScaleStore.getVisibleRange().from;return null!==(t=this._dataList[e])&&void 0!==t?t:null},e.prototype.getVisibleDataList=function(){return this._visibleDataList},e.prototype.addData=function(e,i,n){return p(this,void 0,void 0,(function(){var o,r,a,s,l,c,u;return g(this,(function(h){switch(h.label){case 0:if(o=!1,r=!1,a=0,L(e)){switch(a=e.length,i){case ht.Init:this.clear(),this._dataList=e,this._forwardMore=null==n||n,this._timeScaleStore.resetOffsetRightDistance(),r=!0;break;case ht.Backward:this._dataList=this._dataList.concat(e),this._backwardMore=null!=n&&n,r=a>0;break;case ht.Forward:this._dataList=e.concat(this._dataList),this._forwardMore=null!=n&&n,r=a>0}this._loading=!1,o=!0}else s=this._dataList.length,l=e.timestamp,c=G(this._dataList[s-1],"timestamp",0),l>c?(this._dataList.push(e),(u=this._timeScaleStore.getLastBarRightSideDiffBarCount())<0&&this._timeScaleStore.setLastBarRightSideDiffBarCount(--u),a=1,o=!0,r=!0):l===c&&(this._dataList[s-1]=e,o=!0,r=!0);if(!o)return[3,5];h.label=1;case 1:return h.trys.push([1,4,,5]),this._overlayStore.updatePointPosition(a,i),r?(this._timeScaleStore.adjustVisibleRange(),this._tooltipStore.recalculateCrosshair(!0),[4,this._indicatorStore.calcInstance()]):[3,3];case 2:h.sent(),this._chart.adjustPaneViewport(!1,!0,!0,!0),h.label=3;case 3:return this._actionStore.execute(t.ActionType.OnDataReady),[3,5];case 4:return h.sent(),[3,5];case 5:return[2]}}))}))},e.prototype.setLoadMoreCallback=function(t){this._loadMoreCallback=t},e.prototype.executeLoadMoreCallback=function(t){this._forwardMore&&!this._loading&&V(this._loadMoreCallback)&&(this._loading=!0,this._loadMoreCallback(t))},e.prototype.setLoadDataCallback=function(t){this._loadDataCallback=t},e.prototype.executeLoadDataCallback=function(t){var e=this;if(!this._loading&&V(this._loadDataCallback)&&(this._forwardMore&&t.type===ht.Forward||this._backwardMore&&t.type===ht.Backward)){this._loading=!0,this._loadDataCallback(d(d({},t),{callback:function(i,n){e.addData(i,t.type,n).then((function(){})).catch((function(){}))}}))}},e.prototype.clear=function(){this._forwardMore=!0,this._backwardMore=!0,this._loading=!0,this._dataList=[],this._visibleDataList=[],this._timeScaleStore.clear(),this._tooltipStore.clear()},e.prototype.getTimeScaleStore=function(){return this._timeScaleStore},e.prototype.getIndicatorStore=function(){return this._indicatorStore},e.prototype.getOverlayStore=function(){return this._overlayStore},e.prototype.getTooltipStore=function(){return this._tooltipStore},e.prototype.getActionStore=function(){return this._actionStore},e.prototype.getChart=function(){return this._chart},e}(),Te="main",we="xAxis",Ee="yAxis",Ie="separator";var Pe=function(){function t(t,e){var i=this;this._supportedDevicePixelContentBox=!1,this._width=0,this._height=0,this._pixelWidth=0,this._pixelHeight=0,this._nextPixelWidth=0,this._nextPixelHeight=0,this._requestAnimationId=-1,this._mediaQueryListener=function(){var t=$(i._element);i._nextPixelWidth=Math.round(i._element.clientWidth*t),i._nextPixelHeight=Math.round(i._element.clientHeight*t),i._resetPixelRatio()},this._listener=e,this._element=ft("canvas",t),this._ctx=this._element.getContext("2d",{willReadFrequently:!0}),function(){return p(this,void 0,void 0,(function(){return g(this,(function(t){switch(t.label){case 0:return[4,new Promise((function(t){var e=new ResizeObserver((function(i){t(i.every((function(t){return"devicePixelContentBoxSize"in t}))),e.disconnect()}));e.observe(document.body,{box:"device-pixel-content-box"})})).catch((function(){return!1}))];case 1:return[2,t.sent()]}}))}))}().then((function(t){i._supportedDevicePixelContentBox=t,t?(i._resizeObserver=new ResizeObserver((function(t){var e,n=t.find((function(t){return t.target===i._element})),o=null===(e=null==n?void 0:n.devicePixelContentBoxSize)||void 0===e?void 0:e[0];V(o)&&(i._nextPixelWidth=o.inlineSize,i._nextPixelHeight=o.blockSize,i._pixelWidth===i._nextPixelWidth&&i._pixelHeight===i._nextPixelHeight||i._resetPixelRatio())})),i._resizeObserver.observe(i._element,{box:"device-pixel-content-box"})):(i._mediaQueryList=window.matchMedia("(resolution: ".concat($(i._element),"dppx)")),i._mediaQueryList.addListener(i._mediaQueryListener))})).catch((function(t){return!1}))}return t.prototype._resetPixelRatio=function(){var t=this;this._executeListener((function(){var e=t._element.clientWidth,i=t._element.clientHeight,n=t._nextPixelWidth/e,o=t._nextPixelHeight/i;t._width=e,t._height=i,t._pixelWidth=t._nextPixelWidth,t._pixelHeight=t._nextPixelHeight,t._element.width=t._nextPixelWidth,t._element.height=t._nextPixelHeight,t._ctx.scale(n,o)}))},t.prototype._executeListener=function(t){var e=this;-1===this._requestAnimationId&&(this._requestAnimationId=ct((function(){e._ctx.clearRect(0,0,e._width,e._height),null==t||t(),e._listener(),e._requestAnimationId=-1})))},t.prototype.update=function(t,e){if(this._width!==t||this._height!==e){if(this._element.style.width="".concat(t,"px"),this._element.style.height="".concat(e,"px"),!this._supportedDevicePixelContentBox){var i=$(this._element);this._nextPixelWidth=Math.round(t*i),this._nextPixelHeight=Math.round(e*i),this._resetPixelRatio()}}else this._executeListener()},t.prototype.getElement=function(){return this._element},t.prototype.getContext=function(){return this._ctx},t.prototype.destroy=function(){var t,e;null===(t=this._resizeObserver)||void 0===t||t.unobserve(this._element),null===(e=this._mediaQueryList)||void 0===e||e.removeListener(this._mediaQueryListener)},t}();function De(t){var e={width:0,height:0,left:0,right:0,top:0,bottom:0};return V(t)&&A(e,t),e}var Me=function(t){function e(e,i){var n=t.call(this)||this;return n._bounding=De(),n._pane=i,n.init(e),n}return i(e,t),e.prototype.init=function(t){this._rootContainer=t,this._container=this.createContainer(),t.appendChild(this._container)},e.prototype.setBounding=function(t){return A(this._bounding,t),this},e.prototype.getContainer=function(){return this._container},e.prototype.getBounding=function(){return this._bounding},e.prototype.getPane=function(){return this._pane},e.prototype.update=function(t){this.updateImp(this._container,this._bounding,null!=t?t:3)},e.prototype.destroy=function(){this._rootContainer.removeChild(this._container)},e}(qt),ke=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.init=function(e){var i=this;t.prototype.init.call(this,e),this._mainCanvas=new Pe({position:"absolute",top:"0",left:"0",zIndex:"2",boxSizing:"border-box"},(function(){i.updateMain(i._mainCanvas.getContext())})),this._overlayCanvas=new Pe({position:"absolute",top:"0",left:"0",zIndex:"2",boxSizing:"border-box"},(function(){i.updateOverlay(i._overlayCanvas.getContext())}));var n=this.getContainer();n.appendChild(this._mainCanvas.getElement()),n.appendChild(this._overlayCanvas.getElement())},e.prototype.createContainer=function(){return ft("div",{margin:"0",padding:"0",position:"absolute",top:"0",overflow:"hidden",boxSizing:"border-box",zIndex:"1"})},e.prototype.updateImp=function(t,e,i){var n=e.width,o=e.height,r=e.left;t.style.left="".concat(r,"px");var a=i,s=t.clientWidth,l=t.clientHeight;switch(n===s&&o===l||(t.style.width="".concat(n,"px"),t.style.height="".concat(o,"px"),a=3),a){case 0:this._mainCanvas.update(n,o);break;case 1:this._overlayCanvas.update(n,o);break;case 3:case 4:this._mainCanvas.update(n,o),this._overlayCanvas.update(n,o)}},e.prototype.destroy=function(){this._mainCanvas.destroy(),this._overlayCanvas.destroy()},e.prototype.getImage=function(t){var e=this.getBounding(),i=e.width,n=e.height,o=ft("canvas",{width:"".concat(i,"px"),height:"".concat(n,"px"),boxSizing:"border-box"}),r=o.getContext("2d"),a=$(o);return o.width=i*a,o.height=n*a,r.scale(a,a),r.drawImage(this._mainCanvas.getElement(),0,0,i,n),t&&r.drawImage(this._overlayCanvas.getElement(),0,0,i,n),o},e}(Me);function Ae(t){return"transparent"===t||"none"===t||/^[rR][gG][Bb][Aa]\(([\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)[\s]*,){3}[\s]*0[\s]*\)$/.test(t)||/^[hH][Ss][Ll][Aa]\(([\s]*(360|3[0-5][0-9]|[012]?[0-9][0-9]?)[\s]*,)([\s]*((100|[0-9][0-9]?)%|0)[\s]*,){2}([\s]*0[\s]*)\)$/.test(t)}function Fe(t,e){var i=[];i=i.concat(e);for(var n=0;n<i.length;n++){var o=i[n],r=o.x,a=o.y,s=o.r,l=t.x-r,c=t.y-a;if(!(l*l+c*c>s*s))return!0}return!1}function Le(e,i,n){var o=[];o=o.concat(i);var r=n.style,a=void 0===r?t.PolygonType.Fill:r,s=n.color,l=void 0===s?"currentColor":s,c=n.borderSize,u=void 0===c?1:c,h=n.borderColor,d=void 0===h?"currentColor":h,p=n.borderStyle,g=void 0===p?t.LineType.Solid:p,v=n.borderDashedValue,f=void 0===v?[2,2]:v,y=!(a!==t.PolygonType.Fill&&n.style!==t.PolygonType.StrokeFill||W(l)&&Ae(l));y&&(e.fillStyle=l,o.forEach((function(t){var i=t.x,n=t.y,o=t.r;e.beginPath(),e.arc(i,n,o,0,2*Math.PI),e.closePath(),e.fill()}))),(a===t.PolygonType.Stroke||n.style===t.PolygonType.StrokeFill)&&u>0&&!Ae(d)&&(e.strokeStyle=d,e.lineWidth=u,g===t.LineType.Dashed?e.setLineDash(f):e.setLineDash([]),o.forEach((function(t){var i=t.x,n=t.y,o=t.r;(!y||o>u)&&(e.beginPath(),e.arc(i,n,o,0,2*Math.PI),e.closePath(),e.stroke())})))}var Re={name:"circle",checkEventOn:Fe,draw:function(t,e,i){Le(t,e,i)}};function Be(t,e){var i=[];i=i.concat(e);for(var n=0;n<i.length;n++){for(var o=!1,r=i[n].coordinates,a=0,s=r.length-1;a<r.length;s=a++)r[a].y>t.y!=r[s].y>t.y&&t.x<(r[s].x-r[a].x)*(t.y-r[a].y)/(r[s].y-r[a].y)+r[a].x&&(o=!o);if(o)return!0}return!1}function Oe(e,i,n){var o=[];o=o.concat(i);var r=n.style,a=void 0===r?t.PolygonType.Fill:r,s=n.color,l=void 0===s?"currentColor":s,c=n.borderSize,u=void 0===c?1:c,h=n.borderColor,d=void 0===h?"currentColor":h,p=n.borderStyle,g=void 0===p?t.LineType.Solid:p,v=n.borderDashedValue,f=void 0===v?[2,2]:v;a!==t.PolygonType.Fill&&n.style!==t.PolygonType.StrokeFill||W(l)&&Ae(l)||(e.fillStyle=l,o.forEach((function(t){var i=t.coordinates;e.beginPath(),e.moveTo(i[0].x,i[0].y);for(var n=1;n<i.length;n++)e.lineTo(i[n].x,i[n].y);e.closePath(),e.fill()}))),(a===t.PolygonType.Stroke||n.style===t.PolygonType.StrokeFill)&&u>0&&!Ae(d)&&(e.strokeStyle=d,e.lineWidth=u,g===t.LineType.Dashed?e.setLineDash(f):e.setLineDash([]),o.forEach((function(t){var i=t.coordinates;e.beginPath(),e.moveTo(i[0].x,i[0].y);for(var n=1;n<i.length;n++)e.lineTo(i[n].x,i[n].y);e.closePath(),e.stroke()})))}var Ve={name:"polygon",checkEventOn:Be,draw:function(t,e,i){Oe(t,e,i)}};function Ne(t,e){var i=[];i=i.concat(e);for(var n=0;n<i.length;n++){var o=i[n],r=o.x,a=o.width;a<4&&(r-=2,a=4);var s=o.y,l=o.height;if(l<4&&(s-=2,l=4),t.x>=r&&t.x<=r+a&&t.y>=s&&t.y<=s+l)return!0}return!1}function We(e,i,n){var o,r=[];r=r.concat(i);var a=n.style,s=void 0===a?t.PolygonType.Fill:a,l=n.color,c=void 0===l?"transparent":l,u=n.borderSize,h=void 0===u?1:u,d=n.borderColor,p=void 0===d?"transparent":d,g=n.borderStyle,v=void 0===g?t.LineType.Solid:g,f=n.borderRadius,y=void 0===f?0:f,m=n.borderDashedValue,_=void 0===m?[2,2]:m,x=null!==(o=e.roundRect)&&void 0!==o?o:e.rect,S=!(s!==t.PolygonType.Fill&&n.style!==t.PolygonType.StrokeFill||W(c)&&Ae(c));if(S&&(e.fillStyle=c,r.forEach((function(t){var i=t.x,n=t.y,o=t.width,r=t.height;e.beginPath(),x.call(e,i,n,o,r,y),e.closePath(),e.fill()}))),(s===t.PolygonType.Stroke||n.style===t.PolygonType.StrokeFill)&&h>0&&!Ae(p)){e.strokeStyle=p,e.fillStyle=p,e.lineWidth=h,v===t.LineType.Dashed?e.setLineDash(_):e.setLineDash([]);var C=h%2==1?.5:0,b=Math.round(2*C);r.forEach((function(t){var i=t.x,n=t.y,o=t.width,r=t.height;o>2*h&&r>2*h?(e.beginPath(),x.call(e,i+C,n+C,o-b,r-b,y),e.closePath(),e.stroke()):S||e.fillRect(i,n,o,r)}))}}var ze={name:"rect",checkEventOn:Ne,draw:function(t,e,i){We(t,e,i)}};function Ye(t,e){var i,n,o=e.size,r=void 0===o?12:o,a=e.paddingLeft,s=void 0===a?0:a,l=e.paddingTop,c=void 0===l?0:l,u=e.paddingRight,h=void 0===u?0:u,d=e.paddingBottom,p=void 0===d?0:d,g=e.weight,v=void 0===g?"normal":g,f=e.family,y=t.x,m=t.y,_=t.text,x=t.align,S=void 0===x?"left":x,C=t.baseline,b=void 0===C?"top":C,T=t.width,w=t.height,E=null!=T?T:s+J(_,r,v,f)+h,I=null!=w?w:c+r+p;switch(S){case"left":case"start":i=y;break;case"right":case"end":i=y-E;break;default:i=y-E/2}switch(b){case"top":case"hanging":n=m;break;case"bottom":case"ideographic":case"alphabetic":n=m-I;break;default:n=m-I/2}return{x:i,y:n,width:E,height:I}}function He(t,e,i){var n=[];n=n.concat(e);for(var o=0;o<n.length;o++){var r=Ye(n[o],i),a=r.x,s=r.y,l=r.width,c=r.height;if(t.x>=a&&t.x<=a+l&&t.y>=s&&t.y<=s+c)return!0}return!1}function Xe(t,e,i){var n=[];n=n.concat(e);var o=i.color,r=void 0===o?"currentColor":o,a=i.size,s=void 0===a?12:a,l=i.family,c=i.weight,u=i.paddingLeft,h=void 0===u?0:u,p=i.paddingTop,g=void 0===p?0:p,v=i.paddingRight,f=void 0===v?0:v,y=n.map((function(t){return Ye(t,i)}));We(t,y,d(d({},i),{color:i.backgroundColor})),t.textAlign="left",t.textBaseline="top",t.font=Q(s,c,l),t.fillStyle=r,n.forEach((function(e,i){var n=y[i];t.fillText(e.text,n.x+h,n.y+g,n.width-h-f)}))}var Ge={name:"text",checkEventOn:He,draw:function(t,e,i){Xe(t,e,i)}},je=Xe;function Ke(t,e){var i,n,o,r,a=[];a=a.concat(e);for(var s=0;s<a.length;s++){var l=a[s];if(Math.abs((n=l,o=void 0,r=void 0,o=(i=t).x-n.x,r=i.y-n.y,Math.sqrt(o*o+r*r)-l.r))<2){var c=l.r,u=l.startAngle,h=l.endAngle,d=c*Math.cos(u)+l.x,p=c*Math.sin(u)+l.y,g=c*Math.cos(h)+l.x,v=c*Math.sin(h)+l.y;if(t.x<=Math.max(d,g)+2&&t.x>=Math.min(d,g)-2&&t.y<=Math.max(p,v)+2&&t.y>=Math.min(p,v)-2)return!0}}return!1}function Ze(e,i,n){var o=[];o=o.concat(i);var r=n.style,a=void 0===r?t.LineType.Solid:r,s=n.size,l=void 0===s?1:s,c=n.color,u=void 0===c?"currentColor":c,h=n.dashedValue,d=void 0===h?[2,2]:h;e.lineWidth=l,e.strokeStyle=u,a===t.LineType.Dashed?e.setLineDash(d):e.setLineDash([]),o.forEach((function(t){var i=t.x,n=t.y,o=t.r,r=t.startAngle,a=t.endAngle;e.beginPath(),e.arc(i,n,o,r,a),e.stroke(),e.closePath()}))}var Ue={name:"arc",checkEventOn:Ke,draw:function(t,e,i){Ze(t,e,i)}},qe={};[Re,oe,Ve,ze,Ge,Ge,Ue].forEach((function(t){qe[t.name]=$t.extend(t)}));var $e=function(t){function e(e){var i=t.call(this)||this;return i._widget=e,i}return i(e,t),e.prototype.getWidget=function(){return this._widget},e.prototype.createFigure=function(t,e){var i,n,o=(i=t.name,null!==(n=qe[i])&&void 0!==n?n:null);if(null!==o){var r=new o(t);if(V(e)){for(var a in e)e.hasOwnProperty(a)&&r.registerEvent(a,e[a]);this.addChild(r)}return r}return null},e.prototype.draw=function(t){this.clear(),this.drawImp(t)},e}(qt),Qe=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.drawImp=function(t){var e,i,n=this.getWidget(),o=this.getWidget().getPane(),r=o.getChart(),a=n.getBounding(),s=r.getStyles().grid;if(s.show){t.save(),t.globalCompositeOperation="destination-over";var l=s.horizontal;if(l.show){var c=o.getAxisComponent().getTicks().map((function(t){return{coordinates:[{x:0,y:t.coord},{x:a.width,y:t.coord}]}}));null===(e=this.createFigure({name:"line",attrs:c,styles:l}))||void 0===e||e.draw(t)}var u=s.vertical;if(u.show){c=r.getXAxisPane().getAxisComponent().getTicks().map((function(t){return{coordinates:[{x:t.coord,y:0},{x:t.coord,y:a.height}]}}));null===(i=this.createFigure({name:"line",attrs:c,styles:u}))||void 0===i||i.draw(t)}t.restore()}},e}($e),Je=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.eachChildren=function(t){var e=this.getWidget().getPane().getChart().getChartStore(),i=e.getVisibleDataList(),n=e.getTimeScaleStore().getBarSpace();i.forEach((function(e,i){t(e,n,i)}))},e}($e),ti=function(e){function n(){var i=null!==e&&e.apply(this,arguments)||this;return i._boundCandleBarClickEvent=function(e){return function(){return i.getWidget().getPane().getChart().getChartStore().getActionStore().execute(t.ActionType.OnCandleBarClick,e),!1}},i}return i(n,e),n.prototype.drawImp=function(e){var i=this,n=this.getWidget().getPane(),o=n.getId()===fe,r=n.getChart().getChartStore(),a=this.getCandleBarOptions(r);if(null!==a){var s=0,l=0;if(a.type===t.CandleType.Ohlc){var c=r.getTimeScaleStore().getBarSpace().gapBar;(s=Math.min(Math.max(Math.round(.2*c),1),8))>2&&s%2==1&&s--,l=Math.floor(l/2)}var u=n.getAxisComponent();this.eachChildren((function(n,r){var c=n.data,h=n.x;if(V(c)){var d=c.open,p=c.high,g=c.low,v=c.close,f=a.type,y=a.styles,m=[];v>d?(m[0]=y.upColor,m[1]=y.upBorderColor,m[2]=y.upWickColor):v<d?(m[0]=y.downColor,m[1]=y.downBorderColor,m[2]=y.downWickColor):(m[0]=y.noChangeColor,m[1]=y.noChangeBorderColor,m[2]=y.noChangeWickColor);var _=u.convertToPixel(d),x=u.convertToPixel(v),S=[_,x,u.convertToPixel(p),u.convertToPixel(g)];S.sort((function(t,e){return t-e}));var C=[];switch(f){case t.CandleType.CandleSolid:C=i._createSolidBar(h,S,r,m);break;case t.CandleType.CandleStroke:C=i._createStrokeBar(h,S,r,m);break;case t.CandleType.CandleUpStroke:C=v>d?i._createStrokeBar(h,S,r,m):i._createSolidBar(h,S,r,m);break;case t.CandleType.CandleDownStroke:C=d>v?i._createStrokeBar(h,S,r,m):i._createSolidBar(h,S,r,m);break;case t.CandleType.Ohlc:C=[{name:"rect",attrs:[{x:h-l,y:S[0],width:s,height:S[3]-S[0]},{x:h-r.halfGapBar,y:_+s>S[3]?S[3]-s:_,width:r.halfGapBar,height:s},{x:h+l,y:x+s>S[3]?S[3]-s:x,width:r.halfGapBar-l,height:s}],styles:{color:m[0]}}]}C.forEach((function(t){var r,a;o&&(a={mouseClickEvent:i._boundCandleBarClickEvent(n)}),null===(r=i.createFigure(t,a))||void 0===r||r.draw(e)}))}}))}},n.prototype.getCandleBarOptions=function(t){var e=t.getStyles().candle;return{type:e.type,styles:e.bar}},n.prototype._createSolidBar=function(e,i,n,o){return[{name:"rect",attrs:{x:e,y:i[0],width:1,height:i[3]-i[0]},styles:{color:o[2]}},{name:"rect",attrs:{x:e-n.halfGapBar,y:i[1],width:n.gapBar,height:Math.max(1,i[2]-i[1])},styles:{style:t.PolygonType.StrokeFill,color:o[0],borderColor:o[1]}}]},n.prototype._createStrokeBar=function(e,i,n,o){return[{name:"rect",attrs:[{x:e,y:i[0],width:1,height:i[1]-i[0]},{x:e,y:i[2],width:1,height:i[3]-i[2]}],styles:{color:o[2]}},{name:"rect",attrs:{x:e-n.halfGapBar,y:i[1],width:n.gapBar,height:Math.max(1,i[2]-i[1])},styles:{style:t.PolygonType.Stroke,borderColor:o[1]}}]},n}(Je),ei=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.getCandleBarOptions=function(e){var i,n,o=this.getWidget().getPane();if(!o.getAxisComponent().isInCandle()){var r=e.getIndicatorStore().getInstances(o.getId());try{for(var a=v(r),s=a.next();!s.done;s=a.next()){var l=s.value;if(l.shouldOhlc&&l.visible){var c=l.styles,u=e.getStyles().indicator,h=G(c,"ohlc.upColor",u.ohlc.upColor),d=G(c,"ohlc.downColor",u.ohlc.downColor),p=G(c,"ohlc.noChangeColor",u.ohlc.noChangeColor);return{type:t.CandleType.Ohlc,styles:{upColor:h,downColor:d,noChangeColor:p,upBorderColor:h,downBorderColor:d,noChangeBorderColor:p,upWickColor:h,downWickColor:d,noChangeWickColor:p}}}}}catch(t){i={error:t}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}}return null},n.prototype.drawImp=function(t){var i=this;e.prototype.drawImp.call(this,t);var n=this.getWidget(),o=n.getPane(),r=o.getChart(),a=n.getBounding(),s=r.getXAxisPane().getAxisComponent(),l=o.getAxisComponent(),c=r.getChartStore(),u=c.getDataList(),h=c.getTimeScaleStore(),d=h.getVisibleRange(),p=c.getIndicatorStore().getInstances(o.getId()),g=c.getStyles().indicator;t.save(),p.forEach((function(e){var n;if(e.visible){e.zLevel<0?t.globalCompositeOperation="destination-over":t.globalCompositeOperation="source-over";var o=!1;if(null!==e.draw&&(t.save(),o=null!==(n=e.draw({ctx:t,kLineDataList:u,indicator:e,visibleRange:d,bounding:a,barSpace:h.getBarSpace(),defaultStyles:g,xAxis:s,yAxis:l}))&&void 0!==n&&n,t.restore()),!o){var r=e.result,c=[];i.eachChildren((function(n,o){var h,d,p,v=o.halfGapBar,f=n.dataIndex,y=n.x,m=s.convertToPixel(f-1),_=s.convertToPixel(f+1),x=null!==(h=r[f-1])&&void 0!==h?h:null,S=null!==(d=r[f])&&void 0!==d?d:null,C=null!==(p=r[f+1])&&void 0!==p?p:null,b={x:m},T={x:y},w={x:_};e.figures.forEach((function(t){var e=t.key,i=null==x?void 0:x[e];O(i)&&(b[e]=l.convertToPixel(i));var n=null==S?void 0:S[e];O(n)&&(T[e]=l.convertToPixel(n));var o=null==C?void 0:C[e];O(o)&&(w[e]=l.convertToPixel(o))})),it(u,e,f,g,(function(e,n,r){var u,h,d;if(V(null==S?void 0:S[e.key])){var p=T[e.key],g=null===(u=e.attrs)||void 0===u?void 0:u.call(e,{data:{prev:x,current:S,next:C},coordinate:{prev:b,current:T,next:w},bounding:a,barSpace:o,xAxis:s,yAxis:l});if(!V(g))switch(e.type){case"circle":g={x:y,y:p,r:Math.max(1,v)};break;case"rect":case"bar":var f=null!==(h=e.baseValue)&&void 0!==h?h:l.getRange().from,m=l.convertToPixel(f),_=Math.abs(m-p);f!==(null==S?void 0:S[e.key])&&(_=Math.max(1,_));g={x:y-v,y:p>m?m:p,width:Math.max(1,2*v),height:_};break;case"line":V(c[r])||(c[r]=[]),O(T[e.key])&&O(w[e.key])&&c[r].push({coordinates:[{x:T.x,y:T[e.key]},{x:w.x,y:w[e.key]}],styles:n})}var E=e.type;V(g)&&"line"!==E&&(null===(d=i.createFigure({name:"bar"===E?"rect":E,attrs:g,styles:n}))||void 0===d||d.draw(t))}}))})),c.forEach((function(e){if(e.length>1){for(var n=[{coordinates:[e[0].coordinates[0],e[0].coordinates[1]],styles:e[0].styles}],o=1;o<e.length;o++){var r=n[n.length-1],a=e[o],s=r.coordinates[r.coordinates.length-1];s.x===a.coordinates[0].x&&s.y===a.coordinates[0].y&&r.styles.style===a.styles.style&&r.styles.color===a.styles.color&&r.styles.size===a.styles.size&&r.styles.smooth===a.styles.smooth&&r.styles.dashedValue[0]===a.styles.dashedValue[0]&&r.styles.dashedValue[1]===a.styles.dashedValue[1]?r.coordinates.push(a.coordinates[1]):n.push({coordinates:[a.coordinates[0],a.coordinates[1]],styles:a.styles})}n.forEach((function(e){var n,o=e.coordinates,r=e.styles;null===(n=i.createFigure({name:"line",attrs:{coordinates:o},styles:r}))||void 0===n||n.draw(t)}))}}))}}})),t.restore()},n}(ti),ii=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.drawImp=function(t){var e=this.getWidget(),i=e.getPane(),n=e.getBounding(),o=e.getPane().getChart().getChartStore(),r=o.getTooltipStore().getCrosshair(),a=o.getStyles().crosshair;if(W(r.paneId)&&a.show){if(r.paneId===i.getId()){var s=r.y;this._drawLine(t,[{x:0,y:s},{x:n.width,y:s}],a.horizontal)}var l=r.realX;this._drawLine(t,[{x:l,y:0},{x:l,y:n.height}],a.vertical)}},e.prototype._drawLine=function(t,e,i){var n;if(i.show){var o=i.line;o.show&&(null===(n=this.createFigure({name:"line",attrs:{coordinates:e},styles:o}))||void 0===n||n.draw(t))}},e}($e),ni=function(e){function n(){var i=null!==e&&e.apply(this,arguments)||this;return i._boundIconClickEvent=function(e){return function(){return i.getWidget().getPane().getChart().getChartStore().getActionStore().execute(t.ActionType.OnTooltipIconClick,d({},e)),!0}},i._boundIconMouseMoveEvent=function(t){return function(){return i.getWidget().getPane().getChart().getChartStore().getTooltipStore().setActiveIcon(d({},t)),!0}},i}return i(n,e),n.prototype.drawImp=function(t){var e=this.getWidget(),i=e.getPane(),n=i.getChart().getChartStore(),o=n.getTooltipStore().getCrosshair();if(V(o.kLineData)){var r=e.getBounding(),a=n.getCustomApi(),s=n.getThousandsSeparator(),l=n.getDecimalFoldThreshold(),c=n.getIndicatorStore().getInstances(i.getId()),u=n.getTooltipStore().getActiveIcon(),h=n.getStyles().indicator,d=h.tooltip,p=d.offsetLeft,g=d.offsetTop,v=d.offsetRight;this.drawIndicatorTooltip(t,i.getId(),n.getDataList(),o,u,c,a,s,l,p,g,r.width-v,h)}},n.prototype.drawIndicatorTooltip=function(t,e,i,n,o,r,a,s,l,c,u,h,d){var p=this,g=d.tooltip;if(this.isDrawTooltip(n,g)){var v=g.text;r.forEach((function(r){var y=0,m={x:c,y:u},_=p.getIndicatorTooltipData(i,n,r,a,s,l,d),x=_.name,S=_.calcParamsText,C=_.values,b=_.icons,T=x.length>0,w=C.length>0;if(T||w){var E=f(p.classifyTooltipIcons(b),3),I=E[0],P=E[1],D=E[2];if(y=p.drawStandardTooltipIcons(t,o,I,m,e,r.name,c,y,h),T){var M=x;S.length>0&&(M="".concat(M).concat(S)),y=p.drawStandardTooltipLegends(t,[{title:{text:"",color:v.color},value:{text:M,color:v.color}}],m,c,y,h,v)}y=p.drawStandardTooltipIcons(t,o,P,m,e,r.name,c,y,h),w&&(y=p.drawStandardTooltipLegends(t,C,m,c,y,h,g.text)),y=p.drawStandardTooltipIcons(t,o,D,m,e,r.name,c,y,h),u=m.y+y}}))}return u},n.prototype.drawStandardTooltipIcons=function(t,e,i,n,o,r,a,s,l){var c=this;if(i.length>0){var u=0,h=0;i.forEach((function(e){var i=e.marginLeft,n=void 0===i?0:i,o=e.marginTop,r=void 0===o?0:o,a=e.marginRight,s=void 0===a?0:a,l=e.marginBottom,c=void 0===l?0:l,d=e.paddingLeft,p=void 0===d?0:d,g=e.paddingTop,v=void 0===g?0:g,f=e.paddingRight,y=void 0===f?0:f,m=e.paddingBottom,_=void 0===m?0:m,x=e.size,S=e.fontFamily,C=e.icon;t.font=Q(x,"normal",S),u+=n+p+t.measureText(C).width+y+s,h=Math.max(h,r+v+x+_+c)})),n.x+u>l?(n.x=a,n.y+=s,s=h):s=Math.max(s,h),i.forEach((function(i){var a,s=i.marginLeft,l=void 0===s?0:s,u=i.marginTop,h=void 0===u?0:u,d=i.marginRight,p=void 0===d?0:d,g=i.paddingLeft,v=void 0===g?0:g,f=i.paddingTop,y=void 0===f?0:f,m=i.paddingRight,_=void 0===m?0:m,x=i.paddingBottom,S=void 0===x?0:x,C=i.color,b=i.activeColor,T=i.size,w=i.fontFamily,E=i.icon,I=i.backgroundColor,P=i.activeBackgroundColor,D=(null==e?void 0:e.paneId)===o&&(null==e?void 0:e.indicatorName)===r&&(null==e?void 0:e.iconId)===i.id;null===(a=c.createFigure({name:"text",attrs:{text:E,x:n.x+l,y:n.y+h},styles:{paddingLeft:v,paddingTop:y,paddingRight:_,paddingBottom:S,color:D?b:C,size:T,family:w,backgroundColor:D?P:I}},{mouseClickEvent:c._boundIconClickEvent({paneId:o,indicatorName:r,iconId:i.id}),mouseMoveEvent:c._boundIconMouseMoveEvent({paneId:o,indicatorName:r,iconId:i.id})}))||void 0===a||a.draw(t),n.x+=l+v+t.measureText(E).width+_+p}))}return s},n.prototype.drawStandardTooltipLegends=function(t,e,i,n,o,r,a){var s=this;if(e.length>0){var l=a.marginLeft,c=a.marginTop,u=a.marginRight,h=a.marginBottom,d=a.size,p=a.family,g=a.weight;t.font=Q(d,g,p),e.forEach((function(e){var a,v,f=e.title,y=e.value,m=t.measureText(f.text).width,_=m+t.measureText(y.text).width,x=c+d+h;i.x+l+_+u>r?(i.x=n,i.y+=o,o=x):o=Math.max(o,x),f.text.length>0&&(null===(a=s.createFigure({name:"text",attrs:{x:i.x+l,y:i.y+c,text:f.text},styles:{color:f.color,size:d,family:p,weight:g}}))||void 0===a||a.draw(t)),null===(v=s.createFigure({name:"text",attrs:{x:i.x+l+m,y:i.y+c,text:y.text},styles:{color:y.color,size:d,family:p,weight:g}}))||void 0===v||v.draw(t),i.x+=l+_+u}))}return o},n.prototype.isDrawTooltip=function(e,i){var n=i.showRule;return n===t.TooltipShowRule.Always||n===t.TooltipShowRule.FollowCross&&W(e.paneId)},n.prototype.getIndicatorTooltipData=function(t,e,i,n,o,r,a){var s,l,c=a.tooltip,u=c.showName?i.shortName:"",h="",d=i.calcParams;d.length>0&&c.showParams&&(h="(".concat(d.join(","),")"));var p={name:u,calcParamsText:h,values:[],icons:c.icons},g=e.dataIndex,v=null!==(s=i.result)&&void 0!==s?s:[],f=[];if(i.visible){var y=null!==(l=v[g])&&void 0!==l?l:{};it(t,i,g,a,(function(t,e){if(W(t.title)){var a=e.color,s=y[t.key];O(s)&&(s=K(s,i.precision),i.shouldFormatBigNumber&&(s=n.formatBigNumber(s))),f.push({title:{text:t.title,color:a},value:{text:q(U(null!=s?s:c.defaultValue,o),r),color:a}})}})),p.values=f}if(null!==i.createTooltipDataSource){var m=this.getWidget(),_=m.getPane(),x=_.getChart().getChartStore(),S=i.createTooltipDataSource({kLineDataList:t,indicator:i,visibleRange:x.getTimeScaleStore().getVisibleRange(),bounding:m.getBounding(),crosshair:e,defaultStyles:a,xAxis:_.getChart().getXAxisPane().getAxisComponent(),yAxis:_.getAxisComponent()}),C=S.name,b=S.calcParamsText,T=S.values,w=S.icons;if(W(C)&&c.showName&&(p.name=C),W(b)&&c.showParams&&(p.calcParamsText=b),V(w)&&(p.icons=w),V(T)&&i.visible){var E=[],I=a.tooltip.text.color;T.forEach((function(t){var e={text:"",color:I};B(t.title)?e=t.title:e.text=t.title;var i={text:"",color:I};B(t.value)?i=t.value:i.text=t.value,i.text=q(U(i.text,o),r),E.push({title:e,value:i})})),p.values=E}}return p},n.prototype.classifyTooltipIcons=function(e){var i=[],n=[],o=[];return e.forEach((function(e){switch(e.position){case t.TooltipIconPosition.Left:i.push(e);break;case t.TooltipIconPosition.Middle:n.push(e);break;case t.TooltipIconPosition.Right:o.push(e)}})),[i,n,o]},n}($e),oi=function(e){function n(t){var i=e.call(this,t)||this;return i._initEvent(),i}return i(n,e),n.prototype._initEvent=function(){var t=this,e=this.getWidget().getPane(),i=e.getId(),n=e.getChart().getChartStore().getOverlayStore();this.registerEvent("mouseMoveEvent",(function(e){var o,r=n.getProgressInstanceInfo();if(null!==r){var a=r.instance,s=r.paneId;a.isStart()&&(n.updateProgressInstanceInfo(i),s=i);var l=a.points.length-1,c="".concat(at,"point_").concat(l);return a.isDrawing()&&s===i&&(a.eventMoveForDrawing(t._coordinateToPoint(r.instance,e)),null===(o=a.onDrawing)||void 0===o||o.call(a,d({overlay:a,figureKey:c,figureIndex:l},e))),t._figureMouseMoveEvent(a,1,c,l,0)(e)}return n.setHoverInstanceInfo({paneId:i,instance:null,figureType:0,figureKey:"",figureIndex:-1,attrsIndex:-1},e),!1})).registerEvent("mouseClickEvent",(function(e){var o,r,a=n.getProgressInstanceInfo();if(null!==a){var s=a.instance,l=a.paneId;s.isStart()&&(n.updateProgressInstanceInfo(i,!0),l=i);var c=s.points.length-1,u="".concat(at,"point_").concat(c);return s.isDrawing()&&l===i&&(s.eventMoveForDrawing(t._coordinateToPoint(s,e)),null===(o=s.onDrawing)||void 0===o||o.call(s,d({overlay:s,figureKey:u,figureIndex:c},e)),s.nextStep(),s.isDrawing()||(n.progressInstanceComplete(),null===(r=s.onDrawEnd)||void 0===r||r.call(s,d({overlay:s,figureKey:u,figureIndex:c},e)))),t._figureMouseClickEvent(s,1,u,c,0)(e)}return n.setClickInstanceInfo({paneId:i,instance:null,figureType:0,figureKey:"",figureIndex:-1,attrsIndex:-1},e),!1})).registerEvent("mouseDoubleClickEvent",(function(e){var o,r=n.getProgressInstanceInfo();if(null!==r){var a=r.instance,s=r.paneId;if(a.isDrawing()&&s===i&&(a.forceComplete(),!a.isDrawing())){n.progressInstanceComplete();var l=a.points.length-1,c="".concat(at,"point_").concat(l);null===(o=a.onDrawEnd)||void 0===o||o.call(a,d({overlay:a,figureKey:c,figureIndex:l},e))}var u=a.points.length-1;return t._figureMouseClickEvent(a,1,"".concat(at,"point_").concat(u),u,0)(e)}return!1})).registerEvent("mouseRightClickEvent",(function(e){var i=n.getProgressInstanceInfo();if(null!==i){var o=i.instance;if(o.isDrawing()){var r=o.points.length-1;return t._figureMouseRightClickEvent(o,1,"".concat(at,"point_").concat(r),r,0)(e)}}return!1})).registerEvent("mouseUpEvent",(function(t){var e,o=n.getPressedInstanceInfo(),r=o.instance,a=o.figureIndex,s=o.figureKey;return null!==r&&(null===(e=r.onPressedMoveEnd)||void 0===e||e.call(r,d({overlay:r,figureKey:s,figureIndex:a},t))),n.setPressedInstanceInfo({paneId:i,instance:null,figureType:0,figureKey:"",figureIndex:-1,attrsIndex:-1}),!1})).registerEvent("pressedMouseMoveEvent",(function(e){var i,o,r=n.getPressedInstanceInfo(),a=r.instance,s=r.figureType,l=r.figureIndex,c=r.figureKey;if(null!==a){if(!(a.lock||null!==(o=null===(i=a.onPressedMoving)||void 0===i?void 0:i.call(a,d({overlay:a,figureIndex:l,figureKey:c},e)))&&void 0!==o&&o)){var u=t._coordinateToPoint(a,e);1===s?a.eventPressedPointMove(u,l):a.eventPressedOtherMove(u,t.getWidget().getPane().getChart().getChartStore().getTimeScaleStore())}return!0}return!1}))},n.prototype._createFigureEvents=function(t,e,i,n,o,r){var a;if(!t.isDrawing()){var s=[];if(V(r)&&(N(r)?r&&(s=["mouseClickEvent","mouseDoubleClickEvent","mouseRightClickEvent","tapEvent","doubleTapEvent","mouseDownEvent","touchStartEvent","mouseMoveEvent","touchMoveEvent"]):s=r),0===s.length)return{mouseMoveEvent:this._figureMouseMoveEvent(t,e,i,n,o),mouseDownEvent:this._figureMouseDownEvent(t,e,i,n,o),mouseClickEvent:this._figureMouseClickEvent(t,e,i,n,o),mouseRightClickEvent:this._figureMouseRightClickEvent(t,e,i,n,o),mouseDoubleClickEvent:this._figureMouseDoubleClickEvent(t,e,i,n,o)};a={},s.includes("mouseMoveEvent")||s.includes("touchMoveEvent")||(a.mouseMoveEvent=this._figureMouseMoveEvent(t,e,i,n,o)),s.includes("mouseDownEvent")||s.includes("touchStartEvent")||(a.mouseDownEvent=this._figureMouseDownEvent(t,e,i,n,o)),s.includes("mouseClickEvent")||s.includes("tapEvent")||(a.mouseClickEvent=this._figureMouseClickEvent(t,e,i,n,o)),s.includes("mouseDoubleClickEvent")||s.includes("doubleTapEvent")||(a.mouseDoubleClickEvent=this._figureMouseDoubleClickEvent(t,e,i,n,o)),s.includes("mouseRightClickEvent")||(a.mouseRightClickEvent=this._figureMouseRightClickEvent(t,e,i,n,o))}return a},n.prototype._figureMouseMoveEvent=function(t,e,i,n,o){var r=this;return function(a){var s=r.getWidget().getPane();return s.getChart().getChartStore().getOverlayStore().setHoverInstanceInfo({paneId:s.getId(),instance:t,figureType:e,figureKey:i,figureIndex:n,attrsIndex:o},a),!0}},n.prototype._figureMouseDownEvent=function(t,e,i,n,o){var r=this;return function(a){var s,l=r.getWidget().getPane(),c=l.getId(),u=l.getChart().getChartStore().getOverlayStore();return t.startPressedMove(r._coordinateToPoint(t,a)),null===(s=t.onPressedMoveStart)||void 0===s||s.call(t,d({overlay:t,figureIndex:n,figureKey:i},a)),u.setPressedInstanceInfo({paneId:c,instance:t,figureType:e,figureKey:i,figureIndex:n,attrsIndex:o}),!0}},n.prototype._figureMouseClickEvent=function(t,e,i,n,o){var r=this;return function(a){var s=r.getWidget().getPane(),l=s.getId();return s.getChart().getChartStore().getOverlayStore().setClickInstanceInfo({paneId:l,instance:t,figureType:e,figureKey:i,figureIndex:n,attrsIndex:o},a),!0}},n.prototype._figureMouseDoubleClickEvent=function(t,e,i,n,o){return function(e){var o;return null===(o=t.onDoubleClick)||void 0===o||o.call(t,d(d({},e),{figureIndex:n,figureKey:i,overlay:t})),!0}},n.prototype._figureMouseRightClickEvent=function(t,e,i,n,o){var r=this;return function(e){var o,a;null!==(a=null===(o=t.onRightClick)||void 0===o?void 0:o.call(t,d({overlay:t,figureIndex:n,figureKey:i},e)))&&void 0!==a&&a||r.getWidget().getPane().getChart().getChartStore().getOverlayStore().removeInstance(t);return!0}},n.prototype._coordinateToPoint=function(e,i){var n,o={},r=this.getWidget().getPane(),a=r.getChart(),s=r.getId(),l=a.getChartStore().getTimeScaleStore();if(this.coordinateToPointTimestampDataIndexFlag()){var c=a.getXAxisPane().getAxisComponent().convertFromPixel(i.x),u=null!==(n=l.dataIndexToTimestamp(c))&&void 0!==n?n:void 0;o.dataIndex=c,o.timestamp=u}if(this.coordinateToPointValueFlag()){var h=r.getAxisComponent(),d=h.convertFromPixel(i.y);if(e.mode!==t.OverlayMode.Normal&&s===fe&&O(o.dataIndex)){var p=l.getDataByDataIndex(o.dataIndex);if(null!==p){var g=e.modeSensitivity;if(d>p.high)if(e.mode===t.OverlayMode.WeakMagnet){var v=h.convertToPixel(p.high);d<h.convertFromPixel(v-g)&&(d=p.high)}else d=p.high;else if(d<p.low)if(e.mode===t.OverlayMode.WeakMagnet){var f=h.convertToPixel(p.low);d>h.convertFromPixel(f-g)&&(d=p.low)}else d=p.low;else{var y=Math.max(p.open,p.close),m=Math.min(p.open,p.close);d=d>y?d-y<p.high-d?y:p.high:d<m?d-p.low<m-d?p.low:m:y-d<d-m?y:m}}}o.value=d}return o},n.prototype.coordinateToPointValueFlag=function(){return!0},n.prototype.coordinateToPointTimestampDataIndexFlag=function(){return!0},n.prototype.dispatchEvent=function(t,i,n){return this.getWidget().getPane().getChart().getChartStore().getOverlayStore().isDrawing()?this.onEvent(t,i,n):e.prototype.dispatchEvent.call(this,t,i,n)},n.prototype.checkEventOn=function(){return!0},n.prototype.drawImp=function(t){var e=this,i=this.getWidget(),n=i.getPane(),o=n.getId(),r=n.getChart(),a=n.getAxisComponent(),s=r.getXAxisPane().getAxisComponent(),l=i.getBounding(),c=r.getChartStore(),u=c.getCustomApi(),h=c.getThousandsSeparator(),p=c.getDecimalFoldThreshold(),g=c.getTimeScaleStore(),v=g.getDateTimeFormat(),f=g.getBarSpace(),y=c.getPrecision(),m=c.getStyles().overlay,_=c.getOverlayStore(),x=_.getHoverInstanceInfo(),S=_.getClickInstanceInfo(),C=this.getCompleteOverlays(_,o),b=c.getIndicatorStore().getInstances(o).reduce((function(t,e){var i=e.precision;return t[e.name]=i,t.max=Math.max(t.max,i),t.min=Math.min(t.min,i),t.excludePriceVolumeMax=Math.max(t.excludePriceVolumeMax,i),t.excludePriceVolumeMin=Math.min(t.excludePriceVolumeMin,i),t}),d(d({},y),{max:Math.max(y.price,y.volume),min:Math.min(y.price,y.volume),excludePriceVolumeMax:Number.MIN_SAFE_INTEGER,excludePriceVolumeMin:Number.MAX_SAFE_INTEGER}));C.forEach((function(i){i.visible&&e._drawOverlay(t,i,l,f,b,v,u,h,p,m,s,a,x,S,g)}));var T=_.getProgressInstanceInfo();if(null!==T){var w=this.getProgressOverlay(T,o);null!==w&&w.visible&&this._drawOverlay(t,w,l,f,b,v,u,h,p,m,s,a,x,S,g)}},n.prototype._drawOverlay=function(t,e,i,n,o,r,a,s,l,c,u,h,d,p,g){var v=e.points.map((function(t){var e,i,n=t.dataIndex;O(t.timestamp)&&(n=g.timestampToDataIndex(t.timestamp));var o={x:0,y:0};return O(n)&&(o.x=null!==(e=null==u?void 0:u.convertToPixel(n))&&void 0!==e?e:0),O(t.value)&&(o.y=null!==(i=null==h?void 0:h.convertToPixel(t.value))&&void 0!==i?i:0),o}));if(v.length>0){var f=(new Array).concat(this.getFigures(e,v,i,n,o,s,l,r,c,u,h));this.drawFigures(t,e,f,c)}this.drawDefaultFigures(t,e,v,i,o,r,a,s,l,c,u,h,d,p)},n.prototype.drawFigures=function(t,e,i,n){var o=this;i.forEach((function(i,r){var a=i.type,s=i.styles,l=i.attrs,c=i.ignoreEvent;[].concat(l).forEach((function(l,u){var h,p,g,v=o._createFigureEvents(e,2,null!==(h=i.key)&&void 0!==h?h:"",r,u,c),f=d(d(d({},n[a]),null===(p=e.styles)||void 0===p?void 0:p[a]),s);null===(g=o.createFigure({name:a,attrs:l,styles:f},v))||void 0===g||g.draw(t)}))}))},n.prototype.getCompleteOverlays=function(t,e){return t.getInstances(e)},n.prototype.getProgressOverlay=function(t,e){return t.paneId===e?t.instance:null},n.prototype.getFigures=function(t,e,i,n,o,r,a,s,l,c,u){var h,d;return null!==(d=null===(h=t.createPointFigures)||void 0===h?void 0:h.call(t,{overlay:t,coordinates:e,bounding:i,barSpace:n,precision:o,thousandsSeparator:r,decimalFoldThreshold:a,dateTimeFormat:s,defaultStyles:l,xAxis:c,yAxis:u}))&&void 0!==d?d:[]},n.prototype.drawDefaultFigures=function(t,e,i,n,o,r,a,s,l,c,u,h,p,g){var v,f,y=this;if(e.needDefaultPointFigure&&((null===(v=p.instance)||void 0===v?void 0:v.id)===e.id&&0!==p.figureType||(null===(f=g.instance)||void 0===f?void 0:f.id)===e.id&&0!==g.figureType)){var m=e.styles,_=d(d({},c.point),null==m?void 0:m.point);i.forEach((function(i,n){var o,r,a,s=i.x,l=i.y,c=_.radius,u=_.color,h=_.borderColor,d=_.borderSize;(null===(o=p.instance)||void 0===o?void 0:o.id)===e.id&&1===p.figureType&&p.figureIndex===n&&(c=_.activeRadius,u=_.activeColor,h=_.activeBorderColor,d=_.activeBorderSize),null===(r=y.createFigure({name:"circle",attrs:{x:s,y:l,r:c+d},styles:{color:h}},y._createFigureEvents(e,1,"".concat(at,"point_").concat(n),n,0)))||void 0===r||r.draw(t),null===(a=y.createFigure({name:"circle",attrs:{x:s,y:l,r:c},styles:{color:u}}))||void 0===a||a.draw(t)}))}},n}($e),ri=function(t){function e(e,i){var n=t.call(this,e,i)||this;return n._gridView=new Qe(n),n._indicatorView=new ei(n),n._crosshairLineView=new ii(n),n._tooltipView=n.createTooltipView(),n._overlayView=new oi(n),n.addChild(n._tooltipView),n.addChild(n._overlayView),n.getContainer().style.cursor="crosshair",n.registerEvent("mouseMoveEvent",(function(){return i.getChart().getChartStore().getTooltipStore().setActiveIcon(),!1})),n}return i(e,t),e.prototype.getName=function(){return Te},e.prototype.updateMain=function(t){this.updateMainContent(t),this._indicatorView.draw(t),this._gridView.draw(t)},e.prototype.createTooltipView=function(){return new ni(this)},e.prototype.updateMainContent=function(t){},e.prototype.updateOverlay=function(t){this._overlayView.draw(t),this._crosshairLineView.draw(t),this._tooltipView.draw(t)},e}(ke),ai=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._ripplePoint=e.createFigure({name:"circle",attrs:{x:0,y:0,r:0},styles:{style:"fill"}}),e._animationFrameTime=0,e._animation=new dt({iterationCount:1/0}).doFrame((function(t){e._animationFrameTime=t;var i=e.getWidget().getPane();i.getChart().updatePane(0,i.getId())})),e}return i(e,t),e.prototype.drawImp=function(t){var e,i,n,o=this.getWidget(),r=o.getPane(),a=r.getChart(),s=a.getDataList().length-1,l=o.getBounding(),c=r.getAxisComponent(),u=a.getStyles().candle.area,h=[],d=Number.MAX_SAFE_INTEGER,p=Number.MIN_SAFE_INTEGER,g=null;if(this.eachChildren((function(t){var e=t.data,i=t.x,n=null==e?void 0:e[u.value];if(O(n)){var o=c.convertToPixel(n);p===Number.MIN_SAFE_INTEGER&&(p=i),h.push({x:i,y:o}),d=Math.min(d,o),t.dataIndex===s&&(g={x:i,y:o})}})),h.length>0){null===(e=this.createFigure({name:"line",attrs:{coordinates:h},styles:{color:u.lineColor,size:u.lineSize,smooth:u.smooth}}))||void 0===e||e.draw(t);var v=u.backgroundColor,f=void 0;if(L(v)){var y=t.createLinearGradient(0,l.height,0,d);try{v.forEach((function(t){var e=t.offset,i=t.color;y.addColorStop(e,i)}))}catch(t){}f=y}else f=v;t.fillStyle=f,t.beginPath(),t.moveTo(p,l.height),t.lineTo(h[0].x,h[0].y),ie(t,h,u.smooth),t.lineTo(h[h.length-1].x,l.height),t.closePath(),t.fill()}var m=u.point;if(m.show&&V(g)){null===(i=this.createFigure({name:"circle",attrs:{x:g.x,y:g.y,r:m.radius},styles:{style:"fill",color:m.color}}))||void 0===i||i.draw(t);var _=m.rippleRadius;m.animation&&(_=m.radius+this._animationFrameTime/m.animationDuration*(m.rippleRadius-m.radius),this._animation.setDuration(m.animationDuration).start()),null===(n=this._ripplePoint)||void 0===n||n.setAttrs({x:g.x,y:g.y,r:_}).setStyles({style:"fill",color:m.rippleColor}).draw(t)}else this.stopAnimation()},e.prototype.stopAnimation=function(){this._animation.stop()},e}(Je),si=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.drawImp=function(t){var e=this.getWidget().getPane(),i=e.getChart().getChartStore(),n=i.getStyles().candle.priceMark,o=n.high,r=n.low;if(n.show&&(o.show||r.show)){var a=i.getThousandsSeparator(),s=i.getDecimalFoldThreshold(),l=i.getPrecision(),c=e.getAxisComponent(),u=Number.MIN_SAFE_INTEGER,h=0,d=Number.MAX_SAFE_INTEGER,p=0;this.eachChildren((function(t){var e=t.data,i=t.x;V(e)&&(u<e.high&&(u=e.high,h=i),d>e.low&&(d=e.low,p=i))}));var g=c.convertToPixel(u),v=c.convertToPixel(d);o.show&&u!==Number.MIN_SAFE_INTEGER&&this._drawMark(t,q(U(K(u,l.price),a),s),{x:h,y:g},g<v?[-2,-5]:[2,5],o),r.show&&d!==Number.MAX_SAFE_INTEGER&&this._drawMark(t,q(U(K(d,l.price),a),s),{x:p,y:v},g<v?[2,5]:[-2,-5],r)}},e.prototype._drawMark=function(t,e,i,n,o){var r,a,s,l,c,u,h=i.x,d=i.y+n[0];null===(r=this.createFigure({name:"line",attrs:{coordinates:[{x:h-2,y:d+n[0]},{x:h,y:d},{x:h+2,y:d+n[0]}]},styles:{color:o.color}}))||void 0===r||r.draw(t),h>this.getWidget().getBounding().width/2?(c=(l=h-5)-o.textOffset,u="right"):(u="left",c=(l=h+5)+o.textOffset);var p=d+n[1];null===(a=this.createFigure({name:"line",attrs:{coordinates:[{x:h,y:d},{x:h,y:p},{x:l,y:p}]},styles:{color:o.color}}))||void 0===a||a.draw(t),null===(s=this.createFigure({name:"text",attrs:{x:c,y:p,text:e,align:u,baseline:"middle"},styles:{color:o.color,size:o.textSize,family:o.textFamily,weight:o.textWeight}}))||void 0===s||s.draw(t)},e}(Je),li=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.drawImp=function(t){var e,i=this.getWidget(),n=i.getPane(),o=i.getBounding(),r=n.getChart().getChartStore(),a=r.getStyles().candle.priceMark,s=a.last,l=s.line;if(a.show&&s.show&&l.show){var c=n.getAxisComponent(),u=r.getDataList(),h=u[u.length-1];if(null!=h){var d=h.close,p=h.open,g=c.convertToNicePixel(d),v=void 0;v=d>p?s.upColor:d<p?s.downColor:s.noChangeColor,null===(e=this.createFigure({name:"line",attrs:{coordinates:[{x:0,y:g},{x:o.width,y:g}]},styles:{style:l.style,color:v,size:l.size,dashedValue:l.dashedValue}}))||void 0===e||e.draw(t)}}},e}($e),ci={"zh-CN":{time:"时间:",open:"开:",high:"高:",low:"低:",close:"收:",volume:"成交量:",turnover:"成交额:",change:"涨幅:"},"en-US":{time:"Time: ",open:"Open: ",high:"High: ",low:"Low: ",close:"Close: ",volume:"Volume: ",turnover:"Turnover: ",change:"Change: "}};var ui=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.drawImp=function(e){var i=this.getWidget(),n=i.getPane(),o=n.getId(),r=n.getChart().getChartStore(),a=r.getTooltipStore().getCrosshair();if(V(a.kLineData)){var s=i.getBounding(),l=n.getYAxisWidget().getBounding(),c=r.getDataList(),u=r.getPrecision(),h=r.getLocale(),d=r.getCustomApi(),p=r.getThousandsSeparator(),g=r.getDecimalFoldThreshold(),v=r.getTooltipStore().getActiveIcon(),f=r.getIndicatorStore().getInstances(n.getId()),y=r.getTimeScaleStore().getDateTimeFormat(),m=r.getStyles(),_=m.candle,x=m.indicator;if(_.tooltip.showType===t.TooltipShowType.Rect&&x.tooltip.showType===t.TooltipShowType.Rect){var S=this.isDrawTooltip(a,_.tooltip),C=this.isDrawTooltip(a,x.tooltip);this._drawRectTooltip(e,c,f,s,l,a,u,y,h,d,p,g,S,C,_.tooltip.offsetTop,m)}else if(_.tooltip.showType===t.TooltipShowType.Standard&&x.tooltip.showType===t.TooltipShowType.Standard){var b=_.tooltip,T=b.offsetLeft,w=b.offsetTop,E=b.offsetRight,I=s.width-E,P=this._drawCandleStandardTooltip(e,c,o,a,v,u,y,h,d,p,g,T,w,I,_);this.drawIndicatorTooltip(e,o,c,a,v,f,d,p,g,T,P,I,x)}else if(_.tooltip.showType===t.TooltipShowType.Rect&&x.tooltip.showType===t.TooltipShowType.Standard){var D=_.tooltip,M=(T=D.offsetLeft,w=D.offsetTop,E=D.offsetRight,I=s.width-E,this.drawIndicatorTooltip(e,o,c,a,v,f,d,p,g,T,w,I,x));S=this.isDrawTooltip(a,_.tooltip);this._drawRectTooltip(e,c,f,s,l,a,u,y,h,d,p,g,S,!1,M,m)}else{var k=_.tooltip,A=(T=k.offsetLeft,w=k.offsetTop,E=k.offsetRight,I=s.width-E,this._drawCandleStandardTooltip(e,c,o,a,v,u,y,h,d,p,g,T,w,I,_));C=this.isDrawTooltip(a,x.tooltip);this._drawRectTooltip(e,c,f,s,l,a,u,y,h,d,p,g,!1,C,A,m)}}},n.prototype._drawCandleStandardTooltip=function(t,e,i,n,o,r,a,s,l,c,u,h,d,p,g){var v,y,m,_=g.tooltip,x=_.text,S=0,C={x:h,y:d};if(this.isDrawTooltip(n,_)){var b=null!==(v=n.dataIndex)&&void 0!==v?v:0,T=this._getCandleTooltipLegends({prev:null!==(y=e[b-1])&&void 0!==y?y:null,current:n.kLineData,next:null!==(m=e[b+1])&&void 0!==m?m:null},r,a,s,l,c,u,g),w=f(this.classifyTooltipIcons(_.icons),3),E=w[0],I=w[1],P=w[2];S=this.drawStandardTooltipIcons(t,o,E,C,i,"",h,S,p),S=this.drawStandardTooltipIcons(t,o,I,C,i,"",h,S,p),T.length>0&&(S=this.drawStandardTooltipLegends(t,T,C,h,S,p,x)),S=this.drawStandardTooltipIcons(t,o,P,C,i,"",h,S,p)}return C.y+S},n.prototype._drawRectTooltip=function(e,i,n,o,r,a,s,l,c,u,h,d,p,g,v,f){var y,m,_,x,S,C=this,b=f.candle,T=f.indicator,w=b.tooltip,E=T.tooltip;if(p||g){var I=null!==(y=a.dataIndex)&&void 0!==y?y:0,P=this._getCandleTooltipLegends({prev:null!==(m=i[I-1])&&void 0!==m?m:null,current:a.kLineData,next:null!==(_=i[I+1])&&void 0!==_?_:null},s,l,c,u,h,d,b),D=w.offsetLeft,M=w.offsetTop,k=w.offsetRight,A=w.offsetBottom,F=w.text,L=F.marginLeft,R=F.marginRight,B=F.marginTop,O=F.marginBottom,V=F.size,N=F.weight,W=F.family,z=w.rect,Y=z.position,H=z.paddingLeft,X=z.paddingRight,G=z.paddingTop,j=z.paddingBottom,K=z.offsetLeft,Z=z.offsetRight,U=z.offsetTop,q=z.offsetBottom,$=z.borderSize,J=z.borderRadius,tt=z.borderColor,et=z.color,it=0,nt=0,ot=0;p&&(e.font=Q(V,N,W),P.forEach((function(t){var i=t.title,n=t.value,o="".concat(i.text).concat(n.text),r=e.measureText(o).width+L+R;it=Math.max(it,r)})),ot+=(O+B+V)*P.length);var rt=E.text,at=rt.marginLeft,st=rt.marginRight,lt=rt.marginTop,ct=rt.marginBottom,ut=rt.size,ht=rt.weight,dt=rt.family,pt=[];if(g&&(e.font=Q(ut,ht,dt),n.forEach((function(t){var n,o=null!==(n=C.getIndicatorTooltipData(i,a,t,u,h,d,T).values)&&void 0!==n?n:[];pt.push(o),o.forEach((function(t){var i=t.title,n=t.value,o="".concat(i.text).concat(n.text),r=e.measureText(o).width+at+st;it=Math.max(it,r),ot+=lt+ct+ut}))}))),0!==(nt+=it)&&0!==ot){nt+=2*$+H+X,ot+=2*$+G+j;var gt=o.width/2,vt=Y===t.CandleTooltipRectPosition.Pointer&&a.paneId===fe,ft=(null!==(x=a.realX)&&void 0!==x?x:0)>gt,yt=0;if(vt){var mt=a.realX;yt=ft?mt-Z-nt:mt+K}else ft?(yt=K+D,f.yAxis.inside&&f.yAxis.position===t.YAxisPosition.Left&&(yt+=r.width)):(yt=o.width-Z-nt-k,f.yAxis.inside&&f.yAxis.position===t.YAxisPosition.Right&&(yt-=r.width));var _t=v+U;if(vt)(_t=a.y-ot/2)+ot>o.height-q-A&&(_t=o.height-q-ot-A),_t<v+U&&(_t=v+U+M);null===(S=this.createFigure({name:"rect",attrs:{x:yt,y:_t,width:nt,height:ot},styles:{style:t.PolygonType.StrokeFill,color:et,borderColor:tt,borderSize:$,borderRadius:J}}))||void 0===S||S.draw(e);var xt=yt+$+H+L,St=_t+$+G;if(p&&P.forEach((function(t){var i,n;St+=B;var o=t.title;null===(i=C.createFigure({name:"text",attrs:{x:xt,y:St,text:o.text},styles:{color:o.color,size:V,family:W,weight:N}}))||void 0===i||i.draw(e);var r=t.value;null===(n=C.createFigure({name:"text",attrs:{x:yt+nt-$-R-X,y:St,text:r.text,align:"right"},styles:{color:r.color,size:V,family:W,weight:N}}))||void 0===n||n.draw(e),St+=V+O})),g){var Ct=yt+$+H+at;pt.forEach((function(t){t.forEach((function(t){var i,n;St+=lt;var o=t.title,r=t.value;null===(i=C.createFigure({name:"text",attrs:{x:Ct,y:St,text:o.text},styles:{color:o.color,size:ut,family:dt,weight:ht}}))||void 0===i||i.draw(e),null===(n=C.createFigure({name:"text",attrs:{x:yt+nt-$-st-X,y:St,text:r.text,align:"right"},styles:{color:r.color,size:ut,family:dt,weight:ht}}))||void 0===n||n.draw(e),St+=ut+ct}))}))}}}},n.prototype._getCandleTooltipLegends=function(e,i,n,o,r,a,s,l){var c,u,h,p,g,v=l.tooltip,f=v.text.color,y=e.current,m=null!==(u=null===(c=e.prev)||void 0===c?void 0:c.close)&&void 0!==u?u:y.close,_=y.close-m,x=i.price,S=i.volume,C={"{time}":r.formatDate(n,y.timestamp,"YYYY-MM-DD HH:mm",t.FormatDateType.Tooltip),"{open}":q(U(K(y.open,x),a),s),"{high}":q(U(K(y.high,x),a),s),"{low}":q(U(K(y.low,x),a),s),"{close}":q(U(K(y.close,x),a),s),"{volume}":q(U(r.formatBigNumber(K(null!==(h=y.volume)&&void 0!==h?h:v.defaultValue,S)),a),s),"{turnover}":q(U(K(null!==(p=y.turnover)&&void 0!==p?p:v.defaultValue,x),a),s),"{change}":0===m?v.defaultValue:"".concat(U(K(_/m*100),a),"%")};return(null!==(g=R(v.custom)?v.custom(e,l):v.custom)&&void 0!==g?g:[]).map((function(t){var e,i=t.title,n=t.value,r={text:"",color:""};B(i)?r=d({},i):(r.text=i,r.color=f),r.text=function(t,e){var i,n;return null!==(n=null===(i=ci[e])||void 0===i?void 0:i[t])&&void 0!==n?n:t}(r.text,o);var a={text:v.defaultValue,color:""};B(n)?a=d({},n):(a.text=n,a.color=f);var s=a.text.match(/{(\S*)}/);if(null!==s&&s.length>1){var c="{".concat(s[1],"}");a.text=a.text.replace(c,null!==(e=C[c])&&void 0!==e?e:v.defaultValue),"{change}"===c&&(a.color=0===_?l.priceMark.last.noChangeColor:_>0?l.priceMark.last.upColor:l.priceMark.last.downColor)}return{title:r,value:a}}))},n}(ni),hi=function(e){function n(t,i){var n=e.call(this,t,i)||this;return n._candleBarView=new ti(n),n._candleAreaView=new ai(n),n._candleHighLowPriceView=new si(n),n._candleLastPriceLineView=new li(n),n.addChild(n._candleBarView),n}return i(n,e),n.prototype.updateMainContent=function(e){this.getPane().getChart().getStyles().candle.type!==t.CandleType.Area?(this._candleBarView.draw(e),this._candleHighLowPriceView.draw(e),this._candleAreaView.stopAnimation()):this._candleAreaView.draw(e),this._candleLastPriceLineView.draw(e)},n.prototype.createTooltipView=function(){return new ui(this)},n}(ri),di=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.drawImp=function(t){var e,i,n=this,o=this.getWidget(),r=o.getPane(),a=o.getBounding(),s=r.getAxisComponent(),l=this.getAxisStyles(r.getChart().getStyles());if(l.show){l.axisLine.show&&(null===(e=this.createFigure({name:"line",attrs:this.createAxisLine(a,l),styles:l.axisLine}))||void 0===e||e.draw(t));var c=s.getTicks();if(l.tickLine.show)this.createTickLines(c,a,l).forEach((function(e){var i;null===(i=n.createFigure({name:"line",attrs:e,styles:l.tickLine}))||void 0===i||i.draw(t)}));if(l.tickText.show){var u=this.createTickTexts(c,a,l);null===(i=this.createFigure({name:"text",attrs:u,styles:l.tickText}))||void 0===i||i.draw(t)}}},e}($e),pi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.getAxisStyles=function(t){return t.yAxis},e.prototype.createAxisLine=function(t,e){var i,n=this.getWidget().getPane().getAxisComponent(),o=e.axisLine.size;return{coordinates:[{x:i=n.isFromZero()?0:t.width-o,y:0},{x:i,y:t.height}]}},e.prototype.createTickLines=function(t,e,i){var n=this.getWidget().getPane().getAxisComponent(),o=i.axisLine,r=i.tickLine,a=0,s=0;return n.isFromZero()?(a=0,o.show&&(a+=o.size),s=a+r.length):(a=e.width,o.show&&(a-=o.size),s=a-r.length),t.map((function(t){return{coordinates:[{x:a,y:t.coord},{x:s,y:t.coord}]}}))},e.prototype.createTickTexts=function(t,e,i){var n=this.getWidget().getPane().getAxisComponent(),o=i.axisLine,r=i.tickLine,a=i.tickText,s=0;n.isFromZero()?(s=a.marginStart,o.show&&(s+=o.size),r.show&&(s+=r.length)):(s=e.width-a.marginEnd,o.show&&(s-=o.size),r.show&&(s-=r.length));var l=this.getWidget().getPane().getAxisComponent().isFromZero()?"left":"right";return t.map((function(t){return{x:s,y:t.coord,text:t.text,align:l,baseline:"middle"}}))},e}(di),gi=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.drawImp=function(e){var i,n=this.getWidget(),o=n.getPane(),r=n.getBounding(),a=o.getChart().getChartStore(),s=a.getStyles().candle.priceMark,l=s.last,c=l.text;if(s.show&&l.show&&c.show){var u=a.getPrecision(),h=o.getAxisComponent(),p=a.getDataList(),g=p[p.length-1];if(V(g)){var v=g.close,f=g.open,y=h.convertToNicePixel(v),m=void 0;m=v>f?l.upColor:v<f?l.downColor:l.noChangeColor;var _=void 0;if(h.getType()===t.YAxisType.Percentage){var x=a.getVisibleFirstData().close;_="".concat(((v-x)/x*100).toFixed(2),"%")}else _=K(v,u.price);_=q(U(_,a.getThousandsSeparator()),a.getDecimalFoldThreshold());var S=void 0,C=void 0;h.isFromZero()?(S=0,C="left"):(S=r.width,C="right"),null===(i=this.createFigure({name:"text",attrs:{x:S,y:y,text:_,align:C,baseline:"middle"},styles:d(d({},c),{backgroundColor:m})}))||void 0===i||i.draw(e)}}},n}($e),vi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.drawImp=function(t){var e=this,i=this.getWidget(),n=i.getPane(),o=i.getBounding(),r=n.getChart().getChartStore(),a=r.getCustomApi(),s=r.getStyles().indicator,l=s.lastValueMark,c=l.text;if(l.show){var u=n.getAxisComponent(),h=r.getDataList(),p=h.length-1,g=r.getIndicatorStore().getInstances(n.getId()),v=r.getThousandsSeparator(),f=r.getDecimalFoldThreshold();g.forEach((function(i){var n=i.result[p];if(V(n)&&i.visible){var r=i.precision;it(h,i,p,s,(function(s,l){var h,p=n[s.key];if(O(p)){var g=u.convertToNicePixel(p),y=K(p,r);i.shouldFormatBigNumber&&(y=a.formatBigNumber(y)),y=q(U(y,v),f);var m=void 0,_=void 0;u.isFromZero()?(m=0,_="left"):(m=o.width,_="right"),null===(h=e.createFigure({name:"text",attrs:{x:m,y:g,text:y,align:_,baseline:"middle"},styles:d(d({},c),{backgroundColor:l.color})}))||void 0===h||h.draw(t)}}))}}))}},e}($e),fi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.coordinateToPointTimestampDataIndexFlag=function(){return!1},e.prototype.drawDefaultFigures=function(t,e,i,n,o,r,a,s,l,c,u,h,d,p){this.drawFigures(t,e,this.getDefaultFigures(e,i,n,o,r,a,s,l,u,h,p),c)},e.prototype.getDefaultFigures=function(t,e,i,n,o,r,a,s,l,c,u){var h,d,p=[];if(t.needDefaultYAxisFigure&&t.id===(null===(h=u.instance)||void 0===h?void 0:h.id)&&u.paneId===this.getWidget().getPane().getId()){var g,v,f=Number.MAX_SAFE_INTEGER,y=Number.MIN_SAFE_INTEGER;null!==(d=null==c?void 0:c.isFromZero())&&void 0!==d&&d?(g="left",v=0):(g="right",v=i.width),e.forEach((function(e,i){var o=t.points[i];if(O(o.value)){f=Math.min(f,e.y),y=Math.max(y,e.y);var r=q(U(K(o.value,n.price),a),s);p.push({type:"text",attrs:{x:v,y:e.y,text:r,align:g,baseline:"middle"},ignoreEvent:!0})}})),e.length>1&&p.unshift({type:"rect",attrs:{x:0,y:f,width:i.width,height:y-f},ignoreEvent:!0})}return p},e.prototype.getFigures=function(t,e,i,n,o,r,a,s,l,c,u){var h,d;return null!==(d=null===(h=t.createYAxisFigures)||void 0===h?void 0:h.call(t,{overlay:t,coordinates:e,bounding:i,barSpace:n,precision:o,thousandsSeparator:r,decimalFoldThreshold:a,dateTimeFormat:s,defaultStyles:l,xAxis:c,yAxis:u}))&&void 0!==d?d:[]},e}(oi),yi=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.drawImp=function(t){var e,i=this.getWidget(),n=i.getPane(),o=i.getBounding(),r=i.getPane().getChart().getChartStore(),a=r.getTooltipStore().getCrosshair(),s=r.getStyles().crosshair;if(W(a.paneId)&&this.compare(a,n.getId())&&s.show){var l=this.getDirectionStyles(s),c=l.text;if(l.show&&c.show){var u=n.getAxisComponent(),h=this.getText(a,r,u);t.font=Q(c.size,c.weight,c.family),null===(e=this.createFigure({name:"text",attrs:this.getTextAttrs(h,t.measureText(h).width,a,o,u,c),styles:c}))||void 0===e||e.draw(t)}}},n.prototype.compare=function(t,e){return t.paneId===e},n.prototype.getDirectionStyles=function(t){return t.horizontal},n.prototype.getText=function(e,i,n){var o,r=n,a=n.convertFromPixel(e.y);if(r.getType()===t.YAxisType.Percentage){var s=i.getVisibleFirstData();o="".concat(((a-s.close)/s.close*100).toFixed(2),"%")}else{var l=i.getIndicatorStore().getInstances(e.paneId),c=0,u=!1;r.isInCandle()?c=i.getPrecision().price:l.forEach((function(t){c=Math.max(t.precision,c),u||(u=t.shouldFormatBigNumber)})),o=K(a,c),u&&(o=i.getCustomApi().formatBigNumber(o))}return q(U(o,i.getThousandsSeparator()),i.getDecimalFoldThreshold())},n.prototype.getTextAttrs=function(t,e,i,n,o,r){var a,s;return o.isFromZero()?(a=0,s="left"):(a=n.width,s="right"),{x:a,y:i.y,text:t,align:s,baseline:"middle"}},n}($e),mi=function(t){function e(e,i){var n=t.call(this,e,i)||this;return n._yAxisView=new pi(n),n._candleLastPriceLabelView=new gi(n),n._indicatorLastValueView=new vi(n),n._overlayYAxisView=new fi(n),n._crosshairHorizontalLabelView=new yi(n),n.getContainer().style.cursor="ns-resize",n.addChild(n._overlayYAxisView),n}return i(e,t),e.prototype.getName=function(){return Ee},e.prototype.updateMain=function(t){this._yAxisView.draw(t),this.getPane().getAxisComponent().isInCandle()&&this._candleLastPriceLabelView.draw(t),this._indicatorLastValueView.draw(t)},e.prototype.updateOverlay=function(t){this._overlayYAxisView.draw(t),this._crosshairHorizontalLabelView.draw(t)},e}(ke),_i=function(){function t(t){this._range={from:0,to:0,range:0,realFrom:0,realTo:0,realRange:0},this._prevRange={from:0,to:0,range:0,realFrom:0,realTo:0,realRange:0},this._ticks=[],this._autoCalcTickFlag=!0,this._parent=t}return t.prototype.getParent=function(){return this._parent},t.prototype.buildTicks=function(t){if(this._autoCalcTickFlag&&(this._range=this.calcRange()),this._prevRange.from!==this._range.from||this._prevRange.to!==this._range.to||t){this._prevRange=this._range;var e=this.optimalTicks(this._calcTicks());return this._ticks=this.createTicks({range:this._range,bounding:this.getSelfBounding(),defaultTicks:e}),!0}return!1},t.prototype.getTicks=function(){return this._ticks},t.prototype.getScrollZoomEnabled=function(){var t;return null===(t=this.getParent().getOptions().axisOptions.scrollZoomEnabled)||void 0===t||t},t.prototype.setRange=function(t){this._autoCalcTickFlag=!1,this._range=t},t.prototype.getRange=function(){return this._range},t.prototype.setAutoCalcTickFlag=function(t){this._autoCalcTickFlag=t},t.prototype.getAutoCalcTickFlag=function(){return this._autoCalcTickFlag},t.prototype._calcTicks=function(){var t=this._range,e=t.realFrom,i=t.realTo,n=t.realRange,o=[];if(n>=0){var r=f(this._calcTickInterval(n),2),a=r[0],s=r[1],l=mt(Math.ceil(e/a)*a,s),c=mt(Math.floor(i/a)*a,s),u=0,h=l;if(0!==a)for(;h<=c;){var d=h.toFixed(s);o[u]={text:d,coord:0,value:d},++u,h+=a}}return o},t.prototype._calcTickInterval=function(t){var e,i,n,o,r=(e=t/8,i=Math.floor(xt(e)),n=St(i),e=((o=e/n)<1.5?1:o<2.5?2:o<3.5?3:o<4.5?4:o<5.5?5:o<6.5?6:8)*n,i>=-20?+e.toFixed(i<0?-i:0):e),a=function(t){var e=t.toString(),i=e.indexOf("e");if(i>0){var n=+e.slice(i+1);return n<0?-n:0}var o=e.indexOf(".");return o<0?0:e.length-1-o}(r);return[r,a]},t}(),xi=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.calcRange=function(){var e,i,n,o,r=this.getParent(),a=r.getChart(),s=a.getChartStore(),l=Number.MAX_SAFE_INTEGER,c=Number.MIN_SAFE_INTEGER,u=[],h=!1,d=Number.MAX_SAFE_INTEGER,p=Number.MIN_SAFE_INTEGER,g=Number.MAX_SAFE_INTEGER;s.getIndicatorStore().getInstances(r.getId()).forEach((function(t){var e,i,n;h||(h=null!==(e=t.shouldOhlc)&&void 0!==e&&e),g=Math.min(g,t.precision),O(t.minValue)&&(d=Math.min(d,t.minValue)),O(t.maxValue)&&(p=Math.max(p,t.maxValue)),u.push({figures:null!==(i=t.figures)&&void 0!==i?i:[],result:null!==(n=t.result)&&void 0!==n?n:[]})}));var v=4,f=this.isInCandle();if(f){var y=s.getPrecision().price;v=g!==Number.MAX_SAFE_INTEGER?Math.min(g,y):y}else g!==Number.MAX_SAFE_INTEGER&&(v=g);var m=s.getVisibleDataList(),_=a.getStyles().candle,x=_.type===t.CandleType.Area,S=_.area.value,C=f&&!x||!f&&h;m.forEach((function(t){var e=t.dataIndex,i=t.data;if(V(i)&&(C&&(l=Math.min(l,i.low),c=Math.max(c,i.high)),f&&x)){var n=i[S];O(n)&&(l=Math.min(l,n),c=Math.max(c,n))}u.forEach((function(t){var i,n=t.figures,o=null!==(i=t.result[e])&&void 0!==i?i:{};n.forEach((function(t){var e=o[t.key];O(e)&&(l=Math.min(l,e),c=Math.max(c,e))}))}))})),l!==Number.MAX_SAFE_INTEGER&&c!==Number.MIN_SAFE_INTEGER?(l=Math.min(d,l),c=Math.max(p,c)):(l=0,c=10);var b,T=this.getType();switch(T){case t.YAxisType.Percentage:var w=s.getVisibleFirstData();V(w)&&O(w.close)&&(l=(l-w.close)/w.close*100,c=(c-w.close)/w.close*100),b=Math.pow(10,-2);break;case t.YAxisType.Log:l=xt(l),c=xt(c),b=.05*St(-v);break;default:b=St(-v)}if(l===c||Math.abs(l-c)<b){var E=d===l,I=p===c;l=E?l:I?l-8*b:l-4*b,c=I?c:E?c+8*b:c+4*b}var P=null!==(i=null===(e=this.getParent().getYAxisWidget())||void 0===e?void 0:e.getBounding().height)&&void 0!==i?i:0,D=r.getOptions().gap,M=null!==(n=null==D?void 0:D.top)&&void 0!==n?n:.2;M>=1&&(M/=P);var k=null!==(o=null==D?void 0:D.bottom)&&void 0!==o?o:.1;k>=1&&(k/=P);var A,F,L,R=Math.abs(c-l);return l-=R*k,c+=R*M,R=Math.abs(c-l),T===t.YAxisType.Log?(A=St(l),F=St(c),L=Math.abs(F-A)):(A=l,F=c,L=R),{from:l,to:c,range:R,realFrom:A,realTo:F,realRange:L}},n.prototype._innerConvertToPixel=function(t){var e,i,n=null!==(i=null===(e=this.getParent().getYAxisWidget())||void 0===e?void 0:e.getBounding().height)&&void 0!==i?i:0,o=this.getRange(),r=(t-o.from)/o.range;return this.isReverse()?Math.round(r*n):Math.round((1-r)*n)},n.prototype.isInCandle=function(){return this.getParent().getId()===fe},n.prototype.getType=function(){return this.isInCandle()?this.getParent().getChart().getStyles().yAxis.type:t.YAxisType.Normal},n.prototype.getPosition=function(){return this.getParent().getChart().getStyles().yAxis.position},n.prototype.isReverse=function(){return!!this.isInCandle()&&this.getParent().getChart().getStyles().yAxis.reverse},n.prototype.isFromZero=function(){var e=this.getParent().getChart().getStyles().yAxis,i=e.inside;return e.position===t.YAxisPosition.Left&&i||e.position===t.YAxisPosition.Right&&!i},n.prototype.optimalTicks=function(e){var i,n,o=this,r=this.getParent(),a=null!==(n=null===(i=r.getYAxisWidget())||void 0===i?void 0:i.getBounding().height)&&void 0!==n?n:0,s=r.getChart().getChartStore(),l=s.getCustomApi(),c=[],u=this.getType(),h=s.getIndicatorStore().getInstances(r.getId()),d=s.getThousandsSeparator(),p=s.getDecimalFoldThreshold(),g=0,v=!1;this.isInCandle()?g=s.getPrecision().price:h.forEach((function(t){g=Math.max(g,t.precision),v||(v=t.shouldFormatBigNumber)}));var f,y=s.getStyles().xAxis.tickText.size;return e.forEach((function(e){var i,n=e.value,r=o._innerConvertToPixel(+n);switch(u){case t.YAxisType.Percentage:i="".concat(K(n,2),"%");break;case t.YAxisType.Log:r=o._innerConvertToPixel(xt(+n)),i=K(n,g);break;default:i=K(n,g),v&&(i=l.formatBigNumber(n))}i=q(U(i,d),p);var s=O(f);r>y&&r<a-y&&(s&&Math.abs(f-r)>2*y||!s)&&(c.push({text:i,coord:r,value:n}),f=r)})),c},n.prototype.getAutoSize=function(){var e=this.getParent(),i=e.getChart(),n=i.getStyles(),o=n.yAxis,r=o.size;if("auto"!==r)return r;var a=i.getChartStore(),s=a.getCustomApi(),l=0;if(o.show&&(o.axisLine.show&&(l+=o.axisLine.size),o.tickLine.show&&(l+=o.tickLine.length),o.tickText.show)){var c=0;this.getTicks().forEach((function(t){c=Math.max(c,J(t.text,o.tickText.size,o.tickText.weight,o.tickText.family))})),l+=o.tickText.marginStart+o.tickText.marginEnd+c}var u=n.crosshair,h=0;if(u.show&&u.horizontal.show&&u.horizontal.text.show){var d=a.getIndicatorStore().getInstances(e.getId()),p=0,g=!1;d.forEach((function(t){p=Math.max(t.precision,p),g||(g=t.shouldFormatBigNumber)}));var v=2;if(this.getType()!==t.YAxisType.Percentage)if(this.isInCandle()){var f=a.getPrecision().price,y=n.indicator.lastValueMark;v=y.show&&y.text.show?Math.max(p,f):f}else v=p;var m=K(this.getRange().to,v);g&&(m=s.formatBigNumber(m)),m=q(m,a.getDecimalFoldThreshold()),h+=u.horizontal.text.paddingLeft+u.horizontal.text.paddingRight+2*u.horizontal.text.borderSize+J(m,u.horizontal.text.size,u.horizontal.text.weight,u.horizontal.text.family)}return Math.max(l,h)},n.prototype.getSelfBounding=function(){return this.getParent().getYAxisWidget().getBounding()},n.prototype.convertFromPixel=function(e){var i,n,o=null!==(n=null===(i=this.getParent().getYAxisWidget())||void 0===i?void 0:i.getBounding().height)&&void 0!==n?n:0,r=this.getRange(),a=r.from,s=r.range,l=(this.isReverse()?e/o:1-e/o)*s+a;switch(this.getType()){case t.YAxisType.Percentage:var c=this.getParent().getChart().getChartStore().getVisibleFirstData();return V(c)&&O(c.close)?c.close*l/100+c.close:0;case t.YAxisType.Log:return St(l);default:return l}},n.prototype.convertToRealValue=function(e){var i=e;return this.getType()===t.YAxisType.Log&&(i=St(e)),i},n.prototype.convertToPixel=function(e){var i=e;switch(this.getType()){case t.YAxisType.Percentage:var n=this.getParent().getChart().getChartStore().getVisibleFirstData();V(n)&&O(n.close)&&(i=(e-n.close)/n.close*100);break;case t.YAxisType.Log:i=xt(e);break;default:i=e}return this._innerConvertToPixel(i)},n.prototype.convertToNicePixel=function(t){var e,i,n=null!==(i=null===(e=this.getParent().getYAxisWidget())||void 0===e?void 0:e.getBounding().height)&&void 0!==i?i:0,o=this.convertToPixel(t);return Math.round(Math.max(.05*n,Math.min(o,.98*n)))},n.extend=function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.createTicks=function(e){return t.createTicks(e)},n}(n);return e},n}(_i),Si={default:xi.extend({name:"default",createTicks:function(t){return t.defaultTicks}})};var Ci=function(){function t(t,e,i,n){this._bounding=De(),this._chart=i,this._id=n,this._init(t,e)}return t.prototype._init=function(t,e){this._rootContainer=t,this._container=ft("div",{width:"100%",margin:"0",padding:"0",position:"relative",overflow:"hidden",boxSizing:"border-box"}),null!==e?t.insertBefore(this._container,e):t.appendChild(this._container)},t.prototype.getContainer=function(){return this._container},t.prototype.getId=function(){return this._id},t.prototype.getChart=function(){return this._chart},t.prototype.getBounding=function(){return this._bounding},t.prototype.update=function(t){this._bounding.height!==this._container.clientHeight&&(this._container.style.height="".concat(this._bounding.height,"px")),this.updateImp(null!=t?t:3,this._container,this._bounding)},t.prototype.destroy=function(){this._rootContainer.removeChild(this._container)},t}(),bi=function(t){function e(e,i,n,o,r){var a=t.call(this,e,i,n,o)||this;a._yAxisWidget=null,a._options={minHeight:30,dragEnabled:!0,gap:{top:.2,bottom:.1},axisOptions:{name:"default",scrollZoomEnabled:!0}};var s=a.getContainer();return a._mainWidget=a.createMainWidget(s),a._yAxisWidget=a.createYAxisWidget(s),a.setOptions(r),a}return i(e,t),e.prototype.setOptions=function(t){var e,i,n,o,r,a=null===(e=t.axisOptions)||void 0===e?void 0:e.name;return(this._options.axisOptions.name!==a&&W(a)||!V(this._axis))&&(this._axis=this.createAxisComponent(null!=a?a:"default")),A(this._options,t),this.getId()===me?(o=this.getMainWidget().getContainer(),r="ew-resize"):(o=this.getYAxisWidget().getContainer(),r="ns-resize"),null===(n=null===(i=t.axisOptions)||void 0===i?void 0:i.scrollZoomEnabled)||void 0===n||n?o.style.cursor=r:o.style.cursor="default",this},e.prototype.getOptions=function(){return this._options},e.prototype.getAxisComponent=function(){return this._axis},e.prototype.setBounding=function(t,e,i){var n,o;A(this.getBounding(),t);var r={};return V(t.height)&&(r.height=t.height),V(t.top)&&(r.top=t.top),this._mainWidget.setBounding(r),null===(n=this._yAxisWidget)||void 0===n||n.setBounding(r),V(e)&&this._mainWidget.setBounding(e),V(i)&&(null===(o=this._yAxisWidget)||void 0===o||o.setBounding(i)),this},e.prototype.getMainWidget=function(){return this._mainWidget},e.prototype.getYAxisWidget=function(){return this._yAxisWidget},e.prototype.updateImp=function(t){var e;this._mainWidget.update(t),null===(e=this._yAxisWidget)||void 0===e||e.update(t)},e.prototype.destroy=function(){var e;t.prototype.destroy.call(this),this._mainWidget.destroy(),null===(e=this._yAxisWidget)||void 0===e||e.destroy()},e.prototype.getImage=function(t){var e=this.getBounding(),i=e.width,n=e.height,o=ft("canvas",{width:"".concat(i,"px"),height:"".concat(n,"px"),boxSizing:"border-box"}),r=o.getContext("2d"),a=$(o);o.width=i*a,o.height=n*a,r.scale(a,a);var s=this._mainWidget.getBounding();if(r.drawImage(this._mainWidget.getImage(t),s.left,0,s.width,s.height),null!==this._yAxisWidget){var l=this._yAxisWidget.getBounding();r.drawImage(this._yAxisWidget.getImage(t),l.left,0,l.width,l.height)}return o},e.prototype.createYAxisWidget=function(t){return null},e}(Ci),Ti=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.createAxisComponent=function(t){var e=function(t){var e;return null!==(e=Si[t])&&void 0!==e?e:Si.default}(null!=t?t:"default");return new e(this)},e.prototype.createMainWidget=function(t){return new ri(t,this)},e.prototype.createYAxisWidget=function(t){return new mi(t,this)},e}(bi),wi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.createMainWidget=function(t){return new hi(t,this)},e}(Ti),Ei=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.getAxisStyles=function(t){return t.xAxis},e.prototype.createAxisLine=function(t){return{coordinates:[{x:0,y:0},{x:t.width,y:0}]}},e.prototype.createTickLines=function(t,e,i){var n=i.tickLine,o=i.axisLine.size;return t.map((function(t){return{coordinates:[{x:t.coord,y:0},{x:t.coord,y:o+n.length}]}}))},e.prototype.createTickTexts=function(t,e,i){var n=i.tickText,o=i.axisLine.size,r=i.tickLine.length;return t.map((function(t){return{x:t.coord,y:o+r+n.marginStart,text:t.text,align:"center",baseline:"top"}}))},e}(di),Ii=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.coordinateToPointTimestampDataIndexFlag=function(){return!0},n.prototype.coordinateToPointValueFlag=function(){return!1},n.prototype.getCompleteOverlays=function(t){return t.getInstances()},n.prototype.getProgressOverlay=function(t){return t.instance},n.prototype.getDefaultFigures=function(e,i,n,o,r,a,s,l,c,u,h){var d,p=[];if(e.needDefaultXAxisFigure&&e.id===(null===(d=h.instance)||void 0===d?void 0:d.id)){var g=Number.MAX_SAFE_INTEGER,v=Number.MIN_SAFE_INTEGER;i.forEach((function(i,n){g=Math.min(g,i.x),v=Math.max(v,i.x);var o=e.points[n];if(O(o.timestamp)){var s=a.formatDate(r,o.timestamp,"YYYY-MM-DD HH:mm",t.FormatDateType.Crosshair);p.push({type:"text",attrs:{x:i.x,y:0,text:s,align:"center"},ignoreEvent:!0})}})),i.length>1&&p.unshift({type:"rect",attrs:{x:g,y:0,width:v-g,height:n.height},ignoreEvent:!0})}return p},n.prototype.getFigures=function(t,e,i,n,o,r,a,s,l,c,u){var h,d;return null!==(d=null===(h=t.createXAxisFigures)||void 0===h?void 0:h.call(t,{overlay:t,coordinates:e,bounding:i,barSpace:n,precision:o,thousandsSeparator:r,decimalFoldThreshold:a,dateTimeFormat:s,defaultStyles:l,xAxis:c,yAxis:u}))&&void 0!==d?d:[]},n}(fi),Pi=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.compare=function(t){return V(t.kLineData)&&t.dataIndex===t.realDataIndex},n.prototype.getDirectionStyles=function(t){return t.vertical},n.prototype.getText=function(e,i){var n,o=null===(n=e.kLineData)||void 0===n?void 0:n.timestamp;return i.getCustomApi().formatDate(i.getTimeScaleStore().getDateTimeFormat(),o,"YYYY-MM-DD HH:mm",t.FormatDateType.Crosshair)},n.prototype.getTextAttrs=function(t,e,i,n,o,r){var a,s=i.realX,l="center";return s-e/2-r.paddingLeft<0?(a=0,l="left"):s+e/2+r.paddingRight>n.width?(a=n.width,l="right"):a=s,{x:a,y:0,text:t,align:l,baseline:"top"}},n}(yi),Di=function(t){function e(e,i){var n=t.call(this,e,i)||this;return n._xAxisView=new Ei(n),n._overlayXAxisView=new Ii(n),n._crosshairVerticalLabelView=new Pi(n),n.getContainer().style.cursor="ew-resize",n.addChild(n._overlayXAxisView),n}return i(e,t),e.prototype.getName=function(){return we},e.prototype.updateMain=function(t){this._xAxisView.draw(t)},e.prototype.updateOverlay=function(t){this._overlayXAxisView.draw(t),this._crosshairVerticalLabelView.draw(t)},e}(ke),Mi=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.calcRange=function(){var t=this.getParent().getChart().getChartStore().getTimeScaleStore().getVisibleRange(),e=t.from,i=t.to,n=i-1,o=i-e;return{from:e,to:n,range:o,realFrom:e,realTo:n,realRange:o}},n.prototype.optimalTicks=function(e){var i,n,o=this.getParent().getChart(),r=o.getChartStore(),a=r.getCustomApi().formatDate,s=[],l=e.length,c=r.getDataList();if(l>0){var u=r.getTimeScaleStore().getDateTimeFormat(),h=o.getStyles().xAxis.tickText,d=J("00-00 00:00",h.size,h.weight,h.family),p=parseInt(e[0].value,10),g=this.convertToPixel(p),v=1;if(l>1){var f=parseInt(e[1].value,10),y=this.convertToPixel(f),m=Math.abs(y-g);m<d&&(v=Math.ceil(d/m))}for(var _=0;_<l;_+=v){var x=parseInt(e[_].value,10),S=c[x].timestamp,C=a(u,S,"HH:mm",t.FormatDateType.XAxis);if(0!==_){var b=c[parseInt(e[_-v].value,10)].timestamp;C=null!==(i=this._optimalTickLabel(a,u,S,b))&&void 0!==i?i:C}var T=this.convertToPixel(x);s.push({text:C,coord:T,value:S})}if(1===s.length)s[0].text=a(u,s[0].value,"YYYY-MM-DD HH:mm",t.FormatDateType.XAxis);else{var w=s[0].value,E=s[1].value;if(V(s[2])){var I=s[2].text;/^[0-9]{2}-[0-9]{2}$/.test(I)?s[0].text=a(u,w,"MM-DD",t.FormatDateType.XAxis):/^[0-9]{4}-[0-9]{2}$/.test(I)?s[0].text=a(u,w,"YYYY-MM",t.FormatDateType.XAxis):/^[0-9]{4}$/.test(I)&&(s[0].text=a(u,w,"YYYY",t.FormatDateType.XAxis))}else s[0].text=null!==(n=this._optimalTickLabel(a,u,w,E))&&void 0!==n?n:s[0].text}}return s},n.prototype._optimalTickLabel=function(e,i,n,o){var r=e(i,n,"YYYY",t.FormatDateType.XAxis),a=e(i,n,"YYYY-MM",t.FormatDateType.XAxis),s=e(i,n,"MM-DD",t.FormatDateType.XAxis);return r!==e(i,o,"YYYY",t.FormatDateType.XAxis)?r:a!==e(i,o,"YYYY-MM",t.FormatDateType.XAxis)?a:s!==e(i,o,"MM-DD",t.FormatDateType.XAxis)?s:null},n.prototype.getAutoSize=function(){var t=this.getParent().getChart().getStyles(),e=t.xAxis,i=e.size;if("auto"!==i)return i;var n=t.crosshair,o=0;e.show&&(e.axisLine.show&&(o+=e.axisLine.size),e.tickLine.show&&(o+=e.tickLine.length),e.tickText.show&&(o+=e.tickText.marginStart+e.tickText.marginEnd+e.tickText.size));var r=0;return n.show&&n.vertical.show&&n.vertical.text.show&&(r+=n.vertical.text.paddingTop+n.vertical.text.paddingBottom+2*n.vertical.text.borderSize+n.vertical.text.size),Math.max(o,r)},n.prototype.getSelfBounding=function(){return this.getParent().getMainWidget().getBounding()},n.prototype.convertTimestampFromPixel=function(t){var e=this.getParent().getChart().getChartStore().getTimeScaleStore(),i=e.coordinateToDataIndex(t);return e.dataIndexToTimestamp(i)},n.prototype.convertTimestampToPixel=function(t){var e=this.getParent().getChart().getChartStore().getTimeScaleStore(),i=e.timestampToDataIndex(t);return e.dataIndexToCoordinate(i)},n.prototype.convertFromPixel=function(t){return this.getParent().getChart().getChartStore().getTimeScaleStore().coordinateToDataIndex(t)},n.prototype.convertToPixel=function(t){return this.getParent().getChart().getChartStore().getTimeScaleStore().dataIndexToCoordinate(t)},n.extend=function(t){var e=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return i(n,e),n.prototype.createTicks=function(e){return t.createTicks(e)},n}(n);return e},n}(_i),ki={default:Mi.extend({name:"default",createTicks:function(t){return t.defaultTicks}})};var Ai=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.createAxisComponent=function(t){var e=function(t){var e;return null!==(e=ki[t])&&void 0!==e?e:ki.default}(t);return new e(this)},e.prototype.createMainWidget=function(t){return new Di(t,this)},e}(bi);var Fi=function(e){function n(t,i){var n,o,r,a=e.call(this,t,i)||this;return a._dragFlag=!1,a._dragStartY=0,a._topPaneHeight=0,a._bottomPaneHeight=0,a._pressedMouseMoveEvent=(n=a._pressedTouchMouseMoveEvent,o=20,r=0,function(){var t=Date.now();t-r>o&&(n.apply(this,arguments),r=t)}),a.registerEvent("touchStartEvent",a._mouseDownEvent.bind(a)).registerEvent("touchMoveEvent",a._pressedMouseMoveEvent.bind(a)).registerEvent("touchEndEvent",a._mouseUpEvent.bind(a)).registerEvent("mouseDownEvent",a._mouseDownEvent.bind(a)).registerEvent("mouseUpEvent",a._mouseUpEvent.bind(a)).registerEvent("pressedMouseMoveEvent",a._pressedMouseMoveEvent.bind(a)).registerEvent("mouseEnterEvent",a._mouseEnterEvent.bind(a)).registerEvent("mouseLeaveEvent",a._mouseLeaveEvent.bind(a)),a}return i(n,e),n.prototype.getName=function(){return Ie},n.prototype.checkEventOn=function(){return!0},n.prototype._mouseDownEvent=function(t){this._dragFlag=!0,this._dragStartY=t.pageY;var e=this.getPane();return this._topPaneHeight=e.getTopPane().getBounding().height,this._bottomPaneHeight=e.getBottomPane().getBounding().height,!0},n.prototype._mouseUpEvent=function(){return this._dragFlag=!1,this._mouseLeaveEvent()},n.prototype._pressedTouchMouseMoveEvent=function(e){var i=e.pageY-this._dragStartY,n=this.getPane(),o=n.getTopPane(),r=n.getBottomPane(),a=i<0;if(null!==o&&(null==r?void 0:r.getOptions().dragEnabled)){var s=void 0,l=void 0,c=void 0,u=void 0;a?(s=o,l=r,c=this._topPaneHeight,u=this._bottomPaneHeight):(s=r,l=o,c=this._bottomPaneHeight,u=this._topPaneHeight);var h=s.getOptions().minHeight;if(c>h){var d=Math.max(c-Math.abs(i),h),p=c-d;s.setBounding({height:d}),l.setBounding({height:u+p});var g=n.getChart();g.getChartStore().getActionStore().execute(t.ActionType.OnPaneDrag,{paneId:n.getId()}),g.adjustPaneViewport(!0,!0,!0,!0,!0)}}return!0},n.prototype._mouseEnterEvent=function(){var t,e=this.getPane(),i=e.getBottomPane();if(null!==(t=null==i?void 0:i.getOptions().dragEnabled)&&void 0!==t&&t){var n=e.getChart().getStyles().separator;return this.getContainer().style.background=n.activeBackgroundColor,!0}return!1},n.prototype._mouseLeaveEvent=function(){return!this._dragFlag&&(this.getContainer().style.background="",!0)},n.prototype.createContainer=function(){return ft("div",{width:"100%",height:"".concat(7,"px"),margin:"0",padding:"0",position:"absolute",top:"-3px",zIndex:"20",boxSizing:"border-box",cursor:"ns-resize"})},n.prototype.updateImp=function(t,e,i){if(4===i||2===i){var n=this.getPane().getChart().getStyles().separator;t.style.top="".concat(-Math.floor((7-n.size)/2),"px"),t.style.height="".concat(7,"px")}},n}(Me),Li=function(t){function e(e,i,n,o,r,a){var s=t.call(this,e,i,n,o)||this;return s.getContainer().style.overflow="",s._topPane=r,s._bottomPane=a,s._separatorWidget=new Fi(s.getContainer(),s),s}return i(e,t),e.prototype.setBounding=function(t){return A(this.getBounding(),t),this},e.prototype.getTopPane=function(){return this._topPane},e.prototype.setTopPane=function(t){return this._topPane=t,this},e.prototype.getBottomPane=function(){return this._bottomPane},e.prototype.setBottomPane=function(t){return this._bottomPane=t,this},e.prototype.getWidget=function(){return this._separatorWidget},e.prototype.getImage=function(t){var e=this.getBounding(),i=e.width,n=e.height,o=this.getChart().getStyles().separator,r=ft("canvas",{width:"".concat(i,"px"),height:"".concat(n,"px"),boxSizing:"border-box"}),a=r.getContext("2d"),s=$(r);return r.width=i*s,r.height=n*s,a.scale(s,s),a.fillStyle=o.color,a.fillRect(0,0,i,n),r},e.prototype.updateImp=function(t,e,i){if(4===t||2===t){var n=this.getChart().getStyles().separator;e.style.backgroundColor=n.color,e.style.height="".concat(i.height,"px"),e.style.marginLeft="".concat(i.left,"px"),e.style.width="".concat(i.width,"px"),this._separatorWidget.update(t)}},e}(Ci);function Ri(){var t;return"undefined"!=typeof window&&(null!==(t=window.navigator.userAgent.toLowerCase().indexOf("firefox"))&&void 0!==t?t:-1)>-1}function Bi(){return"undefined"!=typeof window&&/iPhone|iPad|iPod/.test(window.navigator.platform)}var Oi,Vi=function(){function t(t,e,i){var n=this;this._clickCount=0,this._clickTimeoutId=null,this._clickCoordinate={x:Number.NEGATIVE_INFINITY,y:Number.POSITIVE_INFINITY},this._tapCount=0,this._tapTimeoutId=null,this._tapCoordinate={x:Number.NEGATIVE_INFINITY,y:Number.POSITIVE_INFINITY},this._longTapTimeoutId=null,this._longTapActive=!1,this._mouseMoveStartCoordinate=null,this._touchMoveStartCoordinate=null,this._touchMoveExceededManhattanDistance=!1,this._cancelClick=!1,this._cancelTap=!1,this._unsubscribeOutsideMouseEvents=null,this._unsubscribeOutsideTouchEvents=null,this._unsubscribeMobileSafariEvents=null,this._unsubscribeMousemove=null,this._unsubscribeMouseWheel=null,this._unsubscribeContextMenu=null,this._unsubscribeRootMouseEvents=null,this._unsubscribeRootTouchEvents=null,this._startPinchMiddleCoordinate=null,this._startPinchDistance=0,this._pinchPrevented=!1,this._preventTouchDragProcess=!1,this._mousePressed=!1,this._lastTouchEventTimeStamp=0,this._activeTouchId=null,this._acceptMouseLeave=!Bi(),this._onFirefoxOutsideMouseUp=function(t){n._mouseUpHandler(t)},this._onMobileSafariDoubleClick=function(t){n._firesTouchEvents(t)?(++n._tapCount,null!==n._tapTimeoutId&&n._tapCount>1&&(n._mouseTouchMoveWithDownInfo(n._getCoordinate(t),n._tapCoordinate).manhattanDistance<30&&!n._cancelTap&&n._processEvent(n._makeCompatEvent(t),n._handler.doubleTapEvent),n._resetTapTimeout())):(++n._clickCount,null!==n._clickTimeoutId&&n._clickCount>1&&(n._mouseTouchMoveWithDownInfo(n._getCoordinate(t),n._clickCoordinate).manhattanDistance<5&&!n._cancelClick&&n._processEvent(n._makeCompatEvent(t),n._handler.mouseDoubleClickEvent),n._resetClickTimeout()))},this._target=t,this._handler=e,this._options=i,this._init()}return t.prototype.destroy=function(){null!==this._unsubscribeOutsideMouseEvents&&(this._unsubscribeOutsideMouseEvents(),this._unsubscribeOutsideMouseEvents=null),null!==this._unsubscribeOutsideTouchEvents&&(this._unsubscribeOutsideTouchEvents(),this._unsubscribeOutsideTouchEvents=null),null!==this._unsubscribeMousemove&&(this._unsubscribeMousemove(),this._unsubscribeMousemove=null),null!==this._unsubscribeMouseWheel&&(this._unsubscribeMouseWheel(),this._unsubscribeMouseWheel=null),null!==this._unsubscribeContextMenu&&(this._unsubscribeContextMenu(),this._unsubscribeContextMenu=null),null!==this._unsubscribeRootMouseEvents&&(this._unsubscribeRootMouseEvents(),this._unsubscribeRootMouseEvents=null),null!==this._unsubscribeRootTouchEvents&&(this._unsubscribeRootTouchEvents(),this._unsubscribeRootTouchEvents=null),null!==this._unsubscribeMobileSafariEvents&&(this._unsubscribeMobileSafariEvents(),this._unsubscribeMobileSafariEvents=null),this._clearLongTapTimeout(),this._resetClickTimeout()},t.prototype._mouseEnterHandler=function(t){var e,i,n,o=this;null===(e=this._unsubscribeMousemove)||void 0===e||e.call(this),null===(i=this._unsubscribeMouseWheel)||void 0===i||i.call(this),null===(n=this._unsubscribeContextMenu)||void 0===n||n.call(this);var r=this._mouseMoveHandler.bind(this);this._unsubscribeMousemove=function(){o._target.removeEventListener("mousemove",r)},this._target.addEventListener("mousemove",r);var a=this._mouseWheelHandler.bind(this);this._unsubscribeMouseWheel=function(){o._target.removeEventListener("wheel",a)},this._target.addEventListener("wheel",a,{passive:!1});var s=this._contextMenuHandler.bind(this);this._unsubscribeContextMenu=function(){o._target.removeEventListener("contextmenu",s)},this._target.addEventListener("contextmenu",s,{passive:!1}),this._firesTouchEvents(t)||(this._processEvent(this._makeCompatEvent(t),this._handler.mouseEnterEvent),this._acceptMouseLeave=!0)},t.prototype._resetClickTimeout=function(){null!==this._clickTimeoutId&&clearTimeout(this._clickTimeoutId),this._clickCount=0,this._clickTimeoutId=null,this._clickCoordinate={x:Number.NEGATIVE_INFINITY,y:Number.POSITIVE_INFINITY}},t.prototype._resetTapTimeout=function(){null!==this._tapTimeoutId&&clearTimeout(this._tapTimeoutId),this._tapCount=0,this._tapTimeoutId=null,this._tapCoordinate={x:Number.NEGATIVE_INFINITY,y:Number.POSITIVE_INFINITY}},t.prototype._mouseMoveHandler=function(t){this._mousePressed||null!==this._touchMoveStartCoordinate||this._firesTouchEvents(t)||(this._processEvent(this._makeCompatEvent(t),this._handler.mouseMoveEvent),this._acceptMouseLeave=!0)},t.prototype._mouseWheelHandler=function(t){if(Math.abs(t.deltaX)>Math.abs(t.deltaY)){if(!V(this._handler.mouseWheelHortEvent))return;if(this._preventDefault(t),0===Math.abs(t.deltaX))return;this._handler.mouseWheelHortEvent(this._makeCompatEvent(t),-t.deltaX)}else{if(!V(this._handler.mouseWheelVertEvent))return;var e=-t.deltaY/100;if(0===e)return;switch(this._preventDefault(t),t.deltaMode){case t.DOM_DELTA_PAGE:e*=120;break;case t.DOM_DELTA_LINE:e*=32}if(0!==e){var i=Math.sign(e)*Math.min(1,Math.abs(e));this._handler.mouseWheelVertEvent(this._makeCompatEvent(t),i)}}},t.prototype._contextMenuHandler=function(t){this._preventDefault(t)},t.prototype._touchMoveHandler=function(t){var e=this._touchWithId(t.changedTouches,this._activeTouchId);if(null!==e&&(this._lastTouchEventTimeStamp=this._eventTimeStamp(t),null===this._startPinchMiddleCoordinate&&!this._preventTouchDragProcess)){this._pinchPrevented=!0;var i=this._mouseTouchMoveWithDownInfo(this._getCoordinate(e),this._touchMoveStartCoordinate),n=i.xOffset,o=i.yOffset,r=i.manhattanDistance;if(this._touchMoveExceededManhattanDistance||!(r<5)){if(!this._touchMoveExceededManhattanDistance){var a=.5*n,s=o>=a&&!this._options.treatVertDragAsPageScroll(),l=a>o&&!this._options.treatHorzDragAsPageScroll();s||l||(this._preventTouchDragProcess=!0),this._touchMoveExceededManhattanDistance=!0,this._cancelTap=!0,this._clearLongTapTimeout(),this._resetTapTimeout()}this._preventTouchDragProcess||this._processEvent(this._makeCompatEvent(t,e),this._handler.touchMoveEvent)}}},t.prototype._mouseMoveWithDownHandler=function(t){0===t.button&&(this._mouseTouchMoveWithDownInfo(this._getCoordinate(t),this._mouseMoveStartCoordinate).manhattanDistance>=5&&(this._cancelClick=!0,this._resetClickTimeout()),this._cancelClick&&this._processEvent(this._makeCompatEvent(t),this._handler.pressedMouseMoveEvent))},t.prototype._mouseTouchMoveWithDownInfo=function(t,e){var i=Math.abs(e.x-t.x),n=Math.abs(e.y-t.y);return{xOffset:i,yOffset:n,manhattanDistance:i+n}},t.prototype._touchEndHandler=function(t){var e=this._touchWithId(t.changedTouches,this._activeTouchId);if(null===e&&0===t.touches.length&&(e=t.changedTouches[0]),null!==e){this._activeTouchId=null,this._lastTouchEventTimeStamp=this._eventTimeStamp(t),this._clearLongTapTimeout(),this._touchMoveStartCoordinate=null,null!==this._unsubscribeRootTouchEvents&&(this._unsubscribeRootTouchEvents(),this._unsubscribeRootTouchEvents=null);var i=this._makeCompatEvent(t,e);if(this._processEvent(i,this._handler.touchEndEvent),++this._tapCount,null!==this._tapTimeoutId&&this._tapCount>1)this._mouseTouchMoveWithDownInfo(this._getCoordinate(e),this._tapCoordinate).manhattanDistance<30&&!this._cancelTap&&this._processEvent(i,this._handler.doubleTapEvent),this._resetTapTimeout();else this._cancelTap||(this._processEvent(i,this._handler.tapEvent),V(this._handler.tapEvent)&&this._preventDefault(t));0===this._tapCount&&this._preventDefault(t),0===t.touches.length&&this._longTapActive&&(this._longTapActive=!1,this._preventDefault(t))}},t.prototype._mouseUpHandler=function(t){if(0===t.button){var e=this._makeCompatEvent(t);if(this._mouseMoveStartCoordinate=null,this._mousePressed=!1,null!==this._unsubscribeRootMouseEvents&&(this._unsubscribeRootMouseEvents(),this._unsubscribeRootMouseEvents=null),Ri())this._target.ownerDocument.documentElement.removeEventListener("mouseleave",this._onFirefoxOutsideMouseUp);if(!this._firesTouchEvents(t))if(this._processEvent(e,this._handler.mouseUpEvent),++this._clickCount,null!==this._clickTimeoutId&&this._clickCount>1)this._mouseTouchMoveWithDownInfo(this._getCoordinate(t),this._clickCoordinate).manhattanDistance<5&&!this._cancelClick&&this._processEvent(e,this._handler.mouseDoubleClickEvent),this._resetClickTimeout();else this._cancelClick||this._processEvent(e,this._handler.mouseClickEvent)}},t.prototype._clearLongTapTimeout=function(){null!==this._longTapTimeoutId&&(clearTimeout(this._longTapTimeoutId),this._longTapTimeoutId=null)},t.prototype._touchStartHandler=function(t){if(null===this._activeTouchId){var e=t.changedTouches[0];this._activeTouchId=e.identifier,this._lastTouchEventTimeStamp=this._eventTimeStamp(t);var i=this._target.ownerDocument.documentElement;this._cancelTap=!1,this._touchMoveExceededManhattanDistance=!1,this._preventTouchDragProcess=!1,this._touchMoveStartCoordinate=this._getCoordinate(e),null!==this._unsubscribeRootTouchEvents&&(this._unsubscribeRootTouchEvents(),this._unsubscribeRootTouchEvents=null);var n=this._touchMoveHandler.bind(this),o=this._touchEndHandler.bind(this);this._unsubscribeRootTouchEvents=function(){i.removeEventListener("touchmove",n),i.removeEventListener("touchend",o)},i.addEventListener("touchmove",n,{passive:!1}),i.addEventListener("touchend",o,{passive:!1}),this._clearLongTapTimeout(),this._longTapTimeoutId=setTimeout(this._longTapHandler.bind(this,t),500),this._processEvent(this._makeCompatEvent(t,e),this._handler.touchStartEvent),null===this._tapTimeoutId&&(this._tapCount=0,this._tapTimeoutId=setTimeout(this._resetTapTimeout.bind(this),500),this._tapCoordinate=this._getCoordinate(e))}},t.prototype._mouseDownHandler=function(t){if(2===t.button)return this._preventDefault(t),void this._processEvent(this._makeCompatEvent(t),this._handler.mouseRightClickEvent);if(0===t.button){var e=this._target.ownerDocument.documentElement;Ri()&&e.addEventListener("mouseleave",this._onFirefoxOutsideMouseUp),this._cancelClick=!1,this._mouseMoveStartCoordinate=this._getCoordinate(t),null!==this._unsubscribeRootMouseEvents&&(this._unsubscribeRootMouseEvents(),this._unsubscribeRootMouseEvents=null);var i=this._mouseMoveWithDownHandler.bind(this),n=this._mouseUpHandler.bind(this);this._unsubscribeRootMouseEvents=function(){e.removeEventListener("mousemove",i),e.removeEventListener("mouseup",n)},e.addEventListener("mousemove",i),e.addEventListener("mouseup",n),this._mousePressed=!0,this._firesTouchEvents(t)||(this._processEvent(this._makeCompatEvent(t),this._handler.mouseDownEvent),null===this._clickTimeoutId&&(this._clickCount=0,this._clickTimeoutId=setTimeout(this._resetClickTimeout.bind(this),500),this._clickCoordinate=this._getCoordinate(t)))}},t.prototype._init=function(){var t=this;this._target.addEventListener("mouseenter",this._mouseEnterHandler.bind(this)),this._target.addEventListener("touchcancel",this._clearLongTapTimeout.bind(this));var e=this._target.ownerDocument,i=function(e){null!=t._handler.mouseDownOutsideEvent&&(e.composed&&t._target.contains(e.composedPath()[0])||null!==e.target&&t._target.contains(e.target)||t._handler.mouseDownOutsideEvent({x:0,y:0,pageX:0,pageY:0}))};this._unsubscribeOutsideTouchEvents=function(){e.removeEventListener("touchstart",i)},this._unsubscribeOutsideMouseEvents=function(){e.removeEventListener("mousedown",i)},e.addEventListener("mousedown",i),e.addEventListener("touchstart",i,{passive:!0}),Bi()&&(this._unsubscribeMobileSafariEvents=function(){t._target.removeEventListener("dblclick",t._onMobileSafariDoubleClick)},this._target.addEventListener("dblclick",this._onMobileSafariDoubleClick)),this._target.addEventListener("mouseleave",this._mouseLeaveHandler.bind(this)),this._target.addEventListener("touchstart",this._touchStartHandler.bind(this),{passive:!0}),this._target.addEventListener("mousedown",(function(t){if(1===t.button)return t.preventDefault(),!1})),this._target.addEventListener("mousedown",this._mouseDownHandler.bind(this)),this._initPinch(),this._target.addEventListener("touchmove",(function(){}),{passive:!1})},t.prototype._initPinch=function(){var t=this;(V(this._handler.pinchStartEvent)||V(this._handler.pinchEvent)||V(this._handler.pinchEndEvent))&&(this._target.addEventListener("touchstart",(function(e){t._checkPinchState(e.touches)}),{passive:!0}),this._target.addEventListener("touchmove",(function(e){if(2===e.touches.length&&null!==t._startPinchMiddleCoordinate&&V(t._handler.pinchEvent)){var i=t._getTouchDistance(e.touches[0],e.touches[1])/t._startPinchDistance;t._handler.pinchEvent(d(d({},t._startPinchMiddleCoordinate),{pageX:0,pageY:0}),i),t._preventDefault(e)}}),{passive:!1}),this._target.addEventListener("touchend",(function(e){t._checkPinchState(e.touches)})))},t.prototype._checkPinchState=function(t){1===t.length&&(this._pinchPrevented=!1),2!==t.length||this._pinchPrevented||this._longTapActive?this._stopPinch():this._startPinch(t)},t.prototype._startPinch=function(t){var e,i=null!==(e=this._target.getBoundingClientRect())&&void 0!==e?e:{left:0,top:0};this._startPinchMiddleCoordinate={x:(t[0].clientX-i.left+(t[1].clientX-i.left))/2,y:(t[0].clientY-i.top+(t[1].clientY-i.top))/2},this._startPinchDistance=this._getTouchDistance(t[0],t[1]),V(this._handler.pinchStartEvent)&&this._handler.pinchStartEvent({x:0,y:0,pageX:0,pageY:0}),this._clearLongTapTimeout()},t.prototype._stopPinch=function(){null!==this._startPinchMiddleCoordinate&&(this._startPinchMiddleCoordinate=null,V(this._handler.pinchEndEvent)&&this._handler.pinchEndEvent({x:0,y:0,pageX:0,pageY:0}))},t.prototype._mouseLeaveHandler=function(t){var e,i,n;null===(e=this._unsubscribeMousemove)||void 0===e||e.call(this),null===(i=this._unsubscribeMouseWheel)||void 0===i||i.call(this),null===(n=this._unsubscribeContextMenu)||void 0===n||n.call(this),this._firesTouchEvents(t)||this._acceptMouseLeave&&(this._processEvent(this._makeCompatEvent(t),this._handler.mouseLeaveEvent),this._acceptMouseLeave=!Bi())},t.prototype._longTapHandler=function(t){var e=this._touchWithId(t.touches,this._activeTouchId);null!==e&&(this._processEvent(this._makeCompatEvent(t,e),this._handler.longTapEvent),this._cancelTap=!0,this._longTapActive=!0)},t.prototype._firesTouchEvents=function(t){var e;return V(null===(e=t.sourceCapabilities)||void 0===e?void 0:e.firesTouchEvents)?t.sourceCapabilities.firesTouchEvents:this._eventTimeStamp(t)<this._lastTouchEventTimeStamp+500},t.prototype._processEvent=function(t,e){null==e||e.call(this._handler,t)},t.prototype._makeCompatEvent=function(t,e){var i,n=this,o=null!=e?e:t,r=null!==(i=this._target.getBoundingClientRect())&&void 0!==i?i:{left:0,top:0};return{x:o.clientX-r.left,y:o.clientY-r.top,pageX:o.pageX,pageY:o.pageY,isTouch:!t.type.startsWith("mouse")&&"contextmenu"!==t.type&&"click"!==t.type&&"wheel"!==t.type,preventDefault:function(){"touchstart"!==t.type&&n._preventDefault(t)}}},t.prototype._getTouchDistance=function(t,e){var i=t.clientX-e.clientX,n=t.clientY-e.clientY;return Math.sqrt(i*i+n*n)},t.prototype._preventDefault=function(t){t.cancelable&&t.preventDefault()},t.prototype._getCoordinate=function(t){return{x:t.pageX,y:t.pageY}},t.prototype._eventTimeStamp=function(t){var e;return null!==(e=t.timeStamp)&&void 0!==e?e:performance.now()},t.prototype._touchWithId=function(t,e){for(var i=0;i<t.length;++i)if(t[i].identifier===e)return t[i];return null},t}(),Ni=function(){function t(t,e){var i=this;this._flingStartTime=(new Date).getTime(),this._flingScrollRequestId=null,this._startScrollCoordinate=null,this._touchCoordinate=null,this._touchCancelCrosshair=!1,this._touchZoomed=!1,this._pinchScale=1,this._mouseDownWidget=null,this._prevYAxisRange=null,this._xAxisStartScaleCoordinate=null,this._xAxisStartScaleDistance=0,this._xAxisScale=1,this._yAxisStartScaleDistance=0,this._mouseMoveTriggerWidgetInfo={pane:null,widget:null},this._boundKeyBoardDownEvent=function(t){if(t.shiftKey)switch(t.code){case"Equal":i._chart.getChartStore().getTimeScaleStore().zoom(.5);break;case"Minus":i._chart.getChartStore().getTimeScaleStore().zoom(-.5);break;case"ArrowLeft":(e=i._chart.getChartStore().getTimeScaleStore()).startScroll(),e.scroll(-3*e.getBarSpace().bar);break;case"ArrowRight":var e;(e=i._chart.getChartStore().getTimeScaleStore()).startScroll(),e.scroll(3*e.getBarSpace().bar)}},this._container=t,this._chart=e,this._event=new Vi(t,this,{treatVertDragAsPageScroll:function(){return!1},treatHorzDragAsPageScroll:function(){return!1}}),t.addEventListener("keydown",this._boundKeyBoardDownEvent)}return t.prototype.pinchStartEvent=function(){return this._touchZoomed=!0,this._pinchScale=1,!0},t.prototype.pinchEvent=function(t,e){var i=this._findWidgetByEvent(t),n=i.pane,o=i.widget;if((null==n?void 0:n.getId())!==me&&(null==o?void 0:o.getName())===Te){var r=this._makeWidgetEvent(t,o),a=5*(e-this._pinchScale);return this._pinchScale=e,this._chart.getChartStore().getTimeScaleStore().zoom(a,{x:r.x,y:r.y}),!0}return!1},t.prototype.mouseWheelHortEvent=function(t,e){var i=this._chart.getChartStore().getTimeScaleStore();return i.startScroll(),i.scroll(e),!0},t.prototype.mouseWheelVertEvent=function(t,e){var i=this._findWidgetByEvent(t).widget,n=this._makeWidgetEvent(t,i);return(null==i?void 0:i.getName())===Te&&(this._chart.getChartStore().getTimeScaleStore().zoom(e,{x:n.x,y:n.y}),!0)},t.prototype.mouseDownEvent=function(t){var e,i,n=this._findWidgetByEvent(t),o=n.pane,r=n.widget;if(this._mouseDownWidget=r,null!==r){var a=this._makeWidgetEvent(t,r);switch(r.getName()){case Ie:return r.dispatchEvent("mouseDownEvent",a);case Te:var s=null!==(e=o.getAxisComponent().getRange())&&void 0!==e?e:null;return this._prevYAxisRange=null===s?s:d({},s),this._startScrollCoordinate={x:a.x,y:a.y},this._chart.getChartStore().getTimeScaleStore().startScroll(),r.dispatchEvent("mouseDownEvent",a);case we:return(l=r.dispatchEvent("mouseDownEvent",a))&&this._chart.updatePane(1),this._xAxisStartScaleCoordinate={x:a.x,y:a.y},this._xAxisStartScaleDistance=a.pageX,l;case Ee:var l;(l=r.dispatchEvent("mouseDownEvent",a))&&this._chart.updatePane(1);s=null!==(i=o.getAxisComponent().getRange())&&void 0!==i?i:null;return this._prevYAxisRange=null===s?s:d({},s),this._yAxisStartScaleDistance=a.pageY,l}}return!1},t.prototype.mouseMoveEvent=function(t){var e,i,n,o=this._findWidgetByEvent(t),r=o.pane,a=o.widget,s=this._makeWidgetEvent(t,a);if((null===(e=this._mouseMoveTriggerWidgetInfo.pane)||void 0===e?void 0:e.getId())===(null==r?void 0:r.getId())&&(null===(i=this._mouseMoveTriggerWidgetInfo.widget)||void 0===i?void 0:i.getName())===(null==a?void 0:a.getName())||(null==a||a.dispatchEvent("mouseEnterEvent",s),null===(n=this._mouseMoveTriggerWidgetInfo.widget)||void 0===n||n.dispatchEvent("mouseLeaveEvent",s),this._mouseMoveTriggerWidgetInfo={pane:r,widget:a}),null!==a)switch(a.getName()){case Te:var l=a.dispatchEvent("mouseMoveEvent",s),c=this._chart.getChartStore(),u={x:s.x,y:s.y,paneId:null==r?void 0:r.getId()};return l&&null!==c.getTooltipStore().getActiveIcon()&&(u=void 0,null!==a&&(a.getContainer().style.cursor="pointer")),this._chart.getChartStore().getTooltipStore().setCrosshair(u),l;case Ie:case we:case Ee:l=a.dispatchEvent("mouseMoveEvent",s);return this._chart.getChartStore().getTooltipStore().setCrosshair(),l}return!1},t.prototype.pressedMouseMoveEvent=function(t){var e,i,n,o,r;if(null!==this._mouseDownWidget&&this._mouseDownWidget.getName()===Ie)return this._mouseDownWidget.dispatchEvent("pressedMouseMoveEvent",t);var a=this._findWidgetByEvent(t),s=a.pane,l=a.widget;if(null!==l&&(null===(e=this._mouseDownWidget)||void 0===e?void 0:e.getPane().getId())===(null==s?void 0:s.getId())&&(null===(i=this._mouseDownWidget)||void 0===i?void 0:i.getName())===l.getName()){var c=this._makeWidgetEvent(t,l);switch(l.getName()){case Te:var u=l.getBounding();if(!(b=l.dispatchEvent("pressedMouseMoveEvent",c))&&null!==this._startScrollCoordinate){var h=s.getAxisComponent();if(null!==this._prevYAxisRange&&!h.getAutoCalcTickFlag()&&h.getScrollZoomEnabled()){var d=this._prevYAxisRange,p=d.from,g=d.to,v=p+(w=(T=d.range)*(S=(null!==(n=null==h?void 0:h.isReverse())&&void 0!==n&&n?this._startScrollCoordinate.y-c.y:c.y-this._startScrollCoordinate.y)/u.height)),f=g+w,y=h.convertToRealValue(v),m=h.convertToRealValue(f);h.setRange({from:v,to:f,range:f-v,realFrom:y,realTo:m,realRange:m-y})}var _=c.x-this._startScrollCoordinate.x;this._chart.getChartStore().getTimeScaleStore().scroll(_)}return this._chart.getChartStore().getTooltipStore().setCrosshair({x:c.x,y:c.y,paneId:null==s?void 0:s.getId()}),b;case we:if(b=l.dispatchEvent("pressedMouseMoveEvent",c))this._chart.updatePane(1);else{var x=s.getAxisComponent();if(null===(o=null==x?void 0:x.getScrollZoomEnabled())||void 0===o||o){var S=this._xAxisStartScaleDistance/c.pageX;if(Number.isFinite(S)){var C=10*(S-this._xAxisScale);this._xAxisScale=S,this._chart.getChartStore().getTimeScaleStore().zoom(C,null!==(r=this._xAxisStartScaleCoordinate)&&void 0!==r?r:void 0)}}}return b;case Ee:var b;if(b=l.dispatchEvent("pressedMouseMoveEvent",c))this._chart.updatePane(1);else{h=s.getAxisComponent();if(null!==this._prevYAxisRange&&h.getScrollZoomEnabled()){var T,w,E=this._prevYAxisRange,I=(p=E.from,g=E.to,(T=E.range)*(S=c.pageY/this._yAxisStartScaleDistance));v=p-(w=(I-T)/2),f=g+w,y=h.convertToRealValue(v),m=h.convertToRealValue(f);h.setRange({from:v,to:f,range:I,realFrom:y,realTo:m,realRange:m-y}),this._chart.adjustPaneViewport(!1,!0,!0,!0)}}return b}}return!1},t.prototype.mouseUpEvent=function(t){var e=this._findWidgetByEvent(t).widget,i=!1;if(null!==e){var n=this._makeWidgetEvent(t,e);switch(e.getName()){case Te:case Ie:case we:case Ee:i=e.dispatchEvent("mouseUpEvent",n)}i&&this._chart.updatePane(1)}return this._mouseDownWidget=null,this._startScrollCoordinate=null,this._prevYAxisRange=null,this._xAxisStartScaleCoordinate=null,this._xAxisStartScaleDistance=0,this._xAxisScale=1,this._yAxisStartScaleDistance=0,i},t.prototype.mouseClickEvent=function(t){var e=this._findWidgetByEvent(t).widget;if(null!==e){var i=this._makeWidgetEvent(t,e);return e.dispatchEvent("mouseClickEvent",i)}return!1},t.prototype.mouseRightClickEvent=function(t){var e=this._findWidgetByEvent(t).widget,i=!1;if(null!==e){var n=this._makeWidgetEvent(t,e);switch(e.getName()){case Te:case we:case Ee:i=e.dispatchEvent("mouseRightClickEvent",n)}i&&this._chart.updatePane(1)}return!1},t.prototype.mouseDoubleClickEvent=function(t){var e=this._findWidgetByEvent(t),i=e.pane,n=e.widget;if(null!==n)switch(n.getName()){case Te:var o=this._makeWidgetEvent(t,n);return n.dispatchEvent("mouseDoubleClickEvent",o);case Ee:var r=i.getAxisComponent();if(!r.getAutoCalcTickFlag())return r.setAutoCalcTickFlag(!0),this._chart.adjustPaneViewport(!1,!0,!0,!0),!0}return!1},t.prototype.mouseLeaveEvent=function(){return this._chart.getChartStore().getTooltipStore().setCrosshair(),!0},t.prototype.touchStartEvent=function(t){var e=this._findWidgetByEvent(t),i=e.pane,n=e.widget;if(null!==n){var o=this._makeWidgetEvent(t,n);switch(n.getName()){case Te:var r=this._chart.getChartStore(),a=r.getTooltipStore();if(n.dispatchEvent("mouseDownEvent",o))return this._touchCancelCrosshair=!0,this._touchCoordinate=null,a.setCrosshair(void 0,!0),this._chart.updatePane(1),!0;if(null!==this._flingScrollRequestId&&(ut(this._flingScrollRequestId),this._flingScrollRequestId=null),this._flingStartTime=(new Date).getTime(),this._startScrollCoordinate={x:o.x,y:o.y},r.getTimeScaleStore().startScroll(),this._touchZoomed=!1,null!==this._touchCoordinate){var s=o.x-this._touchCoordinate.x,l=o.y-this._touchCoordinate.y;Math.sqrt(s*s+l*l)<10?(this._touchCoordinate={x:o.x,y:o.y},a.setCrosshair({x:o.x,y:o.y,paneId:null==i?void 0:i.getId()})):(this._touchCoordinate=null,this._touchCancelCrosshair=!0,a.setCrosshair())}return!0;case we:case Ee:var c=n.dispatchEvent("mouseDownEvent",o);return c&&this._chart.updatePane(1),c}}return!1},t.prototype.touchMoveEvent=function(t){var e,i,n,o=this._findWidgetByEvent(t),r=o.pane,a=o.widget;if(null!==a){var s=this._makeWidgetEvent(t,a),l=a.getName(),c=this._chart.getChartStore(),u=c.getTooltipStore();switch(l){case Te:if(a.dispatchEvent("pressedMouseMoveEvent",s))return null===(e=s.preventDefault)||void 0===e||e.call(s),u.setCrosshair(void 0,!0),this._chart.updatePane(1),!0;if(null!==this._touchCoordinate)null===(i=s.preventDefault)||void 0===i||i.call(s),u.setCrosshair({x:s.x,y:s.y,paneId:null==r?void 0:r.getId()});else if(null!==this._startScrollCoordinate&&Math.abs(this._startScrollCoordinate.x-s.x)>this._startScrollCoordinate.y-s.y){var h=s.x-this._startScrollCoordinate.x;c.getTimeScaleStore().scroll(h)}return!0;case we:case Ee:var d=a.dispatchEvent("pressedMouseMoveEvent",s);return d&&(null===(n=s.preventDefault)||void 0===n||n.call(s),this._chart.updatePane(1)),d}}return!1},t.prototype.touchEndEvent=function(t){var e=this,i=this._findWidgetByEvent(t).widget;if(null!==i){var n=this._makeWidgetEvent(t,i);switch(i.getName()){case Te:if(i.dispatchEvent("mouseUpEvent",n),null!==this._startScrollCoordinate){var o=(new Date).getTime()-this._flingStartTime,r=(n.x-this._startScrollCoordinate.x)/(o>0?o:1)*20;if(o<200&&Math.abs(r)>0){var a=this._chart.getChartStore().getTimeScaleStore(),s=function(){e._flingScrollRequestId=ct((function(){a.startScroll(),a.scroll(r),r*=.975,Math.abs(r)<1?null!==e._flingScrollRequestId&&(ut(e._flingScrollRequestId),e._flingScrollRequestId=null):s()}))};s()}}return!0;case we:case Ee:i.dispatchEvent("mouseUpEvent",n)&&this._chart.updatePane(1)}}return!1},t.prototype.tapEvent=function(t){var e=this._findWidgetByEvent(t),i=e.pane,n=e.widget,o=!1;if(null!==n){var r=this._makeWidgetEvent(t,n),a=n.dispatchEvent("mouseClickEvent",r);if(n.getName()===Te){var s=this._makeWidgetEvent(t,n),l=this._chart.getChartStore().getTooltipStore();a?(this._touchCancelCrosshair=!0,this._touchCoordinate=null,l.setCrosshair(void 0,!0),o=!0):(this._touchCancelCrosshair||this._touchZoomed||(this._touchCoordinate={x:s.x,y:s.y},l.setCrosshair({x:s.x,y:s.y,paneId:null==i?void 0:i.getId()},!0),o=!0),this._touchCancelCrosshair=!1)}(o||a)&&this._chart.updatePane(1)}return o},t.prototype.doubleTapEvent=function(t){return this.mouseDoubleClickEvent(t)},t.prototype.longTapEvent=function(t){var e=this._findWidgetByEvent(t),i=e.pane,n=e.widget;if(null!==n&&n.getName()===Te){var o=this._makeWidgetEvent(t,n);return this._touchCoordinate={x:o.x,y:o.y},this._chart.getChartStore().getTooltipStore().setCrosshair({x:o.x,y:o.y,paneId:null==i?void 0:i.getId()}),!0}return!1},t.prototype._findWidgetByEvent=function(t){var e,i,n,o,r=t.x,a=t.y,s=this._chart.getAllSeparatorPanes(),l=this._chart.getChartStore().getStyles().separator.size;try{for(var c=v(s),u=c.next();!u.done;u=c.next()){var h=f(u.value,2)[1],d=(_=h.getBounding()).top-Math.round((7-l)/2);if(r>=_.left&&r<=_.left+_.width&&a>=d&&a<=d+7)return{pane:h,widget:h.getWidget()}}}catch(t){e={error:t}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(e)throw e.error}}var p=this._chart.getAllDrawPanes(),g=null;try{for(var y=v(p),m=y.next();!m.done;m=y.next()){var _,x=m.value;if(r>=(_=x.getBounding()).left&&r<=_.left+_.width&&a>=_.top&&a<=_.top+_.height){g=x;break}}}catch(t){n={error:t}}finally{try{m&&!m.done&&(o=y.return)&&o.call(y)}finally{if(n)throw n.error}}var S=null;if(null!==g){if(null===S){var C=g.getMainWidget(),b=C.getBounding();r>=b.left&&r<=b.left+b.width&&a>=b.top&&a<=b.top+b.height&&(S=C)}if(null===S){var T=g.getYAxisWidget();if(null!==T){var w=T.getBounding();r>=w.left&&r<=w.left+w.width&&a>=w.top&&a<=w.top+w.height&&(S=T)}}}return{pane:g,widget:S}},t.prototype._makeWidgetEvent=function(t,e){var i,n,o,r=null!==(i=null==e?void 0:e.getBounding())&&void 0!==i?i:null;return d(d({},t),{x:t.x-(null!==(n=null==r?void 0:r.left)&&void 0!==n?n:0),y:t.y-(null!==(o=null==r?void 0:r.top)&&void 0!==o?o:0)})},t.prototype.destroy=function(){this._container.removeEventListener("keydown",this._boundKeyBoardDownEvent),this._event.destroy()},t}();t.DomPosition=void 0,(Oi=t.DomPosition||(t.DomPosition={})).Root="root",Oi.Main="main",Oi.YAxis="yAxis";var Wi=function(){function e(t,e){this._drawPanes=[],this._separatorPanes=new Map,this._initContainer(t),this._chartEvent=new Ni(this._chartContainer,this),this._chartStore=new be(this,e),this._initPanes(e),this.adjustPaneViewport(!0,!0,!0)}return e.prototype._initContainer=function(t){this._container=t,this._chartContainer=ft("div",{position:"relative",width:"100%",outline:"none",borderStyle:"none",cursor:"crosshair",boxSizing:"border-box",userSelect:"none",webkitUserSelect:"none",msUserSelect:"none",MozUserSelect:"none",webkitTapHighlightColor:"transparent"}),this._chartContainer.tabIndex=1,t.appendChild(this._chartContainer)},e.prototype._initPanes=function(t){var e,i=this,n=null!==(e=null==t?void 0:t.layout)&&void 0!==e?e:[{type:"candle"}],o=!1,r=!1,a=function(t){if(!r){var e=i._createPane(Ai,me,null!=t?t:{});i._xAxisPane=e,r=!0}};n.forEach((function(t){var e,n,r;switch(t.type){case"candle":if(!o){var s=null!==(e=t.options)&&void 0!==e?e:{};A(s,{id:fe}),i._candlePane=i._createPane(wi,fe,s),(l=null!==(n=t.content)&&void 0!==n?n:[]).forEach((function(t){i.createIndicator(t,!0,s)})),o=!0}break;case"indicator":var l,c;if((l=null!==(r=t.content)&&void 0!==r?r:[]).length>0)l.forEach((function(e){V(c)?i.createIndicator(e,!0,{id:c}):c=i.createIndicator(e,!0,t.options)}));break;case"xAxis":a(t.options)}})),a({position:"bottom"})},e.prototype._createPane=function(t,e,i){var n,o=null,r=null;switch(null==i?void 0:i.position){case"top":var a=this._drawPanes[0];V(a)&&(r=new t(this._chartContainer,a.getContainer(),this,e,null!=i?i:{}),o=0);break;case"bottom":break;default:for(var s=this._drawPanes.length-1;s>-1;s--){var l=this._drawPanes[s],c=this._drawPanes[s-1];if("bottom"===(null==l?void 0:l.getOptions().position)&&"bottom"!==(null==c?void 0:c.getOptions().position)){r=new t(this._chartContainer,l.getContainer(),this,e,null!=i?i:{}),o=s;break}}}if(V(r)||(r=new t(this._chartContainer,null,this,e,null!=i?i:{})),O(o)?(this._drawPanes.splice(o,0,r),n=o):(this._drawPanes.push(r),n=this._drawPanes.length-1),r.getId()!==me){var u=this._drawPanes[n+1];if(V(u)&&u.getId()===me&&(u=this._drawPanes[n+2]),V(u))V(d=this._separatorPanes.get(u))?d.setTopPane(r):(d=new Li(this._chartContainer,u.getContainer(),this,"",r,u),this._separatorPanes.set(u,d));var h=this._drawPanes[n-1];if(V(h)&&h.getId()===me&&(h=this._drawPanes[n-2]),V(h)){var d=new Li(this._chartContainer,r.getContainer(),this,"",h,r);this._separatorPanes.set(r,d)}}return r},e.prototype._measurePaneHeight=function(){var t,e=this,i=Math.floor(this._container.clientHeight),n=this._chartStore.getStyles().separator.size,o=this._xAxisPane.getAxisComponent().getAutoSize(),r=i-o-this._separatorPanes.size*n;r<0&&(r=0);var a=0;this._drawPanes.forEach((function(t){if(t.getId()!==fe&&t.getId()!==me){var e=t.getBounding().height,i=t.getOptions().minHeight;e<i&&(e=i),a+e>r?(a=r,e=Math.max(r-a,0)):a+=e,t.setBounding({height:e})}}));var s=r-a;null===(t=this._candlePane)||void 0===t||t.setBounding({height:s}),this._xAxisPane.setBounding({height:o});var l=0;this._drawPanes.forEach((function(t){var i=e._separatorPanes.get(t);V(i)&&(i.setBounding({height:n,top:l}),l+=n),t.setBounding({top:l}),l+=t.getBounding().height}))},e.prototype._measurePaneWidth=function(){var e=this,i=Math.floor(this._container.clientWidth),n=this._chartStore.getStyles(),o=n.yAxis,r=o.position===t.YAxisPosition.Left,a=!o.inside,s=0,l=0,c=0,u=0;this._drawPanes.forEach((function(t){t.getId()!==me&&(l=Math.max(l,t.getAxisComponent().getAutoSize()))})),l>i&&(l=i),a?(s=i-l,r?(c=0,u=l):(c=i-l,u=0)):(s=i,u=0,c=r?0:i-l),this._chartStore.getTimeScaleStore().setTotalBarSpace(s);var h,d={width:i},p={width:s,left:u},g={width:l,left:c},v=n.separator.fill;h=a&&!v?p:d,this._drawPanes.forEach((function(t){var i;null===(i=e._separatorPanes.get(t))||void 0===i||i.setBounding(h),t.setBounding(d,p,g)}))},e.prototype._setPaneOptions=function(t,e){var i,n;if(W(t.id)){var o=this.getDrawPaneById(t.id),r=!1;if(null!==o){var a=e;if(t.id!==fe&&O(t.height)&&t.height>0){var s=Math.max(null!==(i=t.minHeight)&&void 0!==i?i:o.getOptions().minHeight,0),l=Math.max(s,t.height);o.setBounding({height:l}),a=!0,r=!0}(W(null===(n=t.axisOptions)||void 0===n?void 0:n.name)||V(t.gap))&&(a=!0),o.setOptions(t),a&&this.adjustPaneViewport(r,!0,!0,!0,!0)}}},e.prototype.getDrawPaneById=function(t){if(t===fe)return this._candlePane;if(t===me)return this._xAxisPane;var e=this._drawPanes.find((function(e){return e.getId()===t}));return null!=e?e:null},e.prototype.getContainer=function(){return this._container},e.prototype.getChartStore=function(){return this._chartStore},e.prototype.getXAxisPane=function(){return this._xAxisPane},e.prototype.getAllDrawPanes=function(){return this._drawPanes},e.prototype.getAllSeparatorPanes=function(){return this._separatorPanes},e.prototype.adjustPaneViewport=function(t,e,i,n,o){t&&this._measurePaneHeight();var r=e,a=null!=o&&o;(null!=n&&n||a)&&this._drawPanes.forEach((function(t){var e=t.getAxisComponent().buildTicks(a);r||(r=e)})),r&&this._measurePaneWidth(),null!=i&&i&&(this._xAxisPane.getAxisComponent().buildTicks(!0),this.updatePane(4))},e.prototype.updatePane=function(t,e){if(V(e)){var i=this.getDrawPaneById(e);null==i||i.update(t)}else this._separatorPanes.forEach((function(e){e.update(t)})),this._drawPanes.forEach((function(e){e.update(t)}))},e.prototype.crosshairChange=function(e){var i=this,n=this._chartStore.getActionStore();if(n.has(t.ActionType.OnCrosshairChange)){var o={};this._drawPanes.forEach((function(t){var n=t.getId(),r={};i._chartStore.getIndicatorStore().getInstances(n).forEach((function(t){var i,n=t.result;r[t.name]=n[null!==(i=e.dataIndex)&&void 0!==i?i:n.length-1]})),o[n]=r})),W(e.paneId)&&n.execute(t.ActionType.OnCrosshairChange,d(d({},e),{indicatorData:o}))}},e.prototype.getDom=function(e,i){var n,o;if(!W(e))return this._chartContainer;var r=this.getDrawPaneById(e);if(null!==r)switch(null!=i?i:t.DomPosition.Root){case t.DomPosition.Root:return r.getContainer();case t.DomPosition.Main:return r.getMainWidget().getContainer();case t.DomPosition.YAxis:return null!==(o=null===(n=r.getYAxisWidget())||void 0===n?void 0:n.getContainer())&&void 0!==o?o:null}return null},e.prototype.getSize=function(e,i){var n,o;if(!V(e))return{width:Math.floor(this._chartContainer.clientWidth),height:Math.floor(this._chartContainer.clientHeight),left:0,top:0,right:0,bottom:0};var r=this.getDrawPaneById(e);if(null!==r)switch(null!=i?i:t.DomPosition.Root){case t.DomPosition.Root:return r.getBounding();case t.DomPosition.Main:return r.getMainWidget().getBounding();case t.DomPosition.YAxis:return null!==(o=null===(n=r.getYAxisWidget())||void 0===n?void 0:n.getBounding())&&void 0!==o?o:null}return null},e.prototype.setStyles=function(t){var e,i,n;this._chartStore.setOptions({styles:t}),V(null===(e=null==(n=W(t)?Ce(t):t)?void 0:n.yAxis)||void 0===e?void 0:e.type)&&(null===(i=this._candlePane)||void 0===i||i.getAxisComponent().setAutoCalcTickFlag(!0)),this.adjustPaneViewport(!0,!0,!0,!0,!0)},e.prototype.getStyles=function(){return this._chartStore.getStyles()},e.prototype.setLocale=function(t){this._chartStore.setOptions({locale:t}),this.adjustPaneViewport(!0,!0,!0,!0,!0)},e.prototype.getLocale=function(){return this._chartStore.getLocale()},e.prototype.setCustomApi=function(t){this._chartStore.setOptions({customApi:t}),this.adjustPaneViewport(!0,!0,!0,!0,!0)},e.prototype.setPriceVolumePrecision=function(t,e){this._chartStore.setPrecision({price:t,volume:e})},e.prototype.getPriceVolumePrecision=function(){return this._chartStore.getPrecision()},e.prototype.setTimezone=function(t){this._chartStore.setOptions({timezone:t}),this._xAxisPane.getAxisComponent().buildTicks(!0),this._xAxisPane.update(3)},e.prototype.getTimezone=function(){return this._chartStore.getTimeScaleStore().getTimezone()},e.prototype.setOffsetRightDistance=function(t){this._chartStore.getTimeScaleStore().setOffsetRightDistance(t,!0)},e.prototype.getOffsetRightDistance=function(){return this._chartStore.getTimeScaleStore().getOffsetRightDistance()},e.prototype.setMaxOffsetLeftDistance=function(t){t<0||this._chartStore.getTimeScaleStore().setMaxOffsetLeftDistance(t)},e.prototype.setMaxOffsetRightDistance=function(t){t<0||this._chartStore.getTimeScaleStore().setMaxOffsetRightDistance(t)},e.prototype.setLeftMinVisibleBarCount=function(t){t<0||this._chartStore.getTimeScaleStore().setLeftMinVisibleBarCount(Math.ceil(t))},e.prototype.setRightMinVisibleBarCount=function(t){t<0||this._chartStore.getTimeScaleStore().setRightMinVisibleBarCount(Math.ceil(t))},e.prototype.setBarSpace=function(t){this._chartStore.getTimeScaleStore().setBarSpace(t)},e.prototype.getBarSpace=function(){return this._chartStore.getTimeScaleStore().getBarSpace().bar},e.prototype.getVisibleRange=function(){return this._chartStore.getTimeScaleStore().getVisibleRange()},e.prototype.clearData=function(){this._chartStore.clear()},e.prototype.getDataList=function(){return this._chartStore.getDataList()},e.prototype.applyNewData=function(t,e,i){this._chartStore.addData(t,ht.Init,e).then((function(){})).catch((function(){})).finally((function(){null==i||i()}))},e.prototype.applyMoreData=function(t,e,i){this._chartStore.addData(t,ht.Forward,null==e||e).then((function(){})).catch((function(){})).finally((function(){null==i||i()}))},e.prototype.updateData=function(t,e){this._chartStore.addData(t).then((function(){})).catch((function(){})).finally((function(){null==e||e()}))},e.prototype.loadMore=function(t){this._chartStore.setLoadMoreCallback(t)},e.prototype.setLoadDataCallback=function(t){this._chartStore.setLoadDataCallback(t)},e.prototype.createIndicator=function(t,e,i,n){var o,r=this,a=W(t)?{name:t}:t;if(null===Gt(a.name))return null;var s=null==i?void 0:i.id,l=this.getDrawPaneById(null!=s?s:"");if(null!==l)this._chartStore.getIndicatorStore().addInstance(a,null!=s?s:"",null!=e&&e).then((function(t){var e;r._setPaneOptions(null!=i?i:{},null!==(e=l.getAxisComponent().buildTicks(!0))&&void 0!==e&&e)})).catch((function(t){}));else{null!=s||(s=vt(ye));var c=this._createPane(Ti,s,null!=i?i:{}),u=null!==(o=null==i?void 0:i.height)&&void 0!==o?o:100;c.setBounding({height:u}),this._chartStore.getIndicatorStore().addInstance(a,s,null!=e&&e).finally((function(){r.adjustPaneViewport(!0,!0,!0,!0,!0),null==n||n()}))}return null!=s?s:null},e.prototype.overrideIndicator=function(t,e,i){var n=this;this._chartStore.getIndicatorStore().override(t,null!=e?e:null).then((function(t){var e=f(t,2),o=e[0],r=e[1];(o||r)&&(n.adjustPaneViewport(!1,r,!0,r),null==i||i())})).catch((function(){}))},e.prototype.getIndicatorByPaneId=function(t,e){return this._chartStore.getIndicatorStore().getInstanceByPaneId(t,e)},e.prototype.removeIndicator=function(t,e){var i,n,o,r=this._chartStore.getIndicatorStore();if(r.removeInstance(t,e)){var a=!1;if(t!==fe&&!r.hasInstances(t)){var s=this.getDrawPaneById(t),l=this._drawPanes.findIndex((function(e){return e.getId()===t}));if(null!==s){a=!0;var c=this._separatorPanes.get(s);if(V(c)){var u=null==c?void 0:c.getTopPane();try{for(var h=v(this._separatorPanes),d=h.next();!d.done;d=h.next()){var p=d.value;if(p[1].getTopPane().getId()===s.getId()){p[1].setTopPane(u);break}}}catch(t){i={error:t}}finally{try{d&&!d.done&&(n=h.return)&&n.call(h)}finally{if(i)throw i.error}}c.destroy(),this._separatorPanes.delete(s)}this._drawPanes.splice(l,1),s.destroy();var g=this._drawPanes[0];V(g)&&g.getId()===me&&(g=this._drawPanes[1]),null===(o=this._separatorPanes.get(g))||void 0===o||o.destroy(),this._separatorPanes.delete(g)}}this.adjustPaneViewport(a,!0,!0,!0,!0)}},e.prototype.createOverlay=function(t,e){var i=[];if(W(t))i=[{name:t}];else if(L(t))i=t.map((function(t){return W(t)?{name:t}:t}));else{i=[t]}var n=!0;V(e)&&null!==this.getDrawPaneById(e)||(e=fe,n=!1);var o=this._chartStore.getOverlayStore().addInstances(i,e,n);return L(t)?o:o[0]},e.prototype.getOverlayById=function(t){return this._chartStore.getOverlayStore().getInstanceById(t)},e.prototype.overrideOverlay=function(t){this._chartStore.getOverlayStore().override(t)},e.prototype.removeOverlay=function(t){var e;V(t)&&(e=W(t)?{id:t}:t),this._chartStore.getOverlayStore().removeInstance(e)},e.prototype.setPaneOptions=function(t){this._setPaneOptions(t,!1)},e.prototype.setZoomEnabled=function(t){this._chartStore.getTimeScaleStore().setZoomEnabled(t)},e.prototype.isZoomEnabled=function(){return this._chartStore.getTimeScaleStore().getZoomEnabled()},e.prototype.setScrollEnabled=function(t){this._chartStore.getTimeScaleStore().setScrollEnabled(t)},e.prototype.isScrollEnabled=function(){return this._chartStore.getTimeScaleStore().getScrollEnabled()},e.prototype.scrollByDistance=function(t,e){var i=O(e)&&e>0?e:0,n=this._chartStore.getTimeScaleStore();if(n.startScroll(),i>0){var o=new dt({duration:i});o.doFrame((function(e){var o=t*(e/i);n.scroll(o)})),o.start()}else n.scroll(t)},e.prototype.scrollToRealTime=function(t){var e=this._chartStore.getTimeScaleStore(),i=e.getBarSpace().bar,n=(e.getLastBarRightSideDiffBarCount()-e.getInitialOffsetRightDistance()/i)*i;this.scrollByDistance(n,t)},e.prototype.scrollToDataIndex=function(t,e){var i=this._chartStore.getTimeScaleStore(),n=(i.getLastBarRightSideDiffBarCount()+(this.getDataList().length-1-t))*i.getBarSpace().bar;this.scrollByDistance(n,e)},e.prototype.scrollToTimestamp=function(t,e){var i=yt(this.getDataList(),"timestamp",t);this.scrollToDataIndex(i,e)},e.prototype.zoomAtCoordinate=function(t,e,i){var n=O(i)&&i>0?i:0,o=this._chartStore.getTimeScaleStore(),r=o.getBarSpace().bar,a=r*t-r;if(n>0){var s=0,l=new dt({duration:n});l.doFrame((function(t){var i=a*(t/n),r=(i-s)/o.getBarSpace().bar*10;o.zoom(r,e),s=i})),l.start()}else o.zoom(a/r*10,e)},e.prototype.zoomAtDataIndex=function(t,e,i){var n=this._chartStore.getTimeScaleStore().dataIndexToCoordinate(e);this.zoomAtCoordinate(t,{x:n,y:0},i)},e.prototype.zoomAtTimestamp=function(t,e,i){var n=yt(this.getDataList(),"timestamp",e);this.zoomAtDataIndex(t,n,i)},e.prototype.convertToPixel=function(t,e){var i,n=e.paneId,o=void 0===n?fe:n,r=e.absolute,a=void 0!==r&&r,s=[];if(o!==me){var l=this.getDrawPaneById(o);if(null!==l){var c=this._chartStore.getTimeScaleStore(),u=l.getBounding(),h=(new Array).concat(t),d=this._xAxisPane.getAxisComponent(),p=l.getAxisComponent();s=h.map((function(t){var e={},i=t.dataIndex;if(O(t.timestamp)&&(i=c.timestampToDataIndex(t.timestamp)),O(i)&&(e.x=null==d?void 0:d.convertToPixel(i)),O(t.value)){var n=null==p?void 0:p.convertToPixel(t.value);e.y=a?u.top+n:n}return e}))}}return L(t)?s:null!==(i=s[0])&&void 0!==i?i:{}},e.prototype.convertFromPixel=function(t,e){var i,n=e.paneId,o=void 0===n?fe:n,r=e.absolute,a=void 0!==r&&r,s=[];if(o!==me){var l=this.getDrawPaneById(o);if(null!==l){var c=this._chartStore.getTimeScaleStore(),u=l.getBounding(),h=(new Array).concat(t),d=this._xAxisPane.getAxisComponent(),p=l.getAxisComponent();s=h.map((function(t){var e,i,n={};if(O(t.x)){var o=null!==(e=null==d?void 0:d.convertFromPixel(t.x))&&void 0!==e?e:-1;n.dataIndex=o,n.timestamp=null!==(i=c.dataIndexToTimestamp(o))&&void 0!==i?i:void 0}if(O(t.y)){var r=a?t.y-u.top:t.y;n.value=p.convertFromPixel(r)}return n}))}}return L(t)?s:null!==(i=s[0])&&void 0!==i?i:{}},e.prototype.executeAction=function(e,i){var n;if(e===t.ActionType.OnCrosshairChange){var o=d({},i);o.paneId=null!==(n=o.paneId)&&void 0!==n?n:fe,this._chartStore.getTooltipStore().setCrosshair(o)}},e.prototype.subscribeAction=function(t,e){this._chartStore.getActionStore().subscribe(t,e)},e.prototype.unsubscribeAction=function(t,e){this._chartStore.getActionStore().unsubscribe(t,e)},e.prototype.getConvertPictureUrl=function(t,e,i){var n=this,o=this._chartContainer.clientWidth,r=this._chartContainer.clientHeight,a=ft("canvas",{width:"".concat(o,"px"),height:"".concat(r,"px"),boxSizing:"border-box"}),s=a.getContext("2d"),l=$(a);a.width=o*l,a.height=r*l,s.scale(l,l),s.fillStyle=null!=i?i:"#FFFFFF",s.fillRect(0,0,o,r);var c=null!=t&&t;return this._drawPanes.forEach((function(t){var e=n._separatorPanes.get(t);if(V(e)){var i=e.getBounding();s.drawImage(e.getImage(c),i.left,i.top,i.width,i.height)}var r=t.getBounding();s.drawImage(t.getImage(c),0,r.top,o,r.height)})),a.toDataURL("image/".concat(null!=e?e:"jpeg"))},e.prototype.resize=function(){this.adjustPaneViewport(!0,!0,!0,!0,!0)},e.prototype.destroy=function(){this._chartEvent.destroy(),this._drawPanes.forEach((function(t){t.destroy()})),this._drawPanes=[],this._separatorPanes.forEach((function(t){t.destroy()})),this._separatorPanes.clear(),this._container.removeChild(this._chartContainer)},e}(),zi=new Map,Yi=1;var Hi={clone:F,merge:A,isString:W,isNumber:O,isValid:V,isObject:B,isArray:L,isFunction:R,isBoolean:N,formatValue:G,formatPrecision:K,formatBigNumber:Z,formatDate:j,formatThousands:U,formatFoldDecimal:q,calcTextWidth:J,getLinearSlopeIntercept:ee,getLinearYFromSlopeIntercept:Jt,getLinearYFromCoordinates:te,checkCoordinateOnArc:Ke,checkCoordinateOnCircle:Fe,checkCoordinateOnLine:Qt,checkCoordinateOnPolygon:Be,checkCoordinateOnRect:Ne,checkCoordinateOnText:He,drawArc:Ze,drawCircle:Le,drawLine:ne,drawPolygon:Oe,drawRect:We,drawText:Xe,drawRectText:je};t.dispose=function(t){var e,i,n;if(t instanceof Wi)n=t.id;else{var o=void 0;n=null!==(e=null==(o=W(t)?document.getElementById(t):t)?void 0:o.getAttribute("k-line-chart-id"))&&void 0!==e?e:null}null!==n&&(null===(i=zi.get(n))||void 0===i||i.destroy(),zi.delete(n))},t.getFigureClass=function(t){var e;return null!==(e=qe[t])&&void 0!==e?e:null},t.getOverlayClass=function(t){var e;return null!==(e=ge[t])&&void 0!==e?e:null},t.getSupportedFigures=function(){return Object.keys(qe)},t.getSupportedIndicators=function(){return Object.keys(Ht)},t.getSupportedLocales=function(){return Object.keys(ci)},t.getSupportedOverlays=function(){return Object.keys(ge)},t.init=function(t,e){var i;if(null===(i=W(t)?document.getElementById(t):t))return null;var n=zi.get(i.id);if(V(n))return n;var o="k_line_chart_".concat(Yi++);return(n=new Wi(i,e)).id=o,i.setAttribute("k-line-chart-id",o),zi.set(o,n),n},t.registerFigure=function(t){qe[t.name]=$t.extend(t)},t.registerIndicator=function(t){Ht[t.name]=ot.extend(t)},t.registerLocale=function(t,e){ci[t]=d(d({},ci[t]),e)},t.registerOverlay=function(t){ge[t.name]=lt.extend(t)},t.registerStyles=function(t,e){Se[t]=e},t.registerXAxis=function(t){ki[t.name]=Mi.extend(t)},t.registerYAxis=function(t){Si[t.name]=xi.extend(t)},t.utils=Hi,t.version=function(){return"9.8.10"}}));
diff --git a/fincept-qt/scripts/algo_trading/algo_live_runner.py b/fincept-qt/scripts/algo_trading/algo_live_runner.py
deleted file mode 100644
index 3fbaa2f30..000000000
--- a/fincept-qt/scripts/algo_trading/algo_live_runner.py
+++ /dev/null
@@ -1,480 +0,0 @@
-"""
-Algo Live Runner
-
-Long-running Python process spawned by the host for strategy deployment.
-Reads candle_cache, evaluates conditions, generates trade signals.
-
-Usage:
- python algo_live_runner.py --deploy-id <id> --strategy-id <id> --symbol <sym>
- --provider <prov> --mode paper|live --timeframe <tf> --quantity <qty> --db <path>
-"""
-
-import json
-import sys
-import argparse
-import sqlite3
-import time
-import os
-import signal
-import uuid
-import logging
-from datetime import datetime
-
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from condition_evaluator import load_candles_from_db, evaluate_condition_group
-
-# ── Heavy debug logging ──────────────────────────────────────────────
-LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'algo_runner_debug.log')
-logging.basicConfig(
- level=logging.DEBUG,
- format='%(asctime)s [%(levelname)s] %(message)s',
- handlers=[
- logging.FileHandler(LOG_FILE, mode='a', encoding='utf-8'),
- logging.StreamHandler(sys.stderr),
- ],
-)
-log = logging.getLogger('algo_runner')
-
-# Graceful shutdown
-running = True
-
-def signal_handler(sig, frame):
- global running
- running = False
-
-signal.signal(signal.SIGTERM, signal_handler)
-signal.signal(signal.SIGINT, signal_handler)
-
-
-TIMEFRAME_SECONDS = {
- 'live': 1, '1m': 60, '3m': 180, '5m': 300, '10m': 600, '15m': 900,
- '30m': 1800, '1h': 3600, '4h': 14400, '1d': 86400,
-}
-
-
-MAX_ORDER_VALUE_WARNING = 1_000_000 # Warn if order value exceeds this
-
-
-def _db_execute_with_retry(conn, sql, params=(), retries=3, commit=True):
- """Execute a DB statement with retry logic for 'database is locked' errors."""
- for attempt in range(retries):
- try:
- conn.execute(sql, params)
- if commit:
- conn.commit()
- return
- except sqlite3.OperationalError as e:
- if 'locked' in str(e).lower() and attempt < retries - 1:
- log.warning(f" DB locked, retry {attempt + 1}/{retries}...")
- time.sleep(0.1 * (attempt + 1))
- else:
- raise
-
-
-def open_db_connection(db_path: str):
- """Open a shared DB connection with WAL mode for concurrent access."""
- conn = sqlite3.connect(db_path, timeout=10)
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA busy_timeout=5000")
- return conn
-
-
-def load_strategy(conn, strategy_id: str) -> dict:
- """Load strategy conditions from algo_strategies table."""
- row = conn.execute(
- "SELECT entry_conditions, exit_conditions, entry_logic, exit_logic, "
- "stop_loss, take_profit, trailing_stop, trailing_stop_type "
- "FROM algo_strategies WHERE id = ?",
- (strategy_id,)
- ).fetchone()
-
- if not row:
- return None
-
- return {
- 'entry_conditions': json.loads(row[0]),
- 'exit_conditions': json.loads(row[1]),
- 'entry_logic': row[2],
- 'exit_logic': row[3],
- 'stop_loss': row[4],
- 'take_profit': row[5],
- 'trailing_stop': row[6],
- 'trailing_stop_type': row[7],
- }
-
-
-def update_deployment_status(conn, deploy_id: str, status: str, error: str = None):
- """Update deployment status in DB."""
- if error:
- _db_execute_with_retry(conn,
- "UPDATE algo_deployments SET status = ?, error_message = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
- (status, error, deploy_id))
- else:
- _db_execute_with_retry(conn,
- "UPDATE algo_deployments SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
- (status, deploy_id))
-
-
-def update_metrics(conn, deploy_id: str, metrics: dict):
- """Update algo_metrics table."""
- _db_execute_with_retry(conn,
- """INSERT INTO algo_metrics (deployment_id, total_pnl, unrealized_pnl, total_trades,
- win_rate, max_drawdown, current_position_qty, current_position_side,
- current_position_entry, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
- ON CONFLICT(deployment_id) DO UPDATE SET
- total_pnl = excluded.total_pnl,
- unrealized_pnl = excluded.unrealized_pnl,
- total_trades = excluded.total_trades,
- win_rate = excluded.win_rate,
- max_drawdown = excluded.max_drawdown,
- current_position_qty = excluded.current_position_qty,
- current_position_side = excluded.current_position_side,
- current_position_entry = excluded.current_position_entry,
- updated_at = CURRENT_TIMESTAMP""",
- (deploy_id, metrics.get('total_pnl', 0), metrics.get('unrealized_pnl', 0),
- metrics.get('total_trades', 0), metrics.get('win_rate', 0),
- metrics.get('max_drawdown', 0), metrics.get('current_position_qty', 0),
- metrics.get('current_position_side', ''), metrics.get('current_position_entry', 0)))
-
-
-def record_trade(conn, deploy_id: str, symbol: str, side: str,
- quantity: float, price: float, pnl: float, reason: str):
- """Record a trade in algo_trades table."""
- trade_id = f"trade-{uuid.uuid4()}"
- _db_execute_with_retry(conn,
- "INSERT INTO algo_trades (id, deployment_id, symbol, side, quantity, price, pnl, signal_reason) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
- (trade_id, deploy_id, symbol, side, quantity, price, pnl, reason))
- return trade_id
-
-
-def create_order_signal(conn, deploy_id: str, symbol: str, side: str,
- quantity: float, order_type: str = 'MARKET', price: float = None):
- """Write an order signal for the host to execute (live mode)."""
- signal_id = f"signal-{uuid.uuid4()}"
- _db_execute_with_retry(conn,
- "INSERT INTO algo_order_signals (id, deployment_id, symbol, side, quantity, order_type, price, status) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')",
- (signal_id, deploy_id, symbol, side, quantity, order_type, price))
- return signal_id
-
-
-def _normalize_symbol(s: str) -> str:
- """Strip slashes, dashes, underscores and uppercase for matching."""
- return s.replace('/', '').replace('-', '').replace('_', '').replace(':', '').upper()
-
-
-def get_current_price(conn, symbol: str) -> float:
- """Get latest price from strategy_price_cache.
-
- Tries exact match first, then normalized match to handle symbol format
- differences (e.g., BTC/USD vs BTCUSD, NSE:RELIANCE vs RELIANCE).
- """
- # Try exact match first
- row = conn.execute(
- "SELECT price FROM strategy_price_cache WHERE symbol = ? ORDER BY updated_at DESC LIMIT 1",
- (symbol,)
- ).fetchone()
- if row:
- log.debug(f" get_current_price({symbol}) = {row[0]} (exact match)")
- return row[0]
-
- # Try normalized match: load all symbols and compare normalized forms
- norm = _normalize_symbol(symbol)
- rows = conn.execute(
- "SELECT symbol, price FROM strategy_price_cache ORDER BY updated_at DESC"
- ).fetchall()
-
- log.debug(f" get_current_price({symbol}) exact miss. Normalized={norm}. Cache has {len(rows)} entries: {[(s, p) for s, p in rows[:10]]}")
-
- for (cached_sym, price) in rows:
- cached_norm = _normalize_symbol(cached_sym)
- if cached_norm == norm or norm.startswith(cached_norm) or cached_norm.startswith(norm):
- log.debug(f" get_current_price({symbol}) = {price} (normalized/prefix match via '{cached_sym}')")
- return price
-
- log.warning(f" get_current_price({symbol}) = 0.0 (NO MATCH in price cache)")
- return 0.0
-
-
-def check_risk_management(current_price: float, position: dict, strategy: dict) -> str:
- """Check stop-loss, take-profit, trailing stop. Returns 'exit' reason or None."""
- if not position or position['qty'] == 0:
- return None
-
- entry_price = position['entry']
- side = position['side']
-
- if side == 'BUY':
- pnl_pct = (current_price - entry_price) / entry_price * 100
- else:
- pnl_pct = (entry_price - current_price) / entry_price * 100
-
- # Stop loss
- sl = strategy.get('stop_loss')
- if sl and pnl_pct <= -abs(sl):
- return f'stop_loss_hit ({pnl_pct:.2f}%)'
-
- # Take profit
- tp = strategy.get('take_profit')
- if tp and pnl_pct >= abs(tp):
- return f'take_profit_hit ({pnl_pct:.2f}%)'
-
- # Trailing stop
- ts = strategy.get('trailing_stop')
- if ts and position.get('max_pnl_pct', 0) > 0:
- if position['max_pnl_pct'] - pnl_pct >= abs(ts):
- return f'trailing_stop_hit ({pnl_pct:.2f}%)'
-
- return None
-
-
-def main():
- parser = argparse.ArgumentParser(description='Algo Live Runner')
- parser.add_argument('--deploy-id', required=True)
- parser.add_argument('--strategy-id', required=True)
- parser.add_argument('--symbol', required=True)
- parser.add_argument('--provider', default='')
- parser.add_argument('--mode', default='paper', choices=['paper', 'live'])
- parser.add_argument('--timeframe', default='5m')
- parser.add_argument('--quantity', type=float, default=1.0)
- parser.add_argument('--db', required=True)
- args = parser.parse_args()
-
- log.info("=" * 70)
- log.info("ALGO LIVE RUNNER STARTING")
- log.info(f" deploy_id = {args.deploy_id}")
- log.info(f" strategy_id= {args.strategy_id}")
- log.info(f" symbol = {args.symbol}")
- log.info(f" provider = {args.provider}")
- log.info(f" mode = {args.mode}")
- log.info(f" timeframe = {args.timeframe}")
- log.info(f" quantity = {args.quantity}")
- log.info(f" db = {args.db}")
- log.info(f" pid = {os.getpid()}")
- log.info("=" * 70)
-
- # Open shared DB connection (WAL mode for concurrent host access)
- conn = open_db_connection(args.db)
- log.info("Shared DB connection opened (WAL mode)")
-
- # Load strategy
- strategy = load_strategy(conn, args.strategy_id)
- if not strategy:
- log.error(f"Strategy {args.strategy_id} NOT FOUND in DB!")
- update_deployment_status(conn, args.deploy_id, 'error', 'Strategy not found')
- conn.close()
- sys.exit(1)
-
- log.info(f"Strategy loaded OK. Entry conditions: {json.dumps(strategy['entry_conditions'], indent=2)}")
- log.info(f"Exit conditions: {json.dumps(strategy['exit_conditions'], indent=2)}")
- log.info(f"Risk: SL={strategy.get('stop_loss')}, TP={strategy.get('take_profit')}, TS={strategy.get('trailing_stop')}")
-
- update_deployment_status(conn, args.deploy_id, 'running')
-
- # Inject logic operators into condition lists
- entry_conds = strategy['entry_conditions']
- exit_conds = strategy['exit_conditions']
-
- # State
- position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}
- total_pnl = 0.0
- total_trades = 0
- winning_trades = 0
- max_drawdown = 0.0
- peak_pnl = 0.0
- last_candle_time = 0
- loop_count = 0
-
- is_live = args.timeframe == 'live'
- interval = 1 if is_live else TIMEFRAME_SECONDS.get(args.timeframe, 300)
- check_interval = 1 if is_live else max(interval // 2, 5)
- log.info(f"Timeframe interval={interval}s, check_interval={check_interval}s, live_mode={is_live}")
-
- while running:
- loop_count += 1
- try:
- # Load candles (live mode needs fewer rows since each row is a tick)
- candle_limit = 50 if is_live else 200
- df = load_candles_from_db(args.db, args.symbol, args.timeframe, limit=candle_limit)
- if df.empty or len(df) < 2:
- if loop_count <= 5 or loop_count % 20 == 0:
- log.warning(f"[loop#{loop_count}] Candle data insufficient: {len(df)} rows (need >=2) for {args.symbol}@{args.timeframe}")
- # Dump what symbols exist in candle_cache
- try:
- syms = conn.execute("SELECT DISTINCT symbol, timeframe, COUNT(*) FROM candle_cache GROUP BY symbol, timeframe").fetchall()
- log.warning(f" candle_cache contents: {syms}")
- # Also check strategy_price_cache for recent price updates
- prices = conn.execute("SELECT symbol, price, updated_at FROM strategy_price_cache ORDER BY updated_at DESC LIMIT 10").fetchall()
- log.warning(f" strategy_price_cache recent entries: {prices}")
- except Exception as dbg_e:
- log.warning(f" could not read cache tables: {dbg_e}")
- time.sleep(check_interval)
- continue
-
- # Check if we have new data
- newest_time = int(df['open_time'].iloc[-1]) if 'open_time' in df.columns else 0
- if not is_live and newest_time == last_candle_time:
- if loop_count <= 3 or loop_count % 60 == 0:
- log.debug(f"[loop#{loop_count}] No new candle (last={last_candle_time}), {len(df)} candles loaded. Sleeping {check_interval}s")
- time.sleep(check_interval)
- continue
- last_candle_time = newest_time
- if is_live:
- if loop_count <= 3 or loop_count % 100 == 0:
- log.info(f"[loop#{loop_count}] LIVE tick eval, {len(df)} ticks, latest_price={df['close'].iloc[-1]}")
- else:
- log.info(f"[loop#{loop_count}] NEW candle detected! open_time={newest_time}, total candles={len(df)}")
- log.debug(f" Last 3 candles: {df[['open_time','open','high','low','close','volume']].tail(3).to_string()}")
-
- current_price = get_current_price(conn, args.symbol)
- price_source = "price_cache"
- if current_price <= 0:
- current_price = float(df['close'].iloc[-1])
- price_source = "last_candle_close"
- log.info(f" Current price = {current_price} (source: {price_source})")
-
- # Check risk management first
- if position['qty'] != 0:
- # Update max P&L for trailing stop
- if position['side'] == 'BUY':
- pnl_pct = (current_price - position['entry']) / position['entry'] * 100
- else:
- pnl_pct = (position['entry'] - current_price) / position['entry'] * 100
- position['max_pnl_pct'] = max(position.get('max_pnl_pct', 0), pnl_pct)
- log.debug(f" Position: {position['side']} qty={position['qty']} entry={position['entry']} pnl%={pnl_pct:.2f}%")
-
- risk_exit = check_risk_management(current_price, position, strategy)
- if risk_exit:
- log.info(f" RISK EXIT TRIGGERED: {risk_exit}")
- # Close position - use abs(qty) since qty is always stored positive
- qty = abs(position['qty'])
- pnl = (current_price - position['entry']) * qty if position['side'] == 'BUY' \
- else (position['entry'] - current_price) * qty
-
- if args.mode == 'paper':
- record_trade(conn, args.deploy_id, args.symbol, 'SELL' if position['side'] == 'BUY' else 'BUY',
- abs(position['qty']), current_price, pnl, risk_exit)
- else:
- create_order_signal(conn, args.deploy_id, args.symbol,
- 'SELL' if position['side'] == 'BUY' else 'BUY',
- abs(position['qty']))
-
- total_pnl += pnl
- total_trades += 1
- if pnl > 0:
- winning_trades += 1
- position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}
-
- # Evaluate conditions
- verbose_log = not is_live or loop_count <= 3 or loop_count % 100 == 0
- if position['qty'] == 0:
- # No position: check entry conditions
- entry_result = evaluate_condition_group(entry_conds, df)
- if verbose_log:
- log.info(f" ENTRY eval => result={entry_result['result']}, logic={entry_result.get('logic','AND')}")
- for i, d in enumerate(entry_result.get('details', [])):
- log.info(f" cond[{i}]: {d.get('indicator','')} {d.get('operator','')} target={d.get('target','')} "
- f"computed={d.get('computed_value','')} met={d.get('met',False)} "
- f"{'ERROR: '+d.get('error','') if d.get('error') else ''}")
- if entry_result['result']:
- log.info(f" >>> ENTRY SIGNAL FIRED! BUY {args.quantity} @ {current_price}")
- # Enter position
- position = {
- 'qty': args.quantity,
- 'side': 'BUY',
- 'entry': current_price,
- 'max_pnl_pct': 0,
- }
-
- # Position size warning (#18)
- order_value = args.quantity * current_price
- if order_value > MAX_ORDER_VALUE_WARNING:
- log.warning(f" HIGH ORDER VALUE: {args.quantity} x {current_price} = {order_value:.2f} (exceeds {MAX_ORDER_VALUE_WARNING})")
-
- if args.mode == 'paper':
- record_trade(conn, args.deploy_id, args.symbol, 'BUY',
- args.quantity, current_price, 0,
- f'entry_signal: {json.dumps([d.get("indicator", "") for d in entry_result.get("details", [])])}')
- else:
- create_order_signal(conn, args.deploy_id, args.symbol, 'BUY', args.quantity)
-
- else:
- # In position: check exit conditions
- exit_result = evaluate_condition_group(exit_conds, df)
- if verbose_log:
- log.info(f" EXIT eval => result={exit_result['result']}, logic={exit_result.get('logic','AND')}")
- for i, d in enumerate(exit_result.get('details', [])):
- log.info(f" cond[{i}]: {d.get('indicator','')} {d.get('operator','')} target={d.get('target','')} "
- f"computed={d.get('computed_value','')} met={d.get('met',False)} "
- f"{'ERROR: '+d.get('error','') if d.get('error') else ''}")
- if exit_result['result']:
- log.info(f" >>> EXIT SIGNAL FIRED!")
- # Exit position - use abs(qty) since qty is always stored positive
- qty = abs(position['qty'])
- pnl = (current_price - position['entry']) * qty if position['side'] == 'BUY' \
- else (position['entry'] - current_price) * qty
-
- if args.mode == 'paper':
- record_trade(conn, args.deploy_id, args.symbol,
- 'SELL' if position['side'] == 'BUY' else 'BUY',
- abs(position['qty']), current_price, pnl,
- f'exit_signal: {json.dumps([d.get("indicator", "") for d in exit_result.get("details", [])])}')
- else:
- create_order_signal(conn, args.deploy_id, args.symbol,
- 'SELL' if position['side'] == 'BUY' else 'BUY',
- abs(position['qty']))
-
- total_pnl += pnl
- total_trades += 1
- if pnl > 0:
- winning_trades += 1
- position = {'qty': 0, 'side': '', 'entry': 0, 'max_pnl_pct': 0}
-
- # Update metrics
- unrealized = 0
- if position['qty'] != 0:
- if position['side'] == 'BUY':
- unrealized = (current_price - position['entry']) * position['qty']
- else:
- unrealized = (position['entry'] - current_price) * position['qty']
-
- # Track drawdown
- current_equity = total_pnl + unrealized
- if current_equity > peak_pnl:
- peak_pnl = current_equity
- dd = peak_pnl - current_equity
- if dd > max_drawdown:
- max_drawdown = dd
-
- win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
-
- update_metrics(conn, args.deploy_id, {
- 'total_pnl': total_pnl,
- 'unrealized_pnl': unrealized,
- 'total_trades': total_trades,
- 'win_rate': win_rate,
- 'max_drawdown': max_drawdown,
- 'current_position_qty': position['qty'],
- 'current_position_side': position['side'],
- 'current_position_entry': position['entry'],
- })
-
- if loop_count <= 5 or loop_count % 30 == 0:
- log.info(f" Metrics: pnl={total_pnl:.2f} unrealized={unrealized:.2f} trades={total_trades} win%={win_rate:.1f} dd={max_drawdown:.2f}")
-
- time.sleep(check_interval)
-
- except Exception as e:
- log.error(f"[loop#{loop_count}] EXCEPTION: {e}", exc_info=True)
- time.sleep(check_interval)
-
- # Shutdown: update status and close DB connection
- update_deployment_status(conn, args.deploy_id, 'stopped')
- conn.close()
- log.info(f"Deployment {args.deploy_id} STOPPED. Total trades={total_trades}, PnL={total_pnl:.2f}")
-
-
-if __name__ == '__main__':
- main()
diff --git a/fincept-qt/scripts/algo_trading/algo_manager.py b/fincept-qt/scripts/algo_trading/algo_manager.py
deleted file mode 100644
index be7f4474e..000000000
--- a/fincept-qt/scripts/algo_trading/algo_manager.py
+++ /dev/null
@@ -1,133 +0,0 @@
-"""
-Algo Manager — deployment management subcommands.
-
-Called by the C++ AlgoTradingService for deployment control operations.
-algo_live_runner.py only handles the long-running strategy loop; this script
-handles all read/write management queries against the DB.
-
-Usage:
- python algo_manager.py list_deployments --db <path>
- python algo_manager.py stop <deploy_id> --db <path>
- python algo_manager.py stop_all --db <path>
-"""
-
-import json
-import sys
-import os
-import argparse
-import sqlite3
-
-
-def get_db_path(args_db: str) -> str:
- """Resolve DB path: use provided --db, or fall back to AppData location."""
- if args_db and os.path.exists(args_db):
- return args_db
- # Windows fallback
- appdata = os.environ.get('APPDATA', '')
- if appdata:
- candidate = os.path.join(appdata, 'Fincept', 'FinceptTerminal', 'fincept.db')
- if os.path.exists(candidate):
- return candidate
- # Last resort: same dir as script
- return os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'fincept.db')
-
-
-def open_db(db_path: str):
- conn = sqlite3.connect(db_path, timeout=10)
- conn.row_factory = sqlite3.Row
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA busy_timeout=5000")
- return conn
-
-
-def cmd_list_deployments(db_path: str):
- """Return all deployments with their live metrics."""
- try:
- conn = open_db(db_path)
- rows = conn.execute("""
- SELECT
- d.id, d.strategy_id, d.symbol, d.mode, d.status,
- d.timeframe, d.quantity, d.error_message,
- d.created_at, d.updated_at,
- s.name AS strategy_name,
- COALESCE(m.total_pnl, 0) AS total_pnl,
- COALESCE(m.unrealized_pnl, 0) AS unrealized_pnl,
- COALESCE(m.total_trades, 0) AS total_trades,
- COALESCE(m.win_rate, 0) AS win_rate,
- COALESCE(m.max_drawdown, 0) AS max_drawdown,
- COALESCE(m.current_position_qty, 0) AS current_position_qty,
- COALESCE(m.current_position_side, '') AS current_position_side,
- COALESCE(m.current_position_entry, 0) AS current_position_entry
- FROM algo_deployments d
- LEFT JOIN algo_strategies s ON s.id = d.strategy_id
- LEFT JOIN algo_metrics m ON m.deployment_id = d.id
- ORDER BY d.created_at DESC
- """).fetchall()
- conn.close()
-
- deployments = [dict(r) for r in rows]
- print(json.dumps({'success': True, 'deployments': deployments}))
-
- except sqlite3.OperationalError as e:
- # Table may not exist yet (first run before any deployment)
- if 'no such table' in str(e).lower():
- print(json.dumps({'success': True, 'deployments': []}))
- else:
- print(json.dumps({'success': False, 'error': str(e), 'deployments': []}))
- except Exception as e:
- print(json.dumps({'success': False, 'error': str(e), 'deployments': []}))
-
-
-def cmd_stop(deploy_id: str, db_path: str):
- """Mark a deployment as stopped in the DB."""
- try:
- conn = open_db(db_path)
- conn.execute(
- "UPDATE algo_deployments SET status = 'stopped', updated_at = CURRENT_TIMESTAMP WHERE id = ?",
- (deploy_id,)
- )
- conn.commit()
- conn.close()
- print(json.dumps({'success': True, 'deployment_id': deploy_id}))
- except Exception as e:
- print(json.dumps({'success': False, 'error': str(e)}))
-
-
-def cmd_stop_all(db_path: str):
- """Mark all running/starting deployments as stopped."""
- try:
- conn = open_db(db_path)
- conn.execute(
- "UPDATE algo_deployments SET status = 'stopped', updated_at = CURRENT_TIMESTAMP "
- "WHERE status IN ('running', 'starting', 'pending')"
- )
- conn.commit()
- conn.close()
- print(json.dumps({'success': True}))
- except Exception as e:
- print(json.dumps({'success': False, 'error': str(e)}))
-
-
-def main():
- parser = argparse.ArgumentParser(description='Algo Deployment Manager')
- parser.add_argument('command', choices=['list_deployments', 'stop', 'stop_all'])
- parser.add_argument('deploy_id', nargs='?', default=None,
- help='Deployment ID (required for stop)')
- parser.add_argument('--db', default=None, help='SQLite database path')
-
- args = parser.parse_args()
- db_path = get_db_path(args.db)
-
- if args.command == 'list_deployments':
- cmd_list_deployments(db_path)
- elif args.command == 'stop':
- if not args.deploy_id:
- print(json.dumps({'success': False, 'error': 'deploy_id required for stop'}))
- sys.exit(1)
- cmd_stop(args.deploy_id, db_path)
- elif args.command == 'stop_all':
- cmd_stop_all(db_path)
-
-
-if __name__ == '__main__':
- main()
diff --git a/fincept-qt/scripts/algo_trading/condition_evaluator.py b/fincept-qt/scripts/algo_trading/condition_evaluator.py
deleted file mode 100644
index 9ef049719..000000000
--- a/fincept-qt/scripts/algo_trading/condition_evaluator.py
+++ /dev/null
@@ -1,428 +0,0 @@
-"""
-Condition Evaluator Engine
-
-Short-lived subprocess called from the host. Evaluates condition groups against candle data.
-
-Usage:
- python condition_evaluator.py --mode once --conditions <json> --symbol <sym> --timeframe <tf> --db <path>
-
-Input conditions JSON format:
- [
- {"indicator":"RSI","params":{"period":14},"field":"value","operator":"crosses_below","value":30},
- "AND",
- {"indicator":"MACD","params":{"fast":12,"slow":26,"signal":9},"field":"histogram","operator":">","value":0}
- ]
-
- Indicator-vs-indicator comparison:
- [
- {"indicator":"CLOSE","params":{},"field":"value","operator":"crosses_above",
- "compareMode":"indicator","compareIndicator":"EMA","compareParams":{"period":20},"compareField":"value"}
- ]
-
-Output:
- {"success": true, "result": true/false, "details": [...]}
-"""
-
-import json
-import sys
-import argparse
-import sqlite3
-import pandas as pd
-import math
-import os
-import logging
-
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from indicators import get_latest_value, get_last_n_values, get_value_at_offset
-
-log = logging.getLogger('algo_runner.evaluator')
-
-
-def _normalize_symbol(s: str) -> str:
- """Strip slashes, dashes, underscores, colons and uppercase for matching."""
- return s.replace('/', '').replace('-', '').replace('_', '').replace(':', '').upper()
-
-
-def load_candles_from_db(db_path: str, symbol: str, timeframe: str, limit: int = 200) -> pd.DataFrame:
- """Load candles from candle_cache table.
-
- Tries exact symbol match first, then falls back to normalized matching
- to handle format differences (e.g., BTC/USD vs BTCUSD, NSE:RELIANCE vs RELIANCE).
- """
- conn = sqlite3.connect(db_path)
-
- # Try exact match first
- query = """
- SELECT open_time, o, h, l, c, volume
- FROM candle_cache
- WHERE symbol = ? AND timeframe = ? AND is_closed = 1
- ORDER BY open_time ASC
- LIMIT ?
- """
- df = pd.read_sql_query(query, conn, params=(symbol, timeframe, limit))
- log.debug(f"load_candles_from_db('{symbol}', '{timeframe}', limit={limit}) exact match => {len(df)} rows")
-
- if df.empty:
- # Fallback: find the actual symbol name in the cache that matches when normalized
- # Also handles broker truncation (e.g., Angel One truncates "AVANTIFEEDS" to "AVANTIFEED")
- norm = _normalize_symbol(symbol)
- try:
- cached_symbols = pd.read_sql_query(
- "SELECT DISTINCT symbol FROM candle_cache WHERE timeframe = ?",
- conn, params=(timeframe,)
- )
- log.debug(f" Exact match failed. Trying normalized={norm}. Cached symbols for tf={timeframe}: {cached_symbols['symbol'].tolist()}")
- for _, row in cached_symbols.iterrows():
- cached_sym = row['symbol']
- cached_norm = _normalize_symbol(cached_sym)
- if cached_norm == norm or norm.startswith(cached_norm) or cached_norm.startswith(norm):
- df = pd.read_sql_query(query, conn, params=(cached_sym, timeframe, limit))
- log.debug(f" Normalized/prefix match found: '{cached_sym}' => {len(df)} rows")
- break
- except Exception as e:
- log.warning(f" Fallback symbol search failed: {e}")
-
- conn.close()
-
- if df.empty:
- log.warning(f" NO candle data found for '{symbol}' @ {timeframe}")
- return pd.DataFrame(columns=['open', 'high', 'low', 'close', 'volume'])
-
- df.rename(columns={'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close'}, inplace=True)
- return df
-
-
-def _get_target_value(condition: dict, df: pd.DataFrame):
- """
- Get the comparison target value(s). Supports both numeric and indicator comparison modes.
-
- Returns:
- For non-crossing operators: (current_target_value, None)
- For crossing operators: (current_target_value, previous_target_value)
- Also returns target_info dict for debug output.
- """
- compare_mode = condition.get('compareMode', 'value')
- operator = condition.get('operator', '>')
- compare_offset = condition.get('compareOffset', 0)
-
- if compare_mode == 'indicator':
- compare_indicator = condition.get('compareIndicator', '')
- compare_params = condition.get('compareParams', {})
- compare_field = condition.get('compareField', 'value')
-
- if not compare_indicator:
- raise ValueError('compareIndicator is required when compareMode is "indicator"')
-
- target_info = {
- 'target_indicator': compare_indicator,
- 'target_field': compare_field,
- }
-
- if operator in ('crosses_above', 'crosses_below'):
- # Need last 2 values for both sides
- target_values = get_last_n_values(compare_indicator, df, compare_params, compare_field, n=2)
- if len(target_values) < 2:
- raise ValueError(f'Insufficient data for {compare_indicator}')
- target_info['target_computed_value'] = target_values[-1]
- return target_values[-1], target_values[-2], target_info
- else:
- if compare_offset > 0:
- val = get_value_at_offset(compare_indicator, df, compare_params, compare_field, compare_offset)
- else:
- val = get_latest_value(compare_indicator, df, compare_params, compare_field)
- target_info['target_computed_value'] = val
- return val, None, target_info
- else:
- target_value = condition.get('value', 0)
- return target_value, None, {}
-
-
-def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
- """
- Evaluate a single condition against candle data.
- Supports indicator-vs-indicator comparison, offsets, and advanced operators.
- """
- indicator = condition.get('indicator', '')
- params = condition.get('params', {})
- field = condition.get('field', 'value')
- operator = condition.get('operator', '>')
- target_value_raw = condition.get('value', 0)
- target_value2 = condition.get('value2', None)
- offset = condition.get('offset', 0)
- compare_mode = condition.get('compareMode', 'value')
- lookback = condition.get('lookback', 5)
-
- try:
- # Get target value(s) — may be numeric or from another indicator
- target_current, target_prev, target_info = _get_target_value(condition, df)
-
- # ── Crossing operators ────────────────────────────────────────
- if operator in ('crosses_above', 'crosses_below'):
- values = get_last_n_values(indicator, df, params, field, n=2)
- if len(values) < 2 or any(math.isnan(v) for v in values):
- return {
- 'met': False,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': values[-1] if values else None,
- 'operator': operator,
- 'target': target_current if isinstance(target_current, (int, float)) else 0,
- 'error': 'Insufficient data for crossing detection',
- **target_info,
- }
-
- prev_val, curr_val = values
-
- if compare_mode == 'indicator' and target_prev is not None:
- # Crossing relative to another indicator
- if operator == 'crosses_above':
- met = prev_val <= target_prev and curr_val > target_current
- else:
- met = prev_val >= target_prev and curr_val < target_current
- else:
- # Crossing relative to a fixed value
- if operator == 'crosses_above':
- met = prev_val <= target_current and curr_val > target_current
- else:
- met = prev_val >= target_current and curr_val < target_current
-
- return {
- 'met': met,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': curr_val,
- 'prev_value': prev_val,
- 'operator': operator,
- 'target': target_current if isinstance(target_current, (int, float)) else 0,
- **target_info,
- }
-
- # ── Crossed within N bars ─────────────────────────────────────
- elif operator in ('crossed_above_within', 'crossed_below_within'):
- n = int(lookback) + 1
- values = get_last_n_values(indicator, df, params, field, n=n)
- if len(values) < 2:
- return {
- 'met': False, 'indicator': indicator, 'field': field,
- 'computed_value': values[-1] if values else None,
- 'operator': operator, 'target': target_current,
- 'error': 'Insufficient data',
- }
-
- # For indicator-vs-indicator, get N target values to compare bar-by-bar
- met = False
- if compare_mode == 'indicator':
- compare_indicator = condition.get('compareIndicator', '')
- compare_params_dict = condition.get('compareParams', {})
- compare_field_name = condition.get('compareField', 'value')
- target_values_list = get_last_n_values(compare_indicator, df, compare_params_dict, compare_field_name, n=n)
- if len(target_values_list) >= len(values):
- for i in range(len(values) - 1):
- if operator == 'crossed_above_within':
- if values[i] <= target_values_list[i] and values[i + 1] > target_values_list[i + 1]:
- met = True
- break
- else:
- if values[i] >= target_values_list[i] and values[i + 1] < target_values_list[i + 1]:
- met = True
- break
- else:
- # Compare against fixed numeric target
- for i in range(len(values) - 1):
- if operator == 'crossed_above_within':
- if values[i] <= target_current and values[i + 1] > target_current:
- met = True
- break
- else:
- if values[i] >= target_current and values[i + 1] < target_current:
- met = True
- break
-
- return {
- 'met': met,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': values[-1],
- 'operator': operator,
- 'target': target_current if isinstance(target_current, (int, float)) else 0,
- **target_info,
- }
-
- # ── Rising / Falling ──────────────────────────────────────────
- elif operator in ('rising', 'falling'):
- n = int(lookback)
- values = get_last_n_values(indicator, df, params, field, n=n)
- if len(values) < 2 or any(math.isnan(v) for v in values):
- return {
- 'met': False, 'indicator': indicator, 'field': field,
- 'computed_value': values[-1] if values else None,
- 'operator': operator, 'target': 0,
- 'error': 'Insufficient data',
- }
-
- if operator == 'rising':
- met = all(values[i] < values[i + 1] for i in range(len(values) - 1))
- else:
- met = all(values[i] > values[i + 1] for i in range(len(values) - 1))
-
- return {
- 'met': met,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': values[-1],
- 'operator': operator,
- 'target': 0,
- }
-
- # ── Standard comparison operators ─────────────────────────────
- else:
- if offset > 0:
- current_value = get_value_at_offset(indicator, df, params, field, offset)
- else:
- current_value = get_latest_value(indicator, df, params, field)
-
- if math.isnan(current_value):
- return {
- 'met': False,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': None,
- 'operator': operator,
- 'target': target_current if isinstance(target_current, (int, float)) else 0,
- 'error': 'Indicator returned NaN',
- **target_info,
- }
-
- if math.isnan(target_current) if isinstance(target_current, float) else False:
- return {
- 'met': False,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': current_value,
- 'operator': operator,
- 'target': 0,
- 'error': 'Target indicator returned NaN',
- **target_info,
- }
-
- if operator == '>':
- met = current_value > target_current
- elif operator == '<':
- met = current_value < target_current
- elif operator == '>=':
- met = current_value >= target_current
- elif operator == '<=':
- met = current_value <= target_current
- elif operator == '==':
- met = abs(current_value - target_current) < 0.0001
- elif operator == 'between':
- if target_value2 is not None:
- met = target_value_raw <= current_value <= target_value2
- else:
- met = False
- else:
- met = False
-
- return {
- 'met': met,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': current_value,
- 'operator': operator,
- 'target': target_current if isinstance(target_current, (int, float)) else 0,
- **target_info,
- }
-
- except Exception as e:
- return {
- 'met': False,
- 'indicator': indicator,
- 'field': field,
- 'computed_value': None,
- 'operator': operator,
- 'target': target_value_raw,
- 'error': str(e)
- }
-
-
-def evaluate_condition_group(conditions: list, df: pd.DataFrame) -> dict:
- """
- Evaluate a flat list of conditions with AND/OR logic.
-
- conditions format: [condition_dict, "AND"/"OR", condition_dict, ...]
- If no logic operators, default is AND.
- """
- if not conditions:
- return {'result': False, 'details': [], 'logic': 'AND'}
-
- # Parse into conditions and logic
- condition_items = []
- logic = 'AND' # default
-
- for item in conditions:
- if isinstance(item, str) and item.upper() in ('AND', 'OR'):
- logic = item.upper()
- elif isinstance(item, dict):
- condition_items.append(item)
-
- if not condition_items:
- return {'result': False, 'details': [], 'logic': logic}
-
- details = []
- for cond in condition_items:
- result = evaluate_single_condition(cond, df)
- details.append(result)
-
- met_results = [d['met'] for d in details]
-
- if logic == 'AND':
- overall = all(met_results)
- else:
- overall = any(met_results)
-
- return {
- 'result': overall,
- 'details': details,
- 'logic': logic,
- }
-
-
-def main():
- parser = argparse.ArgumentParser(description='Condition Evaluator')
- parser.add_argument('--mode', default='once', choices=['once'])
- parser.add_argument('--conditions', required=True, help='JSON conditions array')
- parser.add_argument('--symbol', required=True)
- parser.add_argument('--timeframe', default='5m')
- parser.add_argument('--db', required=True, help='SQLite database path')
- parser.add_argument('--limit', type=int, default=200)
- args = parser.parse_args()
-
- try:
- conditions = json.loads(args.conditions)
- except json.JSONDecodeError as e:
- print(json.dumps({'success': False, 'error': f'Invalid conditions JSON: {e}'}))
- sys.exit(1)
-
- # Load candle data
- df = load_candles_from_db(args.db, args.symbol, args.timeframe, args.limit)
- if df.empty or len(df) < 2:
- print(json.dumps({
- 'success': False,
- 'error': f'Insufficient candle data for {args.symbol} ({len(df)} candles)'
- }))
- sys.exit(0)
-
- # Evaluate conditions
- result = evaluate_condition_group(conditions, df)
-
- print(json.dumps({
- 'success': True,
- 'symbol': args.symbol,
- 'timeframe': args.timeframe,
- 'candle_count': len(df),
- **result,
- }))
-
-
-if __name__ == '__main__':
- main()
diff --git a/fincept-qt/scripts/algo_trading/fetch_candles.py b/fincept-qt/scripts/algo_trading/fetch_candles.py
new file mode 100644
index 000000000..3db00163a
--- /dev/null
+++ b/fincept-qt/scripts/algo_trading/fetch_candles.py
@@ -0,0 +1,91 @@
+"""
+Minimal candle data fetcher — data source only, no algo logic.
+Returns OHLCV JSON for multiple symbols via yfinance.
+
+Usage: python fetch_candles.py '{"symbols":["RELIANCE","TCS"],"timeframe":"1d","lookback_days":365}'
+"""
+import json
+import sys
+
+try:
+ import yfinance as yf
+except ImportError:
+ print(json.dumps({"success": False, "error": "yfinance not installed"}))
+ sys.exit(1)
+
+
+TIMEFRAME_MAP = {
+ "1m": "1m", "3m": "5m", "5m": "5m", "15m": "15m",
+ "30m": "30m", "1h": "1h", "4h": "1h", "1d": "1d",
+}
+
+PERIOD_MAP = {
+ "1m": "7d", "3m": "60d", "5m": "60d", "15m": "60d",
+ "30m": "60d", "1h": "730d", "4h": "730d", "1d": "max",
+}
+
+
+def symbol_to_yf(symbol: str) -> str:
+ s = symbol.strip().upper()
+ if "." in s or "/" in s or "-" in s:
+ return s
+ return s + ".NS"
+
+
+def fetch_symbol(symbol: str, timeframe: str, lookback_days: int):
+ yf_symbol = symbol_to_yf(symbol)
+ interval = TIMEFRAME_MAP.get(timeframe, "1d")
+ period = PERIOD_MAP.get(timeframe, "max")
+
+ if lookback_days and lookback_days < 365:
+ period = f"{lookback_days}d"
+
+ try:
+ df = yf.download(yf_symbol, period=period, interval=interval, progress=False)
+ if df.empty:
+ return []
+
+ if hasattr(df.columns, 'droplevel') and df.columns.nlevels > 1:
+ df.columns = df.columns.droplevel(1)
+
+ candles = []
+ for idx, row in df.iterrows():
+ candles.append({
+ "t": int(idx.timestamp() * 1000),
+ "o": round(float(row["Open"]), 4),
+ "h": round(float(row["High"]), 4),
+ "l": round(float(row["Low"]), 4),
+ "c": round(float(row["Close"]), 4),
+ "v": round(float(row.get("Volume", 0)), 0),
+ })
+ return candles
+ except Exception as e:
+ return []
+
+
+def main():
+ if len(sys.argv) < 2:
+ print(json.dumps({"success": False, "error": "No params provided"}))
+ sys.exit(1)
+
+ try:
+ params = json.loads(sys.argv[1])
+ except json.JSONDecodeError as e:
+ print(json.dumps({"success": False, "error": f"Invalid JSON: {e}"}))
+ sys.exit(1)
+
+ symbols = params.get("symbols", [])
+ timeframe = params.get("timeframe", "1d")
+ lookback_days = params.get("lookback_days", 365)
+
+ data = {}
+ for symbol in symbols:
+ candles = fetch_symbol(symbol, timeframe, lookback_days)
+ if candles:
+ data[symbol] = candles
+
+ print(json.dumps({"success": True, "data": data}))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-qt/scripts/algo_trading/indicators.py b/fincept-qt/scripts/algo_trading/indicators.py
deleted file mode 100644
index fb41e2eef..000000000
--- a/fincept-qt/scripts/algo_trading/indicators.py
+++ /dev/null
@@ -1,549 +0,0 @@
-"""
-Unified Indicator Wrapper for Algo Trading
-
-Single entry point: compute_indicator(name, df, params) -> dict of field_name: series
-Reuses existing technicals library (ta-based indicators).
-"""
-
-import pandas as pd
-import numpy as np
-import sys
-import os
-
-# Add parent to path so we can import technicals
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from technicals.momentum_indicators import (
- calculate_rsi, calculate_stochastic, calculate_williams_r, calculate_roc,
- calculate_stoch_rsi, calculate_tsi, calculate_ultimate_oscillator,
- calculate_awesome_oscillator, calculate_kama, calculate_ppo, calculate_pvo
-)
-from technicals.trend_indicators import (
- calculate_sma, calculate_ema, calculate_wma, calculate_macd, calculate_cci,
- calculate_adx, calculate_ichimoku, calculate_psar, calculate_aroon,
- calculate_stc, calculate_kst, calculate_vortex, calculate_dpo,
- calculate_trix, calculate_mass_index
-)
-from technicals.volatility_indicators import (
- calculate_atr, calculate_bollinger_bands, calculate_keltner_channel, calculate_donchian_channel
-)
-from technicals.volume_indicators import (
- calculate_obv, calculate_cmf, calculate_mfi, calculate_force_index,
- calculate_adi, calculate_eom, calculate_vpt, calculate_nvi
-)
-
-
-def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
- """
- Compute a technical indicator and return its fields as a dict of Series.
-
- Args:
- name: Indicator name (case-insensitive), e.g. 'RSI', 'MACD', 'SMA'
- df: DataFrame with columns: open, high, low, close, volume
- params: Indicator parameters, e.g. {'period': 14}
-
- Returns:
- Dict mapping field names to pd.Series, e.g. {'value': Series([...])}
- """
- name = name.upper()
-
- # ── Stock Attributes ──────────────────────────────────────────────
- if name == 'CLOSE' or name == 'PRICE':
- return {'value': df['close']}
-
- elif name == 'OPEN':
- return {'value': df['open']}
-
- elif name == 'HIGH':
- return {'value': df['high']}
-
- elif name == 'LOW':
- return {'value': df['low']}
-
- elif name == 'VOLUME':
- return {'value': df['volume']}
-
- elif name == 'CHANGE_PCT':
- pct = df['close'].pct_change() * 100
- return {'value': pct.fillna(0)}
-
- elif name == 'VWAP':
- typical_price = (df['high'] + df['low'] + df['close']) / 3
- cumulative_tp_vol = (typical_price * df['volume']).cumsum()
- cumulative_vol = df['volume'].cumsum()
- vwap = cumulative_tp_vol / cumulative_vol
- return {'value': vwap}
-
- elif name == 'HL2':
- return {'value': (df['high'] + df['low']) / 2}
-
- elif name == 'HLC3':
- return {'value': (df['high'] + df['low'] + df['close']) / 3}
-
- elif name == 'OHLC4':
- return {'value': (df['open'] + df['high'] + df['low'] + df['close']) / 4}
-
- # Heikin-Ashi candles
- elif name == 'HA_CLOSE':
- return {'value': (df['open'] + df['high'] + df['low'] + df['close']) / 4}
-
- elif name == 'HA_OPEN':
- ha_close = (df['open'] + df['high'] + df['low'] + df['close']) / 4
- ha_open = pd.Series(index=df.index, dtype=float)
- ha_open.iloc[0] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
- for i in range(1, len(df)):
- ha_open.iloc[i] = (ha_open.iloc[i - 1] + ha_close.iloc[i - 1]) / 2
- return {'value': ha_open}
-
- elif name == 'HA_HIGH':
- ha_close = (df['open'] + df['high'] + df['low'] + df['close']) / 4
- ha_open = pd.Series(index=df.index, dtype=float)
- ha_open.iloc[0] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
- for i in range(1, len(df)):
- ha_open.iloc[i] = (ha_open.iloc[i - 1] + ha_close.iloc[i - 1]) / 2
- return {'value': pd.concat([df['high'], ha_open, ha_close], axis=1).max(axis=1)}
-
- elif name == 'HA_LOW':
- ha_close = (df['open'] + df['high'] + df['low'] + df['close']) / 4
- ha_open = pd.Series(index=df.index, dtype=float)
- ha_open.iloc[0] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
- for i in range(1, len(df)):
- ha_open.iloc[i] = (ha_open.iloc[i - 1] + ha_close.iloc[i - 1]) / 2
- return {'value': pd.concat([df['low'], ha_open, ha_close], axis=1).min(axis=1)}
-
- # ── Moving Averages ───────────────────────────────────────────────
- elif name == 'SMA':
- period = params.get('period', 20)
- series = calculate_sma(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'EMA':
- period = params.get('period', 12)
- series = calculate_ema(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'WMA':
- period = params.get('period', 9)
- series = calculate_wma(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'KAMA':
- period = params.get('period', 10)
- pow1 = params.get('pow1', 2)
- pow2 = params.get('pow2', 30)
- series = calculate_kama(df, window=period, pow1=pow1, pow2=pow2, fillna=True)
- return {'value': series}
-
- elif name == 'TEMA':
- period = params.get('period', 20)
- ema1 = df['close'].ewm(span=period, adjust=False).mean()
- ema2 = ema1.ewm(span=period, adjust=False).mean()
- ema3 = ema2.ewm(span=period, adjust=False).mean()
- return {'value': 3 * ema1 - 3 * ema2 + ema3}
-
- elif name == 'DEMA':
- period = params.get('period', 20)
- ema1 = df['close'].ewm(span=period, adjust=False).mean()
- ema2 = ema1.ewm(span=period, adjust=False).mean()
- return {'value': 2 * ema1 - ema2}
-
- elif name == 'HMA':
- period = params.get('period', 14)
- half_period = max(int(period / 2), 1)
- sqrt_period = max(int(period ** 0.5), 1)
- wma_half = df['close'].rolling(half_period).apply(
- lambda x: np.average(x, weights=range(1, half_period + 1)), raw=True
- )
- wma_full = df['close'].rolling(period).apply(
- lambda x: np.average(x, weights=range(1, period + 1)), raw=True
- )
- diff = 2 * wma_half - wma_full
- hma = diff.rolling(sqrt_period).apply(
- lambda x: np.average(x, weights=range(1, sqrt_period + 1)), raw=True
- )
- return {'value': hma.bfill()}
-
- elif name == 'RMA':
- period = params.get('period', 14)
- rma = df['close'].ewm(alpha=1.0 / period, adjust=False).mean()
- return {'value': rma}
-
- elif name == 'TMA':
- period = params.get('period', 20)
- sma1 = df['close'].rolling(window=period).mean()
- tma = sma1.rolling(window=period).mean()
- return {'value': tma.bfill()}
-
- elif name == 'VWMA':
- period = params.get('period', 20)
- vwma = (df['close'] * df['volume']).rolling(period).sum() / df['volume'].rolling(period).sum()
- return {'value': vwma}
-
- # ── Momentum ──────────────────────────────────────────────────────
- elif name == 'RSI':
- period = params.get('period', 14)
- series = calculate_rsi(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'STOCHASTIC' or name == 'STOCH':
- period = params.get('period', 14)
- smooth = params.get('smooth', 3)
- result = calculate_stochastic(df, window=period, smooth_window=smooth, fillna=True)
- return {
- 'k': result['stoch_k'],
- 'd': result['stoch_d'],
- }
-
- elif name == 'STOCH_RSI':
- period = params.get('period', 14)
- smooth1 = params.get('smooth1', 3)
- smooth2 = params.get('smooth2', 3)
- result = calculate_stoch_rsi(df, window=period, smooth1=smooth1, smooth2=smooth2, fillna=True)
- return {
- 'stoch_rsi': result['stoch_rsi'],
- 'k': result['stoch_rsi_k'],
- 'd': result['stoch_rsi_d'],
- }
-
- elif name == 'WILLIAMS_R' or name == 'WILLR':
- period = params.get('period', 14)
- series = calculate_williams_r(df, lbp=period, fillna=True)
- return {'value': series}
-
- elif name == 'ROC' or name == 'MOMENTUM':
- period = params.get('period', 12)
- series = calculate_roc(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'TSI':
- window_slow = params.get('window_slow', 25)
- window_fast = params.get('window_fast', 13)
- series = calculate_tsi(df, window_slow=window_slow, window_fast=window_fast, fillna=True)
- return {'value': series}
-
- elif name == 'ULTIMATE_OSCILLATOR':
- w1 = params.get('window1', 7)
- w2 = params.get('window2', 14)
- w3 = params.get('window3', 28)
- series = calculate_ultimate_oscillator(df, window1=w1, window2=w2, window3=w3, fillna=True)
- return {'value': series}
-
- elif name == 'AWESOME_OSCILLATOR':
- w1 = params.get('window1', 5)
- w2 = params.get('window2', 34)
- series = calculate_awesome_oscillator(df, window1=w1, window2=w2, fillna=True)
- return {'value': series}
-
- elif name == 'PPO':
- fast = params.get('fast', 12)
- slow = params.get('slow', 26)
- signal = params.get('signal', 9)
- result = calculate_ppo(df, window_slow=slow, window_fast=fast, window_sign=signal, fillna=True)
- return {
- 'ppo': result['ppo'],
- 'ppo_signal': result['ppo_signal'],
- 'ppo_hist': result['ppo_hist'],
- }
-
- elif name == 'PVO':
- window_slow = params.get('window_slow', 26)
- window_fast = params.get('window_fast', 12)
- window_sign = params.get('window_sign', 9)
- result = calculate_pvo(df, window_slow=window_slow, window_fast=window_fast, window_sign=window_sign, fillna=True)
- return {
- 'pvo': result['pvo'],
- 'pvo_signal': result['pvo_signal'],
- 'pvo_hist': result['pvo_hist'],
- }
-
- # ── Trend ─────────────────────────────────────────────────────────
- elif name == 'MACD':
- fast = params.get('fast', 12)
- slow = params.get('slow', 26)
- signal = params.get('signal', 9)
- result = calculate_macd(df, window_fast=fast, window_slow=slow, window_sign=signal, fillna=True)
- return {
- 'line': result['macd'],
- 'signal_line': result['macd_signal'],
- 'histogram': result['macd_diff'],
- }
-
- elif name == 'ADX':
- period = params.get('period', 14)
- result = calculate_adx(df, window=period, fillna=True)
- return {
- 'value': result['adx'],
- 'plus_di': result['adx_pos'],
- 'minus_di': result['adx_neg'],
- }
-
- elif name == 'CCI':
- period = params.get('period', 20)
- series = calculate_cci(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'SUPERTREND':
- period = params.get('period', 10)
- multiplier = params.get('multiplier', 3.0)
- atr = calculate_atr(df, window=period, fillna=True)
- hl2 = (df['high'] + df['low']) / 2
- upper_band = hl2 + multiplier * atr
- lower_band = hl2 - multiplier * atr
- supertrend = pd.Series(index=df.index, dtype=float)
- direction = pd.Series(1, index=df.index, dtype=int)
- supertrend.iloc[0] = lower_band.iloc[0]
- for i in range(1, len(df)):
- if df['close'].iloc[i] > upper_band.iloc[i - 1]:
- direction.iloc[i] = 1
- elif df['close'].iloc[i] < lower_band.iloc[i - 1]:
- direction.iloc[i] = -1
- else:
- direction.iloc[i] = direction.iloc[i - 1]
- if direction.iloc[i] == 1:
- supertrend.iloc[i] = max(lower_band.iloc[i], supertrend.iloc[i - 1]) if direction.iloc[i - 1] == 1 else lower_band.iloc[i]
- else:
- supertrend.iloc[i] = min(upper_band.iloc[i], supertrend.iloc[i - 1]) if direction.iloc[i - 1] == -1 else upper_band.iloc[i]
- return {
- 'value': supertrend,
- 'direction': direction,
- }
-
- elif name == 'ICHIMOKU':
- w1 = params.get('window1', 9)
- w2 = params.get('window2', 26)
- w3 = params.get('window3', 52)
- result = calculate_ichimoku(df, window1=w1, window2=w2, window3=w3, fillna=True)
- return {
- 'conversion': result['ichimoku_conversion'],
- 'base': result['ichimoku_base'],
- 'span_a': result['ichimoku_a'],
- 'span_b': result['ichimoku_b'],
- }
-
- elif name == 'PSAR':
- step = params.get('step', 0.02)
- max_step = params.get('max_step', 0.2)
- result = calculate_psar(df, step=step, max_step=max_step, fillna=True)
- return {
- 'psar': result['psar'],
- 'psar_up': result['psar_up'],
- 'psar_down': result['psar_down'],
- }
-
- elif name == 'AROON':
- period = params.get('period', 25)
- result = calculate_aroon(df, window=period, fillna=True)
- return {
- 'aroon_up': result['aroon_up'],
- 'aroon_down': result['aroon_down'],
- 'aroon_indicator': result['aroon_indicator'],
- }
-
- elif name == 'STC':
- window_slow = params.get('window_slow', 50)
- window_fast = params.get('window_fast', 23)
- cycle = params.get('cycle', 10)
- series = calculate_stc(df, window_slow=window_slow, window_fast=window_fast, cycle=cycle, fillna=True)
- return {'value': series}
-
- elif name == 'KST':
- nsig = params.get('nsig', 9)
- result = calculate_kst(df, nsig=nsig, fillna=True)
- return {
- 'kst': result['kst'],
- 'kst_signal': result['kst_signal'],
- }
-
- elif name == 'VORTEX':
- period = params.get('period', 14)
- result = calculate_vortex(df, window=period, fillna=True)
- return {
- 'vortex_pos': result['vortex_pos'],
- 'vortex_neg': result['vortex_neg'],
- }
-
- elif name == 'DPO':
- period = params.get('period', 20)
- series = calculate_dpo(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'TRIX':
- period = params.get('period', 15)
- series = calculate_trix(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'MASS_INDEX':
- window_fast = params.get('window_fast', 9)
- window_slow = params.get('window_slow', 25)
- series = calculate_mass_index(df, window_fast=window_fast, window_slow=window_slow, fillna=True)
- return {'value': series}
-
- # ── Volatility ────────────────────────────────────────────────────
- elif name == 'BOLLINGER' or name == 'BB':
- period = params.get('period', 20)
- std_dev = params.get('std_dev', 2)
- result = calculate_bollinger_bands(df, window=period, window_dev=std_dev, fillna=True)
- # Calculate %B
- upper = result['bb_upper']
- lower = result['bb_lower']
- close = df['close']
- pct_b = (close - lower) / (upper - lower)
- return {
- 'upper': upper,
- 'middle': result['bb_middle'],
- 'lower': lower,
- 'pct_b': pct_b,
- }
-
- elif name == 'ATR':
- period = params.get('period', 14)
- series = calculate_atr(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'KELTNER':
- period = params.get('period', 20)
- result = calculate_keltner_channel(df, window=period, fillna=True)
- return {
- 'upper': result['kc_upper'],
- 'middle': result['kc_middle'],
- 'lower': result['kc_lower'],
- }
-
- elif name == 'DONCHIAN':
- period = params.get('period', 20)
- result = calculate_donchian_channel(df, window=period, fillna=True)
- return {
- 'upper': result['dc_upper'],
- 'middle': result['dc_middle'],
- 'lower': result['dc_lower'],
- }
-
- # ── Volume ────────────────────────────────────────────────────────
- elif name == 'OBV':
- series = calculate_obv(df, fillna=True)
- return {'value': series}
-
- elif name == 'CMF':
- period = params.get('period', 20)
- series = calculate_cmf(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'MFI':
- period = params.get('period', 14)
- series = calculate_mfi(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'FORCE_INDEX' or name == 'FI':
- period = params.get('period', 13)
- series = calculate_force_index(df, window=period, fillna=True)
- return {'value': series}
-
- elif name == 'ADI':
- series = calculate_adi(df, fillna=True)
- return {'value': series}
-
- elif name == 'EOM':
- period = params.get('period', 14)
- result = calculate_eom(df, window=period, fillna=True)
- return {
- 'value': result['eom'],
- 'signal': result['eom_signal'],
- }
-
- elif name == 'VPT':
- series = calculate_vpt(df, fillna=True)
- return {'value': series}
-
- elif name == 'NVI':
- series = calculate_nvi(df, fillna=True)
- return {'value': series}
-
- # ── Pivot Points ──────────────────────────────────────────────────
- elif name == 'PIVOT':
- pivot_type = int(params.get('type', 0)) # 0=Standard, 1=Fibonacci, 2=Woodie, 3=Camarilla
- # Use previous bar's HLC for pivot calculation
- h = float(df['high'].iloc[-2]) if len(df) > 1 else float(df['high'].iloc[-1])
- l = float(df['low'].iloc[-2]) if len(df) > 1 else float(df['low'].iloc[-1])
- c = float(df['close'].iloc[-2]) if len(df) > 1 else float(df['close'].iloc[-1])
-
- if pivot_type == 1: # Fibonacci
- pp = (h + l + c) / 3
- r1 = pp + 0.382 * (h - l)
- s1 = pp - 0.382 * (h - l)
- r2 = pp + 0.618 * (h - l)
- s2 = pp - 0.618 * (h - l)
- r3 = pp + 1.0 * (h - l)
- s3 = pp - 1.0 * (h - l)
- elif pivot_type == 2: # Woodie
- pp = (h + l + 2 * c) / 4
- r1 = 2 * pp - l
- s1 = 2 * pp - h
- r2 = pp + (h - l)
- s2 = pp - (h - l)
- r3 = h + 2 * (pp - l)
- s3 = l - 2 * (h - pp)
- elif pivot_type == 3: # Camarilla
- pp = (h + l + c) / 3
- r1 = c + 1.1 * (h - l) / 12
- s1 = c - 1.1 * (h - l) / 12
- r2 = c + 1.1 * (h - l) / 6
- s2 = c - 1.1 * (h - l) / 6
- r3 = c + 1.1 * (h - l) / 4
- s3 = c - 1.1 * (h - l) / 4
- else: # Standard
- pp = (h + l + c) / 3
- r1 = 2 * pp - l
- s1 = 2 * pp - h
- r2 = pp + (h - l)
- s2 = pp - (h - l)
- r3 = h + 2 * (pp - l)
- s3 = l - 2 * (h - pp)
-
- length = len(df)
- return {
- 'pp': pd.Series([pp] * length, index=df.index),
- 'r1': pd.Series([r1] * length, index=df.index),
- 'r2': pd.Series([r2] * length, index=df.index),
- 'r3': pd.Series([r3] * length, index=df.index),
- 's1': pd.Series([s1] * length, index=df.index),
- 's2': pd.Series([s2] * length, index=df.index),
- 's3': pd.Series([s3] * length, index=df.index),
- }
-
- else:
- raise ValueError(f"Unknown indicator: {name}")
-
-
-def get_latest_value(name: str, df: pd.DataFrame, params: dict, field: str = 'value') -> float:
- """Get the most recent value of an indicator field."""
- result = compute_indicator(name, df, params)
- if field not in result:
- raise ValueError(f"Indicator {name} has no field '{field}'. Available: {list(result.keys())}")
- series = result[field]
- val = series.iloc[-1]
- if pd.isna(val):
- return float('nan')
- return float(val)
-
-
-def get_last_n_values(name: str, df: pd.DataFrame, params: dict, field: str = 'value', n: int = 2) -> list:
- """Get the last N values of an indicator field (for crossing detection)."""
- result = compute_indicator(name, df, params)
- if field not in result:
- raise ValueError(f"Indicator {name} has no field '{field}'. Available: {list(result.keys())}")
- series = result[field]
- values = series.iloc[-n:].tolist()
- return [float(v) if not pd.isna(v) else float('nan') for v in values]
-
-
-def get_value_at_offset(name: str, df: pd.DataFrame, params: dict, field: str = 'value', offset: int = 0) -> float:
- """Get value of an indicator at N bars ago (offset=0 is latest, offset=1 is previous, etc.)."""
- result = compute_indicator(name, df, params)
- if field not in result:
- raise ValueError(f"Indicator {name} has no field '{field}'. Available: {list(result.keys())}")
- series = result[field]
- idx = -(offset + 1)
- if abs(idx) > len(series):
- return float('nan')
- val = series.iloc[idx]
- return float(val) if not pd.isna(val) else float('nan')
diff --git a/fincept-qt/scripts/algo_trading/scanner_engine.py b/fincept-qt/scripts/algo_trading/scanner_engine.py
deleted file mode 100644
index 1b015a7ce..000000000
--- a/fincept-qt/scripts/algo_trading/scanner_engine.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""
-Scanner Engine
-
-One-shot scanner: evaluates conditions across multiple symbols.
-Returns list of symbols that match the given conditions.
-
-Usage (called by C++ AlgoTradingService):
- python scanner_engine.py scan <json_params> --db <path>
-
-JSON params:
- {
- "conditions": [...],
- "symbols": [...],
- "timeframe": "1d",
- "lookback_days": 365,
- "logic": "AND"
- }
-"""
-
-import json
-import sys
-import argparse
-import sqlite3
-import os
-
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from condition_evaluator import load_candles_from_db, evaluate_condition_group
-
-
-def get_db_path(arg_db: str) -> str:
- if arg_db and os.path.exists(arg_db):
- return arg_db
- appdata = os.environ.get('APPDATA', '')
- if appdata:
- candidate = os.path.join(appdata, 'Fincept', 'FinceptTerminal', 'fincept.db')
- if os.path.exists(candidate):
- return candidate
- return arg_db or ''
-
-
-def main():
- parser = argparse.ArgumentParser(description='Algo Scanner Engine')
- parser.add_argument('command', choices=['scan'], help='Subcommand')
- parser.add_argument('payload', help='JSON params: conditions, symbols, timeframe, lookback_days, logic')
- parser.add_argument('--db', default=None, help='SQLite database path')
- args = parser.parse_args()
-
- db_path = get_db_path(args.db)
-
- try:
- params = json.loads(args.payload)
- except json.JSONDecodeError as e:
- print(json.dumps({'success': False, 'error': f'Invalid JSON: {e}'}))
- sys.exit(1)
-
- conditions = params.get('conditions', [])
- symbols = params.get('symbols', [])
- timeframe = params.get('timeframe', '1d')
- limit = int(params.get('lookback_days', 365))
- logic = params.get('logic', 'AND')
-
- if not conditions:
- print(json.dumps({'success': False, 'error': 'No conditions provided'}))
- sys.exit(1)
-
- if not isinstance(symbols, list) or not symbols:
- print(json.dumps({'success': False, 'error': 'symbols must be a non-empty array'}))
- sys.exit(1)
-
- matches = []
- errors = []
- scanned = 0
- debug_log = []
-
- debug_log.append(f'[scanner] db={db_path}')
- debug_log.append(f'[scanner] timeframe={timeframe}, symbols={len(symbols)}, conditions={len(conditions)}, logic={logic}')
-
- # Log candle_cache state for diagnostics
- try:
- conn_check = sqlite3.connect(db_path)
- cur = conn_check.cursor()
- cur.execute('SELECT COUNT(*) FROM candle_cache WHERE timeframe = ?', (timeframe,))
- total_rows = cur.fetchone()[0]
- debug_log.append(f'[scanner] candle_cache rows for tf={timeframe}: {total_rows}')
- conn_check.close()
- except Exception as e:
- debug_log.append(f'[scanner] DB check skipped: {e}')
-
- for symbol in symbols:
- scanned += 1
- try:
- df = load_candles_from_db(db_path, symbol, timeframe, limit)
- if df.empty or len(df) < 10:
- errors.append({'symbol': symbol, 'error': f'Insufficient data ({len(df)} candles)'})
- continue
-
- result = evaluate_condition_group(conditions, df)
-
- if result['result']:
- current_price = float(df['close'].iloc[-1])
- matches.append({
- 'symbol': symbol,
- 'price': current_price,
- 'conditions': result.get('details', []),
- })
-
- except Exception as e:
- errors.append({'symbol': symbol, 'error': str(e)})
- debug_log.append(f'[scanner] {symbol} exception: {e}')
-
- debug_log.append(f'[scanner] done: scanned={scanned}, matches={len(matches)}, errors={len(errors)}')
-
- print(json.dumps({
- 'success': True,
- 'matches': matches,
- 'match_count': len(matches),
- 'total_scanned': scanned,
- 'condition_count': len(conditions),
- 'errors': errors,
- 'timeframe': timeframe,
- 'scanner_debug': debug_log,
- }))
-
-
-if __name__ == '__main__':
- main()
diff --git a/fincept-qt/src/algo_engine/AlgoEngine.cpp b/fincept-qt/src/algo_engine/AlgoEngine.cpp
new file mode 100644
index 000000000..5142e254e
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoEngine.cpp
@@ -0,0 +1,258 @@
+// src/algo_engine/AlgoEngine.cpp
+#include "algo_engine/AlgoEngine.h"
+#include "core/logging/Logger.h"
+#include "datahub/DataHub.h"
+#include "storage/sqlite/Database.h"
+#include "trading/UnifiedTrading.h"
+
+#include <QDateTime>
+#include <QMetaObject>
+#include <QPointer>
+#include <QSqlQuery>
+#include <QtConcurrent>
+
+namespace fincept::algo {
+
+AlgoEngine& AlgoEngine::instance() {
+ static AlgoEngine s;
+ return s;
+}
+
+AlgoEngine::AlgoEngine() {
+ engine_thread_.setObjectName(QStringLiteral("AlgoEngineThread"));
+ engine_thread_.start();
+ moveToThread(&engine_thread_);
+}
+
+AlgoEngine::~AlgoEngine() {
+ stop_all();
+ engine_thread_.quit();
+ engine_thread_.wait(5000);
+}
+
+void AlgoEngine::start_deployment(const services::algo::AlgoDeployment& deployment,
+ const services::algo::AlgoStrategy& strategy) {
+ QMutexLocker lock(&mutex_);
+ if (runners_.contains(deployment.id)) {
+ emit error_occurred(deployment.id, QStringLiteral("Deployment already running"));
+ return;
+ }
+
+ auto* runner = new DeploymentRunner(deployment, strategy);
+ runner->moveToThread(&engine_thread_);
+
+ connect(runner, &DeploymentRunner::trade_executed, this, &AlgoEngine::trade_executed);
+ connect(runner, &DeploymentRunner::metrics_updated, this, &AlgoEngine::metrics_updated);
+ connect(runner, &DeploymentRunner::error_occurred, this, &AlgoEngine::error_occurred);
+ connect(runner, &DeploymentRunner::order_requested, this, &AlgoEngine::on_order_requested);
+ connect(runner, &DeploymentRunner::status_changed, this, [this](const QString& id, const QString& status) {
+ if (status == "stopped" || status == "error") {
+ QMutexLocker lock(&mutex_);
+ if (auto* r = runners_.take(id)) {
+ r->deleteLater();
+ emit deployment_stopped(id);
+ }
+ }
+ auto& hub = datahub::DataHub::instance();
+ hub.publish(QStringLiteral("algo:state:") + id, QVariant::fromValue(status));
+ });
+
+ // Publish metrics to DataHub on update
+ connect(runner, &DeploymentRunner::metrics_updated, this,
+ [](const QString& dep_id, const AlgoMetrics& m) {
+ datahub::DataHub::instance().publish(
+ QStringLiteral("algo:metrics:") + dep_id, QVariant::fromValue(m));
+ });
+ connect(runner, &DeploymentRunner::trade_executed, this,
+ [](const AlgoTradeRecord& trade) {
+ datahub::DataHub::instance().publish(
+ QStringLiteral("algo:trade:") + trade.deployment_id,
+ QVariant::fromValue(trade));
+ });
+
+ runners_.insert(deployment.id, runner);
+ lock.unlock();
+
+ QMetaObject::invokeMethod(runner, &DeploymentRunner::start, Qt::QueuedConnection);
+ emit deployment_started(deployment.id);
+ LOG_INFO("AlgoEngine", QString("Started deployment %1 for strategy '%2' on %3")
+ .arg(deployment.id, strategy.name, deployment.symbol));
+}
+
+void AlgoEngine::stop_deployment(const QString& deployment_id) {
+ QMutexLocker lock(&mutex_);
+ auto* runner = runners_.value(deployment_id, nullptr);
+ if (!runner) return;
+ lock.unlock();
+ QMetaObject::invokeMethod(runner, &DeploymentRunner::stop, Qt::QueuedConnection);
+}
+
+void AlgoEngine::pause_deployment(const QString& deployment_id) {
+ QMutexLocker lock(&mutex_);
+ auto* runner = runners_.value(deployment_id, nullptr);
+ if (!runner) return;
+ lock.unlock();
+ QMetaObject::invokeMethod(runner, &DeploymentRunner::pause, Qt::QueuedConnection);
+}
+
+void AlgoEngine::resume_deployment(const QString& deployment_id) {
+ QMutexLocker lock(&mutex_);
+ auto* runner = runners_.value(deployment_id, nullptr);
+ if (!runner) return;
+ lock.unlock();
+ QMetaObject::invokeMethod(runner, &DeploymentRunner::resume, Qt::QueuedConnection);
+}
+
+void AlgoEngine::stop_all() {
+ QMutexLocker lock(&mutex_);
+ auto ids = runners_.keys();
+ lock.unlock();
+ for (const auto& id : ids)
+ stop_deployment(id);
+}
+
+bool AlgoEngine::is_running(const QString& deployment_id) const {
+ QMutexLocker lock(&mutex_);
+ auto* runner = runners_.value(deployment_id, nullptr);
+ return runner && runner->is_running();
+}
+
+QStringList AlgoEngine::active_deployment_ids() const {
+ QMutexLocker lock(&mutex_);
+ return runners_.keys();
+}
+
+AlgoMetrics AlgoEngine::metrics(const QString& deployment_id) const {
+ QMutexLocker lock(&mutex_);
+ auto* runner = runners_.value(deployment_id, nullptr);
+ return runner ? runner->metrics() : AlgoMetrics{};
+}
+
+int AlgoEngine::active_count() const {
+ QMutexLocker lock(&mutex_);
+ return runners_.size();
+}
+
+void AlgoEngine::on_order_requested(const AlgoOrderSignal& signal) {
+ execute_order(signal);
+}
+
+void AlgoEngine::execute_order(const AlgoOrderSignal& signal) {
+ QPointer<AlgoEngine> self = this;
+ QString dep_id = signal.deployment_id;
+
+ fincept::trading::UnifiedOrder order;
+ order.symbol = signal.symbol;
+ order.exchange = signal.exchange;
+ order.side = (signal.side == "BUY") ? trading::OrderSide::Buy : trading::OrderSide::Sell;
+ order.order_type = trading::OrderType::Market;
+ order.quantity = signal.quantity;
+ if (signal.product_type == "CNC" || signal.product_type == "delivery")
+ order.product_type = trading::ProductType::Delivery;
+ else if (signal.product_type == "NRML" || signal.product_type == "margin")
+ order.product_type = trading::ProductType::Margin;
+ else
+ order.product_type = trading::ProductType::Intraday;
+
+ QString account_id = signal.account_id;
+ double submitted_price = signal.price;
+
+ QtConcurrent::run([self, dep_id, account_id, order, submitted_price]() {
+ auto response = fincept::trading::UnifiedTrading::instance()
+ .place_order(account_id, order);
+
+ if (!self) return;
+ QMetaObject::invokeMethod(self, [self, dep_id, response, order]() {
+ if (!self) return;
+ QMutexLocker lock(&self->mutex_);
+ auto* runner = self->runners_.value(dep_id, nullptr);
+ if (!runner) return;
+ lock.unlock();
+
+ if (response.success) {
+ runner->on_order_filled(response.order_id, order.quantity > 0 ? order.price : 0, order.quantity);
+ } else {
+ runner->on_order_rejected(response.order_id, response.message);
+ }
+ }, Qt::QueuedConnection);
+ });
+}
+
+void AlgoEngine::list_deployments() {
+ QPointer<AlgoEngine> self = this;
+ QtConcurrent::run([self]() {
+ auto db = fincept::Database::instance().connection();
+ QSqlQuery q(db);
+ q.exec(QStringLiteral("SELECT * FROM algo_deployments ORDER BY created_at DESC"));
+
+ QVector<services::algo::AlgoDeployment> deployments;
+ while (q.next()) {
+ services::algo::AlgoDeployment d;
+ d.id = q.value("id").toString();
+ d.strategy_id = q.value("strategy_id").toString();
+ d.strategy_name = q.value("strategy_name").toString();
+ d.symbol = q.value("symbol").toString();
+ d.exchange = q.value("exchange").toString();
+ d.product_type = q.value("product_type").toString();
+ d.mode = q.value("mode").toString();
+ d.entry_side = q.value("entry_side").toString();
+ d.backend = q.value("backend").toString();
+ d.broker_id = q.value("broker_id").toString();
+ d.broker_account_id = q.value("broker_account_id").toString();
+ d.status = q.value("status").toString();
+ d.timeframe = q.value("timeframe").toString();
+ d.quantity = q.value("quantity").toDouble();
+ d.max_order_value = q.value("max_order_value").toDouble();
+ d.max_daily_loss = q.value("max_daily_loss").toDouble();
+ d.created_at = q.value("created_at").toString();
+ deployments.append(d);
+ }
+
+ // Load live metrics for running deployments
+ QSqlQuery mq(db);
+ mq.exec(QStringLiteral("SELECT * FROM algo_metrics"));
+ QHash<QString, int> metrics_idx;
+ while (mq.next()) {
+ QString dep_id = mq.value("deployment_id").toString();
+ for (int i = 0; i < deployments.size(); ++i) {
+ if (deployments[i].id == dep_id) {
+ deployments[i].total_pnl = mq.value("total_pnl").toDouble();
+ deployments[i].unrealized_pnl = mq.value("unrealized_pnl").toDouble();
+ deployments[i].total_trades = mq.value("total_trades").toInt();
+ deployments[i].win_rate = mq.value("win_rate").toDouble();
+ deployments[i].max_drawdown = mq.value("max_drawdown").toDouble();
+ break;
+ }
+ }
+ }
+
+ if (!self) return;
+ QMetaObject::invokeMethod(self, [self, deployments]() {
+ if (!self) return;
+ emit self->deployments_loaded(deployments);
+ }, Qt::QueuedConnection);
+ });
+}
+
+void AlgoEngine::recover_orphaned() {
+ auto db = fincept::Database::instance().connection();
+ QSqlQuery q(db);
+ q.exec(QStringLiteral(
+ "SELECT id FROM algo_deployments WHERE status IN ('running', 'starting')"));
+ while (q.next()) {
+ QString id = q.value(0).toString();
+ QSqlQuery u(db);
+ u.prepare(QStringLiteral(
+ "UPDATE algo_deployments SET status = 'crashed', "
+ "error_message = 'Application restarted' WHERE id = ?"));
+ u.addBindValue(id);
+ u.exec();
+
+ datahub::DataHub::instance().publish(
+ QStringLiteral("algo:state:") + id, QVariant::fromValue(QStringLiteral("crashed")));
+ emit deployment_crashed(id, QStringLiteral("Application restarted unexpectedly"));
+ LOG_WARN("AlgoEngine", QString("Marked orphaned deployment %1 as crashed").arg(id));
+ }
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/AlgoEngine.h b/fincept-qt/src/algo_engine/AlgoEngine.h
new file mode 100644
index 000000000..e60d220dd
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoEngine.h
@@ -0,0 +1,59 @@
+// src/algo_engine/AlgoEngine.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "algo_engine/DeploymentRunner.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QHash>
+#include <QMutex>
+#include <QObject>
+#include <QThread>
+#include <QTimer>
+
+namespace fincept::algo {
+
+class AlgoEngine : public QObject {
+ Q_OBJECT
+public:
+ static AlgoEngine& instance();
+
+ void start_deployment(const fincept::services::algo::AlgoDeployment& deployment,
+ const fincept::services::algo::AlgoStrategy& strategy);
+ void stop_deployment(const QString& deployment_id);
+ void pause_deployment(const QString& deployment_id);
+ void resume_deployment(const QString& deployment_id);
+ void stop_all();
+
+ bool is_running(const QString& deployment_id) const;
+ QStringList active_deployment_ids() const;
+ AlgoMetrics metrics(const QString& deployment_id) const;
+ int active_count() const;
+
+ void list_deployments();
+ void recover_orphaned();
+
+signals:
+ void deployment_started(const QString& deployment_id);
+ void deployment_stopped(const QString& deployment_id);
+ void deployment_crashed(const QString& deployment_id, const QString& reason);
+ void deployments_loaded(QVector<fincept::services::algo::AlgoDeployment> deployments);
+ void trade_executed(const fincept::algo::AlgoTradeRecord& trade);
+ void metrics_updated(const QString& deployment_id, const fincept::algo::AlgoMetrics& metrics);
+ void error_occurred(const QString& deployment_id, const QString& error);
+
+private slots:
+ void on_order_requested(const fincept::algo::AlgoOrderSignal& signal);
+
+private:
+ AlgoEngine();
+ ~AlgoEngine() override;
+ Q_DISABLE_COPY(AlgoEngine)
+
+ void execute_order(const AlgoOrderSignal& signal);
+
+ QThread engine_thread_;
+ mutable QMutex mutex_;
+ QHash<QString, DeploymentRunner*> runners_;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/AlgoEngineProducer.cpp b/fincept-qt/src/algo_engine/AlgoEngineProducer.cpp
new file mode 100644
index 000000000..59e8b865b
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoEngineProducer.cpp
@@ -0,0 +1,57 @@
+// src/algo_engine/AlgoEngineProducer.cpp
+#include "algo_engine/AlgoEngineProducer.h"
+#include "algo_engine/AlgoEngine.h"
+#include "datahub/DataHub.h"
+
+namespace fincept::algo {
+
+AlgoEngineProducer& AlgoEngineProducer::instance() {
+ static AlgoEngineProducer s;
+ return s;
+}
+
+AlgoEngineProducer::AlgoEngineProducer() = default;
+
+void AlgoEngineProducer::ensure_registered_with_hub() {
+ if (hub_registered_) return;
+
+ auto& hub = datahub::DataHub::instance();
+ hub.register_producer(this);
+
+ datahub::TopicPolicy metrics_policy;
+ metrics_policy.push_only = true;
+ metrics_policy.coalesce_within_ms = 1000;
+ metrics_policy.drop_on_idle = true;
+ hub.set_policy_pattern(QStringLiteral("algo:metrics:*"), metrics_policy);
+
+ datahub::TopicPolicy trade_policy;
+ trade_policy.push_only = true;
+ trade_policy.drop_on_idle = true;
+ hub.set_policy_pattern(QStringLiteral("algo:trade:*"), trade_policy);
+
+ datahub::TopicPolicy state_policy;
+ state_policy.push_only = true;
+ hub.set_policy_pattern(QStringLiteral("algo:state:*"), state_policy);
+
+ hub_registered_ = true;
+
+ AlgoEngine::instance().recover_orphaned();
+}
+
+QStringList AlgoEngineProducer::topic_patterns() const {
+ return {
+ QStringLiteral("algo:metrics:*"),
+ QStringLiteral("algo:trade:*"),
+ QStringLiteral("algo:state:*"),
+ };
+}
+
+void AlgoEngineProducer::refresh(const QStringList& /*topics*/) {
+ // Push-only producer — no pull refresh needed
+}
+
+int AlgoEngineProducer::max_requests_per_sec() const {
+ return 0;
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/AlgoEngineProducer.h b/fincept-qt/src/algo_engine/AlgoEngineProducer.h
new file mode 100644
index 000000000..9dbded4a1
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoEngineProducer.h
@@ -0,0 +1,24 @@
+// src/algo_engine/AlgoEngineProducer.h
+#pragma once
+#include "datahub/Producer.h"
+
+#include <QObject>
+
+namespace fincept::algo {
+
+class AlgoEngineProducer : public QObject, public fincept::datahub::Producer {
+ Q_OBJECT
+public:
+ static AlgoEngineProducer& instance();
+ void ensure_registered_with_hub();
+
+ QStringList topic_patterns() const override;
+ void refresh(const QStringList& topics) override;
+ int max_requests_per_sec() const override;
+
+private:
+ AlgoEngineProducer();
+ bool hub_registered_ = false;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/AlgoEngineTypes.cpp b/fincept-qt/src/algo_engine/AlgoEngineTypes.cpp
new file mode 100644
index 000000000..17ee5e8c3
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoEngineTypes.cpp
@@ -0,0 +1,8 @@
+// src/algo_engine/AlgoEngineTypes.cpp
+#include "algo_engine/AlgoEngineTypes.h"
+
+namespace {
+const int reg_algo_metrics = qRegisterMetaType<fincept::algo::AlgoMetrics>("fincept::algo::AlgoMetrics");
+const int reg_algo_trade = qRegisterMetaType<fincept::algo::AlgoTradeRecord>("fincept::algo::AlgoTradeRecord");
+const int reg_ohlcv = qRegisterMetaType<fincept::algo::OhlcvCandle>("fincept::algo::OhlcvCandle");
+} // namespace
diff --git a/fincept-qt/src/algo_engine/AlgoEngineTypes.h b/fincept-qt/src/algo_engine/AlgoEngineTypes.h
new file mode 100644
index 000000000..d6b5c0680
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoEngineTypes.h
@@ -0,0 +1,183 @@
+// src/algo_engine/AlgoEngineTypes.h
+#pragma once
+#include <QHash>
+#include <QMetaType>
+#include <QString>
+#include <QVector>
+
+#include <cstdint>
+#include <optional>
+
+namespace fincept::algo {
+
+// ── OHLCV Candle ────────────────────────────────────────────────────────────
+
+struct OhlcvCandle {
+ int64_t open_time = 0;
+ int64_t close_time = 0;
+ double open = 0;
+ double high = 0;
+ double low = 0;
+ double close = 0;
+ double volume = 0;
+ bool is_closed = false;
+};
+
+// ── Timeframe ───────────────────────────────────────────────────────────────
+
+enum class Timeframe { M1, M3, M5, M15, M30, H1, H4, D1 };
+
+inline int timeframe_seconds(Timeframe tf) {
+ switch (tf) {
+ case Timeframe::M1: return 60;
+ case Timeframe::M3: return 180;
+ case Timeframe::M5: return 300;
+ case Timeframe::M15: return 900;
+ case Timeframe::M30: return 1800;
+ case Timeframe::H1: return 3600;
+ case Timeframe::H4: return 14400;
+ case Timeframe::D1: return 86400;
+ }
+ return 60;
+}
+
+inline Timeframe timeframe_from_string(const QString& s) {
+ if (s == "1m") return Timeframe::M1;
+ if (s == "3m") return Timeframe::M3;
+ if (s == "5m") return Timeframe::M5;
+ if (s == "15m") return Timeframe::M15;
+ if (s == "30m") return Timeframe::M30;
+ if (s == "1h") return Timeframe::H1;
+ if (s == "4h") return Timeframe::H4;
+ if (s == "1d") return Timeframe::D1;
+ return Timeframe::M5;
+}
+
+inline QString timeframe_to_string(Timeframe tf) {
+ switch (tf) {
+ case Timeframe::M1: return QStringLiteral("1m");
+ case Timeframe::M3: return QStringLiteral("3m");
+ case Timeframe::M5: return QStringLiteral("5m");
+ case Timeframe::M15: return QStringLiteral("15m");
+ case Timeframe::M30: return QStringLiteral("30m");
+ case Timeframe::H1: return QStringLiteral("1h");
+ case Timeframe::H4: return QStringLiteral("4h");
+ case Timeframe::D1: return QStringLiteral("1d");
+ }
+ return QStringLiteral("5m");
+}
+
+// ── Indicator result ────────────────────────────────────────────────────────
+
+struct IndicatorResult {
+ QHash<QString, double> current;
+ QHash<QString, double> previous;
+ bool valid = false;
+ QString error;
+};
+
+// ── Condition evaluation ────────────────────────────────────────────────────
+
+struct ConditionResult {
+ bool met = false;
+ QString indicator;
+ QString field;
+ double computed_value = 0;
+ double target_value = 0;
+ QString op;
+ QString error;
+};
+
+struct GroupEvalResult {
+ bool triggered = false;
+ QVector<ConditionResult> details;
+ QString logic;
+};
+
+// ── Position ────────────────────────────────────────────────────────────────
+
+enum class PositionSide { None, Long, Short };
+
+inline QString position_side_to_string(PositionSide s) {
+ switch (s) {
+ case PositionSide::Long: return QStringLiteral("LONG");
+ case PositionSide::Short: return QStringLiteral("SHORT");
+ default: return QStringLiteral("NONE");
+ }
+}
+
+struct AlgoPosition {
+ PositionSide side = PositionSide::None;
+ double quantity = 0;
+ double entry_price = 0;
+ int64_t entry_time = 0;
+ double unrealized_pnl = 0;
+ double highest_since_entry = 0;
+ double lowest_since_entry = 0;
+};
+
+// ── Risk ────────────────────────────────────────────────────────────────────
+
+struct RiskState {
+ double daily_pnl = 0;
+ double max_drawdown = 0;
+ double peak_equity = 0;
+ bool paused_by_loss_limit = false;
+ int64_t day_start_epoch = 0;
+};
+
+// ── Trade record ────────────────────────────────────────────────────────────
+
+struct AlgoTradeRecord {
+ QString id;
+ QString deployment_id;
+ QString symbol;
+ QString side;
+ double quantity = 0;
+ double price = 0;
+ double pnl = 0;
+ QString reason;
+ int64_t timestamp = 0;
+ QString broker_order_id;
+ int64_t latency_ms = 0;
+};
+
+// ── Metrics ─────────────────────────────────────────────────────────────────
+
+struct AlgoMetrics {
+ double total_pnl = 0;
+ double unrealized_pnl = 0;
+ int total_trades = 0;
+ int winning_trades = 0;
+ int losing_trades = 0;
+ double win_rate = 0;
+ double max_drawdown = 0;
+ double current_price = 0;
+ double current_position_qty = 0;
+ QString current_position_side;
+ double current_position_entry = 0;
+ int64_t last_signal_time = 0;
+ int64_t last_trade_time = 0;
+};
+
+// ── Order signal ────────────────────────────────────────────────────────────
+
+struct AlgoOrderSignal {
+ QString deployment_id;
+ QString account_id;
+ QString symbol;
+ QString exchange;
+ QString product_type;
+ QString side;
+ double quantity = 0;
+ QString order_type = "MARKET";
+ double price = 0;
+ double trigger_price = 0;
+ QString reason;
+};
+
+} // namespace fincept::algo
+
+Q_DECLARE_METATYPE(fincept::algo::AlgoMetrics)
+Q_DECLARE_METATYPE(fincept::algo::AlgoTradeRecord)
+Q_DECLARE_METATYPE(fincept::algo::OhlcvCandle)
diff --git a/fincept-qt/src/algo_engine/AlgoScanner.cpp b/fincept-qt/src/algo_engine/AlgoScanner.cpp
new file mode 100644
index 000000000..e3fc98347
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoScanner.cpp
@@ -0,0 +1,95 @@
+// src/algo_engine/AlgoScanner.cpp
+#include "algo_engine/AlgoScanner.h"
+#include "algo_engine/ConditionEvaluator.h"
+#include "core/logging/Logger.h"
+
+#include <QJsonDocument>
+
+namespace fincept::algo {
+
+AlgoScanner& AlgoScanner::instance() {
+ static AlgoScanner s;
+ return s;
+}
+
+void AlgoScanner::scan(const QJsonArray& conditions, const QStringList& symbols,
+ const QString& timeframe, int lookback_days, const QString& logic,
+ DataSource source, const QString& broker_id, const QString& account_id) {
+ if (conditions.isEmpty()) {
+ emit scan_error(QStringLiteral("No conditions provided"));
+ return;
+ }
+ if (symbols.isEmpty()) {
+ emit scan_error(QStringLiteral("No symbols provided"));
+ return;
+ }
+
+ LOG_INFO("AlgoScanner", QString("Scanning %1 symbols via %2")
+ .arg(symbols.size()).arg(data_source_to_string(source)));
+
+ CandleDataFetcher::instance().fetch_multi(
+ symbols, timeframe, lookback_days, source, broker_id, account_id,
+ [this, conditions, logic](const QHash<QString, QVector<OhlcvCandle>>& data,
+ const QStringList& fetch_errors) {
+ QVector<ScanMatch> matches;
+ QStringList all_errors = fetch_errors;
+ int scanned = 0;
+
+ for (auto it = data.begin(); it != data.end(); ++it) {
+ scanned++;
+ const auto& candles = it.value();
+ if (candles.size() < 20) {
+ all_errors.append(QString("%1: insufficient data (%2 candles)")
+ .arg(it.key()).arg(candles.size()));
+ continue;
+ }
+
+ auto eval = ConditionEvaluator::evaluate_group(conditions, logic, candles);
+ if (eval.triggered) {
+ ScanMatch m;
+ m.symbol = it.key();
+ m.price = candles.last().close;
+ m.details = eval.details;
+ matches.append(m);
+ }
+ }
+
+ QJsonObject out;
+ out["success"] = true;
+ out["total_scanned"] = scanned;
+ out["condition_count"] = conditions.size();
+
+ QJsonArray matches_arr;
+ for (const auto& m : matches) {
+ QJsonObject mo;
+ mo["symbol"] = m.symbol;
+ mo["price"] = m.price;
+ QJsonArray conds;
+ for (const auto& d : m.details) {
+ QJsonObject co;
+ co["indicator"] = d.indicator;
+ co["field"] = d.field;
+ co["operator"] = d.op;
+ co["value"] = d.target_value;
+ conds.append(co);
+ }
+ mo["conditions"] = conds;
+ matches_arr.append(mo);
+ }
+ out["matches"] = matches_arr;
+
+ QJsonArray err_arr;
+ for (const auto& e : all_errors) {
+ QJsonObject eo;
+ eo["error"] = e;
+ err_arr.append(eo);
+ }
+ out["errors"] = err_arr;
+
+ emit scan_complete(out);
+ LOG_INFO("AlgoScanner", QString("Scan done: %1 matches / %2 scanned")
+ .arg(matches.size()).arg(scanned));
+ });
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/AlgoScanner.h b/fincept-qt/src/algo_engine/AlgoScanner.h
new file mode 100644
index 000000000..05738721f
--- /dev/null
+++ b/fincept-qt/src/algo_engine/AlgoScanner.h
@@ -0,0 +1,37 @@
+// src/algo_engine/AlgoScanner.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "algo_engine/CandleDataFetcher.h"
+
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QObject>
+
+namespace fincept::algo {
+
+struct ScanMatch {
+ QString symbol;
+ double price = 0;
+ QVector<ConditionResult> details;
+};
+
+class AlgoScanner : public QObject {
+ Q_OBJECT
+public:
+ static AlgoScanner& instance();
+
+ void scan(const QJsonArray& conditions, const QStringList& symbols,
+ const QString& timeframe, int lookback_days, const QString& logic,
+ DataSource source = DataSource::Auto,
+ const QString& broker_id = {}, const QString& account_id = {});
+
+signals:
+ void scan_complete(const QJsonObject& result);
+ void scan_error(const QString& error);
+
+private:
+ AlgoScanner() = default;
+ Q_DISABLE_COPY(AlgoScanner)
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/CandleAggregator.cpp b/fincept-qt/src/algo_engine/CandleAggregator.cpp
new file mode 100644
index 000000000..009a0c9cf
--- /dev/null
+++ b/fincept-qt/src/algo_engine/CandleAggregator.cpp
@@ -0,0 +1,93 @@
+// src/algo_engine/CandleAggregator.cpp
+#include "algo_engine/CandleAggregator.h"
+
+#include <QMutexLocker>
+
+namespace fincept::algo {
+
+CandleAggregator::CandleAggregator(const QString& symbol, Timeframe tf,
+ int buffer_size, QObject* parent)
+ : QObject(parent)
+ , symbol_(symbol)
+ , timeframe_(tf)
+ , period_ms_(static_cast<int64_t>(timeframe_seconds(tf)) * 1000)
+ , max_buffer_(buffer_size) {}
+
+void CandleAggregator::on_tick(double price, double volume, int64_t timestamp_ms) {
+ QMutexLocker lock(&mutex_);
+
+ if (!has_first_tick_) {
+ has_first_tick_ = true;
+ int64_t candle_start = align_to_period(timestamp_ms);
+ current_.open_time = candle_start;
+ current_.close_time = candle_start + period_ms_;
+ current_.open = price;
+ current_.high = price;
+ current_.low = price;
+ current_.close = price;
+ current_.volume = volume;
+ current_.is_closed = false;
+ return;
+ }
+
+ if (timestamp_ms >= current_.close_time) {
+ close_current_and_open_new(timestamp_ms, price, volume);
+ return;
+ }
+
+ current_.close = price;
+ if (price > current_.high) current_.high = price;
+ if (price < current_.low) current_.low = price;
+ current_.volume += volume;
+}
+
+void CandleAggregator::close_current_and_open_new(int64_t tick_time,
+ double price, double volume) {
+ current_.is_closed = true;
+ OhlcvCandle closed = current_;
+
+ buffer_.append(closed);
+ if (buffer_.size() > max_buffer_)
+ buffer_.removeFirst();
+
+ int64_t new_start = align_to_period(tick_time);
+ current_.open_time = new_start;
+ current_.close_time = new_start + period_ms_;
+ current_.open = price;
+ current_.high = price;
+ current_.low = price;
+ current_.close = price;
+ current_.volume = volume;
+ current_.is_closed = false;
+
+ // unlock before emitting — receivers may call closed_candles()
+ mutex_.unlock();
+ emit candle_closed(closed);
+ mutex_.lock();
+}
+
+int64_t CandleAggregator::align_to_period(int64_t timestamp_ms) const {
+ return (timestamp_ms / period_ms_) * period_ms_;
+}
+
+QVector<OhlcvCandle> CandleAggregator::closed_candles() const {
+ QMutexLocker lock(&mutex_);
+ return buffer_;
+}
+
+OhlcvCandle CandleAggregator::current_candle() const {
+ QMutexLocker lock(&mutex_);
+ return current_;
+}
+
+void CandleAggregator::warm_from(const QVector<OhlcvCandle>& historical) {
+ QMutexLocker lock(&mutex_);
+ buffer_.clear();
+ for (const auto& c : historical) {
+ buffer_.append(c);
+ if (buffer_.size() > max_buffer_)
+ buffer_.removeFirst();
+ }
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/CandleAggregator.h b/fincept-qt/src/algo_engine/CandleAggregator.h
new file mode 100644
index 000000000..6f5694e45
--- /dev/null
+++ b/fincept-qt/src/algo_engine/CandleAggregator.h
@@ -0,0 +1,43 @@
+// src/algo_engine/CandleAggregator.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+
+#include <QMutex>
+#include <QObject>
+#include <QVector>
+
+namespace fincept::algo {
+
+class CandleAggregator : public QObject {
+ Q_OBJECT
+public:
+ explicit CandleAggregator(const QString& symbol, Timeframe tf,
+ int buffer_size = 200, QObject* parent = nullptr);
+
+ void on_tick(double price, double volume, int64_t timestamp_ms);
+
+ QVector<OhlcvCandle> closed_candles() const;
+ OhlcvCandle current_candle() const;
+ int buffer_size() const { return max_buffer_; }
+
+ void warm_from(const QVector<OhlcvCandle>& historical);
+
+signals:
+ void candle_closed(const fincept::algo::OhlcvCandle& candle);
+
+private:
+ void close_current_and_open_new(int64_t tick_time, double price, double volume);
+ int64_t align_to_period(int64_t timestamp_ms) const;
+
+ QString symbol_;
+ Timeframe timeframe_;
+ int64_t period_ms_;
+ int max_buffer_;
+
+ mutable QMutex mutex_;
+ QVector<OhlcvCandle> buffer_;
+ OhlcvCandle current_;
+ bool has_first_tick_ = false;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/CandleDataFetcher.cpp b/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
new file mode 100644
index 000000000..77394d169
--- /dev/null
+++ b/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
@@ -0,0 +1,224 @@
+// src/algo_engine/CandleDataFetcher.cpp
+#include "algo_engine/CandleDataFetcher.h"
+#include "core/logging/Logger.h"
+#include "python/PythonRunner.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
+
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QPointer>
+#include <QtConcurrent>
+
+namespace fincept::algo {
+
+CandleDataFetcher& CandleDataFetcher::instance() {
+ static CandleDataFetcher s;
+ return s;
+}
+
+QVector<OhlcvCandle> CandleDataFetcher::broker_candles_to_ohlcv(
+ const QVector<trading::BrokerCandle>& src) {
+ QVector<OhlcvCandle> out;
+ out.reserve(src.size());
+ for (const auto& c : src) {
+ OhlcvCandle o;
+ o.open_time = c.timestamp;
+ o.open = c.open;
+ o.high = c.high;
+ o.low = c.low;
+ o.close = c.close;
+ o.volume = c.volume;
+ o.is_closed = true;
+ out.append(o);
+ }
+ return out;
+}
+
+QString CandleDataFetcher::timeframe_to_broker_resolution(const QString& tf) {
+ if (tf == "1m") return QStringLiteral("1");
+ if (tf == "3m") return QStringLiteral("3");
+ if (tf == "5m") return QStringLiteral("5");
+ if (tf == "15m") return QStringLiteral("15");
+ if (tf == "30m") return QStringLiteral("30");
+ if (tf == "1h") return QStringLiteral("60");
+ if (tf == "4h") return QStringLiteral("240");
+ if (tf == "1d") return QStringLiteral("D");
+ return QStringLiteral("D");
+}
+
+void CandleDataFetcher::fetch(const QString& symbol, const QString& timeframe,
+ int lookback_days, DataSource source,
+ const QString& broker_id, const QString& account_id,
+ CandleCallback callback) {
+ if (source == DataSource::Broker ||
+ (source == DataSource::Auto && !broker_id.isEmpty())) {
+ fetch_from_broker(symbol, timeframe, lookback_days, broker_id, account_id,
+ [callback, symbol, timeframe, lookback_days, this](bool ok, const QVector<OhlcvCandle>& candles, const QString& err) {
+ if (ok && !candles.isEmpty()) {
+ callback(true, candles, {});
+ return;
+ }
+ LOG_WARN("CandleDataFetcher",
+ QString("Broker fetch failed for %1, falling back to yfinance: %2")
+ .arg(symbol, err));
+ fetch_from_yfinance({symbol}, timeframe, lookback_days,
+ [callback, symbol](const QHash<QString, QVector<OhlcvCandle>>& data, const QStringList& errors) {
+ if (data.contains(symbol)) {
+ callback(true, data[symbol], {});
+ } else {
+ callback(false, {}, errors.isEmpty() ? "No data" : errors.first());
+ }
+ });
+ });
+ return;
+ }
+
+ // YFinance or Auto without broker
+ fetch_from_yfinance({symbol}, timeframe, lookback_days,
+ [callback, symbol](const QHash<QString, QVector<OhlcvCandle>>& data, const QStringList& errors) {
+ if (data.contains(symbol)) {
+ callback(true, data[symbol], {});
+ } else {
+ callback(false, {}, errors.isEmpty() ? "No data" : errors.first());
+ }
+ });
+}
+
+void CandleDataFetcher::fetch_multi(const QStringList& symbols, const QString& timeframe,
+ int lookback_days, DataSource source,
+ const QString& broker_id, const QString& account_id,
+ MultiCandleCallback callback) {
+ if (source == DataSource::Broker ||
+ (source == DataSource::Auto && !broker_id.isEmpty())) {
+ QPointer<CandleDataFetcher> self = this;
+ auto results = std::make_shared<QHash<QString, QVector<OhlcvCandle>>>();
+ auto errors = std::make_shared<QStringList>();
+ auto remaining = std::make_shared<std::atomic<int>>(symbols.size());
+
+ for (const auto& sym : symbols) {
+ fetch_from_broker(sym, timeframe, lookback_days, broker_id, account_id,
+ [self, sym, results, errors, remaining, callback, symbols, timeframe, lookback_days]
+ (bool ok, const QVector<OhlcvCandle>& candles, const QString& err) {
+ if (ok && !candles.isEmpty()) {
+ results->insert(sym, candles);
+ } else {
+ errors->append(QString("%1: %2").arg(sym, err));
+ }
+ if (remaining->fetch_sub(1) == 1) {
+ if (!results->isEmpty()) {
+ callback(*results, *errors);
+ } else if (self) {
+ self->fetch_from_yfinance(symbols, timeframe, lookback_days, callback);
+ }
+ }
+ });
+ }
+ return;
+ }
+
+ fetch_from_yfinance(symbols, timeframe, lookback_days, callback);
+}
+
+void CandleDataFetcher::fetch_from_broker(const QString& symbol, const QString& timeframe,
+ int lookback_days, const QString& broker_id,
+ const QString& account_id, CandleCallback callback) {
+ QPointer<CandleDataFetcher> self = this;
+ QtConcurrent::run([self, symbol, timeframe, lookback_days, broker_id, account_id, callback]() {
+ auto* broker = trading::BrokerRegistry::instance().get(broker_id);
+ if (!broker) {
+ QMetaObject::invokeMethod(self, [callback]() {
+ callback(false, {}, QStringLiteral("Broker not found"));
+ }, Qt::QueuedConnection);
+ return;
+ }
+
+ auto creds = trading::AccountManager::instance().load_credentials(account_id);
+ if (creds.api_key.isEmpty()) {
+ QMetaObject::invokeMethod(self, [callback]() {
+ callback(false, {}, QStringLiteral("No credentials"));
+ }, Qt::QueuedConnection);
+ return;
+ }
+
+ QDateTime to = QDateTime::currentDateTime();
+ QDateTime from = to.addDays(-lookback_days);
+ QString resolution = timeframe_to_broker_resolution(timeframe);
+
+ auto result = broker->get_history(creds, symbol, resolution,
+ from.toString("yyyy-MM-dd"),
+ to.toString("yyyy-MM-dd"));
+
+ if (!self) return;
+ if (result.success) {
+ auto candles = broker_candles_to_ohlcv(result.data.value_or({}));
+ QMetaObject::invokeMethod(self, [callback, candles]() {
+ callback(true, candles, {});
+ }, Qt::QueuedConnection);
+ } else {
+ QMetaObject::invokeMethod(self, [callback, result]() {
+ callback(false, {}, result.error);
+ }, Qt::QueuedConnection);
+ }
+ });
+}
+
+void CandleDataFetcher::fetch_from_yfinance(const QStringList& symbols, const QString& timeframe,
+ int lookback_days, MultiCandleCallback callback) {
+ QJsonObject params;
+ params["symbols"] = QJsonArray::fromStringList(symbols);
+ params["timeframe"] = timeframe;
+ params["lookback_days"] = lookback_days;
+ auto json = QJsonDocument(params).toJson(QJsonDocument::Compact);
+
+ QPointer<CandleDataFetcher> self = this;
+ python::PythonRunner::instance().run(
+ QStringLiteral("algo_trading/fetch_candles.py"), {json},
+ [self, callback](python::PythonResult result) {
+ if (!self) return;
+
+ if (!result.success) {
+ QMetaObject::invokeMethod(self, [callback, result]() {
+ callback({}, {result.error});
+ }, Qt::QueuedConnection);
+ return;
+ }
+
+ auto doc = QJsonDocument::fromJson(
+ python::extract_json(result.output).toUtf8());
+ auto root = doc.object();
+
+ QHash<QString, QVector<OhlcvCandle>> data;
+ QStringList errors;
+
+ if (!root.value("success").toBool()) {
+ errors.append(root.value("error").toString());
+ } else {
+ auto symbols_data = root.value("data").toObject();
+ for (auto it = symbols_data.begin(); it != symbols_data.end(); ++it) {
+ QVector<OhlcvCandle> candles;
+ for (const auto& cv : it.value().toArray()) {
+ auto co = cv.toObject();
+ OhlcvCandle c;
+ c.open_time = static_cast<int64_t>(co.value("t").toDouble());
+ c.open = co.value("o").toDouble();
+ c.high = co.value("h").toDouble();
+ c.low = co.value("l").toDouble();
+ c.close = co.value("c").toDouble();
+ c.volume = co.value("v").toDouble();
+ c.is_closed = true;
+ candles.append(c);
+ }
+ data.insert(it.key(), candles);
+ }
+ }
+
+ QMetaObject::invokeMethod(self, [callback, data, errors]() {
+ callback(data, errors);
+ }, Qt::QueuedConnection);
+ });
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/CandleDataFetcher.h b/fincept-qt/src/algo_engine/CandleDataFetcher.h
new file mode 100644
index 000000000..225d9d78c
--- /dev/null
+++ b/fincept-qt/src/algo_engine/CandleDataFetcher.h
@@ -0,0 +1,61 @@
+// src/algo_engine/CandleDataFetcher.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "trading/TradingTypes.h"
+
+#include <QObject>
+#include <QString>
+#include <QVector>
+#include <functional>
+
+namespace fincept::algo {
+
+enum class DataSource { Broker, YFinance, Auto };
+
+inline QString data_source_to_string(DataSource s) {
+ switch (s) {
+ case DataSource::Broker: return QStringLiteral("Broker");
+ case DataSource::YFinance: return QStringLiteral("YFinance");
+ case DataSource::Auto: return QStringLiteral("Auto");
+ }
+ return QStringLiteral("Auto");
+}
+
+inline DataSource data_source_from_string(const QString& s) {
+ if (s == "Broker") return DataSource::Broker;
+ if (s == "YFinance") return DataSource::YFinance;
+ return DataSource::Auto;
+}
+
+using CandleCallback = std::function<void(bool success, const QVector<OhlcvCandle>& candles, const QString& error)>;
+using MultiCandleCallback = std::function<void(const QHash<QString, QVector<OhlcvCandle>>& data, const QStringList& errors)>;
+
+class CandleDataFetcher : public QObject {
+ Q_OBJECT
+public:
+ static CandleDataFetcher& instance();
+
+ void fetch(const QString& symbol, const QString& timeframe, int lookback_days,
+ DataSource source, const QString& broker_id, const QString& account_id,
+ CandleCallback callback);
+
+ void fetch_multi(const QStringList& symbols, const QString& timeframe, int lookback_days,
+ DataSource source, const QString& broker_id, const QString& account_id,
+ MultiCandleCallback callback);
+
+private:
+ CandleDataFetcher() = default;
+ Q_DISABLE_COPY(CandleDataFetcher)
+
+ void fetch_from_broker(const QString& symbol, const QString& timeframe, int lookback_days,
+ const QString& broker_id, const QString& account_id,
+ CandleCallback callback);
+
+ void fetch_from_yfinance(const QStringList& symbols, const QString& timeframe,
+ int lookback_days, MultiCandleCallback callback);
+
+ static QVector<OhlcvCandle> broker_candles_to_ohlcv(const QVector<fincept::trading::BrokerCandle>& src);
+ static QString timeframe_to_broker_resolution(const QString& tf);
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
new file mode 100644
index 000000000..afeed9182
--- /dev/null
+++ b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
@@ -0,0 +1,148 @@
+// src/algo_engine/ConditionEvaluator.cpp
+#include "algo_engine/ConditionEvaluator.h"
+
+#include <QJsonObject>
+
+namespace fincept::algo {
+
+using services::algo::ConditionDef;
+
+ConditionDef ConditionEvaluator::parse_condition(const QJsonObject& obj) {
+ ConditionDef c;
+ c.indicator = obj.value("indicator").toString();
+ c.params = obj.value("params").toObject();
+ c.field = obj.value("field").toString("value");
+ c.op = obj.value("operator").toString(">");
+ c.value = obj.value("value").toDouble(0);
+ c.compare_mode = obj.value("compare_mode").toString("value");
+ c.compare_indicator = obj.value("compare_indicator").toString();
+ c.compare_params = obj.value("compare_params").toObject();
+ c.compare_field = obj.value("compare_field").toString("value");
+ return c;
+}
+
+bool ConditionEvaluator::apply_comparison(double lhs, const QString& op, double rhs) {
+ if (op == ">") return lhs > rhs;
+ if (op == "<") return lhs < rhs;
+ if (op == ">=") return lhs >= rhs;
+ if (op == "<=") return lhs <= rhs;
+ if (op == "==") return std::abs(lhs - rhs) < 1e-8;
+ return false;
+}
+
+bool ConditionEvaluator::apply_crossing(double curr, double prev,
+ double target_curr, double target_prev,
+ const QString& op) {
+ if (op == "crosses_above")
+ return prev <= target_prev && curr > target_curr;
+ if (op == "crosses_below")
+ return prev >= target_prev && curr < target_curr;
+ return false;
+}
+
+bool ConditionEvaluator::apply_trend(const QVector<double>& /*values*/,
+ int /*count*/, const QString& /*op*/) {
+ // Simplified: compare last two values
+ // A more sophisticated version would check N consecutive bars
+ return false;
+}
+
+ConditionResult ConditionEvaluator::evaluate_single(
+ const ConditionDef& condition,
+ const QVector<OhlcvCandle>& candles) {
+
+ ConditionResult result;
+ result.indicator = condition.indicator;
+ result.field = condition.field;
+ result.op = condition.op;
+
+ auto ind_result = IndicatorEngine::compute(
+ condition.indicator, candles, condition.params, condition.field);
+
+ if (!ind_result.valid) {
+ result.error = ind_result.error;
+ return result;
+ }
+
+ double curr_val = ind_result.current.value(condition.field, 0);
+ double prev_val = ind_result.previous.value(condition.field, curr_val);
+ result.computed_value = curr_val;
+
+ if (condition.compare_mode == "indicator") {
+ auto cmp_result = IndicatorEngine::compute(
+ condition.compare_indicator, candles,
+ condition.compare_params, condition.compare_field);
+
+ if (!cmp_result.valid) {
+ result.error = cmp_result.error;
+ return result;
+ }
+
+ double target_curr = cmp_result.current.value(condition.compare_field, 0);
+ double target_prev = cmp_result.previous.value(condition.compare_field, target_curr);
+ result.target_value = target_curr;
+
+ if (condition.op == "crosses_above" || condition.op == "crosses_below") {
+ result.met = apply_crossing(curr_val, prev_val, target_curr, target_prev, condition.op);
+ } else if (condition.op == "rising" || condition.op == "falling") {
+ result.met = (condition.op == "rising") ? (curr_val > prev_val) : (curr_val < prev_val);
+ } else {
+ result.met = apply_comparison(curr_val, condition.op, target_curr);
+ }
+ } else {
+ result.target_value = condition.value;
+
+ if (condition.op == "crosses_above" || condition.op == "crosses_below") {
+ result.met = apply_crossing(curr_val, prev_val,
+ condition.value, condition.value, condition.op);
+ } else if (condition.op == "rising" || condition.op == "falling") {
+ result.met = (condition.op == "rising") ? (curr_val > prev_val) : (curr_val < prev_val);
+ } else {
+ result.met = apply_comparison(curr_val, condition.op, condition.value);
+ }
+ }
+
+ return result;
+}
+
+GroupEvalResult ConditionEvaluator::evaluate_group(
+ const QJsonArray& conditions_json,
+ const QString& logic,
+ const QVector<OhlcvCandle>& candles) {
+
+ GroupEvalResult group;
+ group.logic = logic;
+
+ if (conditions_json.isEmpty()) {
+ group.triggered = false;
+ return group;
+ }
+
+ bool is_and = (logic.toUpper() == "AND");
+ bool overall = is_and;
+
+ for (const auto& val : conditions_json) {
+ auto cond = parse_condition(val.toObject());
+ auto result = evaluate_single(cond, candles);
+ group.details.append(result);
+
+ if (is_and) {
+ overall = overall && result.met;
+ } else {
+ overall = overall || result.met;
+ }
+ }
+
+ // Reset to false for OR if first iteration set it wrong
+ if (!is_and && !conditions_json.isEmpty()) {
+ overall = false;
+ for (const auto& d : group.details) {
+ if (d.met) { overall = true; break; }
+ }
+ }
+
+ group.triggered = overall;
+ return group;
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/ConditionEvaluator.h b/fincept-qt/src/algo_engine/ConditionEvaluator.h
new file mode 100644
index 000000000..76d9ec5b2
--- /dev/null
+++ b/fincept-qt/src/algo_engine/ConditionEvaluator.h
@@ -0,0 +1,31 @@
+// src/algo_engine/ConditionEvaluator.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "algo_engine/IndicatorEngine.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QJsonArray>
+
+namespace fincept::algo {
+
+class ConditionEvaluator {
+public:
+ static ConditionResult evaluate_single(
+ const fincept::services::algo::ConditionDef& condition,
+ const QVector<OhlcvCandle>& candles);
+
+ static GroupEvalResult evaluate_group(
+ const QJsonArray& conditions_json,
+ const QString& logic,
+ const QVector<OhlcvCandle>& candles);
+
+private:
+ static fincept::services::algo::ConditionDef parse_condition(const QJsonObject& obj);
+ static bool apply_comparison(double lhs, const QString& op, double rhs);
+ static bool apply_crossing(double curr, double prev,
+ double target_curr, double target_prev,
+ const QString& op);
+ static bool apply_trend(const QVector<double>& values, int count, const QString& op);
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.cpp b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
new file mode 100644
index 000000000..271d32072
--- /dev/null
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
@@ -0,0 +1,345 @@
+// src/algo_engine/DeploymentRunner.cpp
+#include "algo_engine/DeploymentRunner.h"
+#include "algo_engine/ConditionEvaluator.h"
+#include "core/logging/Logger.h"
+#include "datahub/DataHub.h"
+#include "storage/sqlite/Database.h"
+
+using fincept::Database;
+#include "trading/BrokerTopic.h"
+#include "trading/TradingTypes.h"
+
+#include <QDateTime>
+#include <QSqlQuery>
+#include <QUuid>
+#include <QVariant>
+
+namespace fincept::algo {
+
+DeploymentRunner::DeploymentRunner(const services::algo::AlgoDeployment& deployment,
+ const services::algo::AlgoStrategy& strategy,
+ QObject* parent)
+ : QObject(parent)
+ , deployment_(deployment)
+ , strategy_(strategy)
+ , timeframe_(timeframe_from_string(deployment.timeframe.isEmpty() ? strategy.timeframe : deployment.timeframe)) {
+
+ aggregator_ = std::make_unique<CandleAggregator>(deployment.symbol, timeframe_, 200, this);
+ connect(aggregator_.get(), &CandleAggregator::candle_closed,
+ this, &DeploymentRunner::on_candle_closed);
+
+ position_mgr_ = std::make_unique<PositionManager>(
+ deployment.id,
+ strategy.stop_loss, strategy.take_profit, strategy.trailing_stop,
+ deployment.max_order_value, deployment.max_daily_loss);
+
+ heartbeat_timer_ = new QTimer(this);
+ heartbeat_timer_->setInterval(5000);
+ connect(heartbeat_timer_, &QTimer::timeout, this, &DeploymentRunner::on_heartbeat);
+}
+
+DeploymentRunner::~DeploymentRunner() {
+ if (running_.load())
+ stop();
+}
+
+void DeploymentRunner::start() {
+ if (running_.load()) return;
+
+ running_ = true;
+ paused_ = false;
+ last_heartbeat_ms_ = QDateTime::currentMSecsSinceEpoch();
+
+ subscribe_tick_topic();
+ heartbeat_timer_->start();
+
+ update_deployment_status(QStringLiteral("running"));
+ emit status_changed(deployment_.id, QStringLiteral("running"));
+ LOG_INFO("AlgoEngine", QString("Deployment %1 started: %2 on %3")
+ .arg(deployment_.id, strategy_.name, deployment_.symbol));
+}
+
+void DeploymentRunner::pause() {
+ paused_ = true;
+ emit status_changed(deployment_.id, QStringLiteral("paused"));
+ LOG_INFO("AlgoEngine", QString("Deployment %1 paused").arg(deployment_.id));
+}
+
+void DeploymentRunner::resume() {
+ paused_ = false;
+ emit status_changed(deployment_.id, QStringLiteral("running"));
+ LOG_INFO("AlgoEngine", QString("Deployment %1 resumed").arg(deployment_.id));
+}
+
+void DeploymentRunner::stop() {
+ if (!running_.load()) return;
+
+ running_ = false;
+ paused_ = false;
+ heartbeat_timer_->stop();
+ unsubscribe_tick_topic();
+ persist_metrics();
+ update_deployment_status(QStringLiteral("stopped"));
+ emit status_changed(deployment_.id, QStringLiteral("stopped"));
+ LOG_INFO("AlgoEngine", QString("Deployment %1 stopped").arg(deployment_.id));
+}
+
+void DeploymentRunner::subscribe_tick_topic() {
+ const QString topic = fincept::trading::broker_topic(
+ deployment_.broker_id, deployment_.broker_account_id,
+ QStringLiteral("ticks"), deployment_.symbol);
+
+ auto& hub = fincept::datahub::DataHub::instance();
+ tick_connection_ = hub.subscribe(this, topic,
+ [this](const QVariant& v) { on_tick_data(v); });
+}
+
+void DeploymentRunner::unsubscribe_tick_topic() {
+ if (tick_connection_) {
+ QObject::disconnect(tick_connection_);
+ tick_connection_ = {};
+ }
+ fincept::datahub::DataHub::instance().unsubscribe(this);
+}
+
+void DeploymentRunner::on_tick_data(const QVariant& data) {
+ if (!running_.load() || paused_.load()) return;
+
+ last_heartbeat_ms_ = QDateTime::currentMSecsSinceEpoch();
+
+ double price = 0;
+ double volume = 0;
+ int64_t timestamp = QDateTime::currentMSecsSinceEpoch();
+
+ if (data.canConvert<fincept::trading::BrokerQuote>()) {
+ auto quote = data.value<fincept::trading::BrokerQuote>();
+ price = quote.ltp;
+ volume = quote.volume;
+ timestamp = quote.timestamp > 0 ? quote.timestamp : timestamp;
+ } else if (data.canConvert<QVariantMap>()) {
+ auto map = data.toMap();
+ price = map.value("ltp", map.value("price")).toDouble();
+ volume = map.value("volume").toDouble();
+ } else {
+ return;
+ }
+
+ if (price <= 0) return;
+
+ position_mgr_->update_price(price);
+
+ auto risk_signal = position_mgr_->check_risk(price);
+ if (risk_signal) {
+ risk_signal->account_id = deployment_.broker_account_id;
+ risk_signal->symbol = deployment_.symbol;
+ risk_signal->exchange = deployment_.exchange;
+ risk_signal->product_type = deployment_.product_type;
+ emit_order_signal(*risk_signal);
+ }
+
+ aggregator_->on_tick(price, volume, timestamp);
+}
+
+void DeploymentRunner::on_candle_closed(const OhlcvCandle& /*candle*/) {
+ if (!running_.load() || paused_.load()) return;
+ if (position_mgr_->is_paused()) return;
+
+ auto candles = aggregator_->closed_candles();
+ if (candles.size() < 20) return;
+
+ if (position_mgr_->has_position()) {
+ evaluate_exit(candles);
+ } else {
+ evaluate_entry(candles);
+ }
+
+ auto m = position_mgr_->metrics();
+ m.last_signal_time = QDateTime::currentMSecsSinceEpoch();
+ emit metrics_updated(deployment_.id, m);
+}
+
+void DeploymentRunner::evaluate_entry(const QVector<OhlcvCandle>& candles) {
+ auto result = ConditionEvaluator::evaluate_group(
+ strategy_.entry_conditions, strategy_.entry_logic, candles);
+
+ if (!result.triggered) return;
+
+ AlgoOrderSignal signal;
+ signal.deployment_id = deployment_.id;
+ signal.account_id = deployment_.broker_account_id;
+ signal.symbol = deployment_.symbol;
+ signal.exchange = deployment_.exchange;
+ signal.product_type = deployment_.product_type;
+ signal.side = deployment_.entry_side;
+ signal.quantity = deployment_.quantity;
+ signal.order_type = "MARKET";
+ signal.reason = "entry_signal";
+
+ if (!position_mgr_->validate_order_value(signal.quantity, candles.last().close)) {
+ LOG_WARN("AlgoEngine", QString("Deployment %1: order value exceeds limit, skipping entry")
+ .arg(deployment_.id));
+ return;
+ }
+
+ emit_order_signal(signal);
+}
+
+void DeploymentRunner::evaluate_exit(const QVector<OhlcvCandle>& candles) {
+ auto result = ConditionEvaluator::evaluate_group(
+ strategy_.exit_conditions, strategy_.exit_logic, candles);
+
+ if (!result.triggered) return;
+
+ auto pos = position_mgr_->position();
+ AlgoOrderSignal signal;
+ signal.deployment_id = deployment_.id;
+ signal.account_id = deployment_.broker_account_id;
+ signal.symbol = deployment_.symbol;
+ signal.exchange = deployment_.exchange;
+ signal.product_type = deployment_.product_type;
+ signal.side = (pos.side == PositionSide::Long) ? "SELL" : "BUY";
+ signal.quantity = pos.quantity;
+ signal.order_type = "MARKET";
+ signal.reason = "exit_signal";
+
+ emit_order_signal(signal);
+}
+
+void DeploymentRunner::emit_order_signal(const AlgoOrderSignal& signal) {
+ PendingOrder pending;
+ pending.signal = signal;
+ pending.submitted_ms = QDateTime::currentMSecsSinceEpoch();
+ pending_orders_.append(pending);
+
+ emit order_requested(signal);
+ LOG_INFO("AlgoEngine", QString("Deployment %1: %2 %3 %4 @ MARKET (%5)")
+ .arg(deployment_.id, signal.side,
+ QString::number(signal.quantity), signal.symbol, signal.reason));
+}
+
+void DeploymentRunner::on_order_filled(const QString& broker_order_id,
+ double fill_price, double fill_qty) {
+ int idx = -1;
+ for (int i = 0; i < pending_orders_.size(); ++i) {
+ if (pending_orders_[i].broker_order_id == broker_order_id ||
+ pending_orders_[i].broker_order_id.isEmpty()) {
+ idx = i;
+ break;
+ }
+ }
+ if (idx < 0) return;
+
+ auto pending = pending_orders_.takeAt(idx);
+ int64_t now = QDateTime::currentMSecsSinceEpoch();
+
+ bool is_entry = (pending.signal.reason == "entry_signal");
+ double pnl = 0;
+
+ if (is_entry) {
+ PositionSide side = (pending.signal.side == "BUY") ? PositionSide::Long : PositionSide::Short;
+ position_mgr_->record_entry(side, fill_qty, fill_price, now);
+ } else {
+ pnl = position_mgr_->record_exit(fill_qty, fill_price, now);
+ }
+
+ AlgoTradeRecord trade;
+ trade.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ trade.deployment_id = deployment_.id;
+ trade.symbol = deployment_.symbol;
+ trade.side = pending.signal.side;
+ trade.quantity = fill_qty;
+ trade.price = fill_price;
+ trade.pnl = pnl;
+ trade.reason = pending.signal.reason;
+ trade.timestamp = now;
+ trade.broker_order_id = broker_order_id;
+ trade.latency_ms = now - pending.submitted_ms;
+
+ persist_trade(trade);
+ emit trade_executed(trade);
+ emit metrics_updated(deployment_.id, position_mgr_->metrics());
+}
+
+void DeploymentRunner::on_order_rejected(const QString& /*broker_order_id*/,
+ const QString& reason) {
+ if (!pending_orders_.isEmpty())
+ pending_orders_.removeFirst();
+ LOG_ERROR("AlgoEngine", QString("Deployment %1: order rejected: %2")
+ .arg(deployment_.id, reason));
+}
+
+void DeploymentRunner::on_heartbeat() {
+ if (!running_.load()) return;
+ int64_t now = QDateTime::currentMSecsSinceEpoch();
+ if (now - last_heartbeat_ms_ > 30000) {
+ LOG_ERROR("AlgoEngine", QString("Deployment %1: no tick data for 30s, marking error")
+ .arg(deployment_.id));
+ update_deployment_status(QStringLiteral("error"));
+ emit status_changed(deployment_.id, QStringLiteral("error"));
+ emit error_occurred(deployment_.id, QStringLiteral("No tick data received for 30 seconds"));
+ }
+}
+
+void DeploymentRunner::persist_trade(const AlgoTradeRecord& trade) {
+ auto db = Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral(
+ "INSERT INTO algo_trades (id, deployment_id, symbol, side, quantity, price, pnl, "
+ "reason, broker_order_id, latency_ms, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))"));
+ q.addBindValue(trade.id);
+ q.addBindValue(trade.deployment_id);
+ q.addBindValue(trade.symbol);
+ q.addBindValue(trade.side);
+ q.addBindValue(trade.quantity);
+ q.addBindValue(trade.price);
+ q.addBindValue(trade.pnl);
+ q.addBindValue(trade.reason);
+ q.addBindValue(trade.broker_order_id);
+ q.addBindValue(trade.latency_ms);
+ if (!q.exec())
+ LOG_ERROR("AlgoEngine", QString("Failed to persist trade: %1").arg(q.lastError().text()));
+}
+
+void DeploymentRunner::persist_metrics() {
+ auto m = position_mgr_->metrics();
+ auto db = Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral(
+ "INSERT OR REPLACE INTO algo_metrics (deployment_id, total_pnl, unrealized_pnl, "
+ "total_trades, win_rate, max_drawdown, current_position_qty, current_position_side, "
+ "current_position_entry, current_price, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))"));
+ q.addBindValue(deployment_.id);
+ q.addBindValue(m.total_pnl);
+ q.addBindValue(m.unrealized_pnl);
+ q.addBindValue(m.total_trades);
+ q.addBindValue(m.win_rate);
+ q.addBindValue(m.max_drawdown);
+ q.addBindValue(m.current_position_qty);
+ q.addBindValue(m.current_position_side);
+ q.addBindValue(m.current_position_entry);
+ q.addBindValue(m.current_price);
+ if (!q.exec())
+ LOG_ERROR("AlgoEngine", QString("Failed to persist metrics: %1").arg(q.lastError().text()));
+}
+
+void DeploymentRunner::update_deployment_status(const QString& status) {
+ auto db = Database::instance().connection();
+ QSqlQuery q(db);
+ q.prepare(QStringLiteral(
+ "UPDATE algo_deployments SET status = ?, updated_at = datetime('now') WHERE id = ?"));
+ q.addBindValue(status);
+ q.addBindValue(deployment_.id);
+ q.exec();
+}
+
+AlgoMetrics DeploymentRunner::metrics() const {
+ return position_mgr_->metrics();
+}
+
+AlgoPosition DeploymentRunner::position() const {
+ return position_mgr_->position();
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.h b/fincept-qt/src/algo_engine/DeploymentRunner.h
new file mode 100644
index 000000000..c326ccb49
--- /dev/null
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.h
@@ -0,0 +1,82 @@
+// src/algo_engine/DeploymentRunner.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+#include "algo_engine/CandleAggregator.h"
+#include "algo_engine/PositionManager.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QObject>
+#include <QTimer>
+
+#include <atomic>
+#include <memory>
+
+namespace fincept::algo {
+
+class DeploymentRunner : public QObject {
+ Q_OBJECT
+public:
+ explicit DeploymentRunner(const fincept::services::algo::AlgoDeployment& deployment,
+ const fincept::services::algo::AlgoStrategy& strategy,
+ QObject* parent = nullptr);
+ ~DeploymentRunner() override;
+
+ void start();
+ void pause();
+ void resume();
+ void stop();
+ bool is_running() const { return running_.load(); }
+ bool is_paused() const { return paused_.load(); }
+ QString deployment_id() const { return deployment_.id; }
+
+ AlgoMetrics metrics() const;
+ AlgoPosition position() const;
+
+signals:
+ void trade_executed(const fincept::algo::AlgoTradeRecord& trade);
+ void metrics_updated(const QString& deployment_id, const fincept::algo::AlgoMetrics& metrics);
+ void status_changed(const QString& deployment_id, const QString& status);
+ void order_requested(const fincept::algo::AlgoOrderSignal& signal);
+ void error_occurred(const QString& deployment_id, const QString& error);
+
+public slots:
+ void on_order_filled(const QString& broker_order_id, double fill_price, double fill_qty);
+ void on_order_rejected(const QString& broker_order_id, const QString& reason);
+
+private slots:
+ void on_candle_closed(const fincept::algo::OhlcvCandle& candle);
+ void on_tick_data(const QVariant& data);
+ void on_heartbeat();
+
+private:
+ void subscribe_tick_topic();
+ void unsubscribe_tick_topic();
+ void evaluate_entry(const QVector<OhlcvCandle>& candles);
+ void evaluate_exit(const QVector<OhlcvCandle>& candles);
+ void emit_order_signal(const AlgoOrderSignal& signal);
+ void persist_trade(const AlgoTradeRecord& trade);
+ void persist_metrics();
+ void update_deployment_status(const QString& status);
+
+ fincept::services::algo::AlgoDeployment deployment_;
+ fincept::services::algo::AlgoStrategy strategy_;
+ Timeframe timeframe_;
+
+ std::unique_ptr<CandleAggregator> aggregator_;
+ std::unique_ptr<PositionManager> position_mgr_;
+
+ std::atomic<bool> running_{false};
+ std::atomic<bool> paused_{false};
+ QMetaObject::Connection tick_connection_;
+ QTimer* heartbeat_timer_ = nullptr;
+ int64_t last_heartbeat_ms_ = 0;
+
+ struct PendingOrder {
+ QString broker_order_id;
+ AlgoOrderSignal signal;
+ int64_t submitted_ms = 0;
+ };
+ QVector<PendingOrder> pending_orders_;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/IndicatorEngine.cpp b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
new file mode 100644
index 000000000..2f2ce4ac2
--- /dev/null
+++ b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
@@ -0,0 +1,804 @@
+// src/algo_engine/IndicatorEngine.cpp
+#include "algo_engine/IndicatorEngine.h"
+
+#include <algorithm>
+#include <cmath>
+#include <numeric>
+
+namespace fincept::algo {
+
+// ── Helpers ─────────────────────────────────────────────────────────────────
+
+void IndicatorEngine::extract_arrays(const QVector<OhlcvCandle>& candles,
+ QVector<double>& open, QVector<double>& high,
+ QVector<double>& low, QVector<double>& close,
+ QVector<double>& volume) {
+ const int n = candles.size();
+ open.resize(n);
+ high.resize(n);
+ low.resize(n);
+ close.resize(n);
+ volume.resize(n);
+ for (int i = 0; i < n; ++i) {
+ open[i] = candles[i].open;
+ high[i] = candles[i].high;
+ low[i] = candles[i].low;
+ close[i] = candles[i].close;
+ volume[i] = candles[i].volume;
+ }
+}
+
+QVector<double> IndicatorEngine::sma_series(const QVector<double>& src, int period) {
+ const int n = src.size();
+ QVector<double> out(n, std::numeric_limits<double>::quiet_NaN());
+ if (n < period) return out;
+ double sum = 0;
+ for (int i = 0; i < period; ++i)
+ sum += src[i];
+ out[period - 1] = sum / period;
+ for (int i = period; i < n; ++i) {
+ sum += src[i] - src[i - period];
+ out[i] = sum / period;
+ }
+ return out;
+}
+
+QVector<double> IndicatorEngine::ema_series(const QVector<double>& src, int period) {
+ const int n = src.size();
+ QVector<double> out(n, std::numeric_limits<double>::quiet_NaN());
+ if (n < period) return out;
+ double sum = 0;
+ for (int i = 0; i < period; ++i)
+ sum += src[i];
+ out[period - 1] = sum / period;
+ double mult = 2.0 / (period + 1);
+ for (int i = period; i < n; ++i)
+ out[i] = (src[i] - out[i - 1]) * mult + out[i - 1];
+ return out;
+}
+
+QVector<double> IndicatorEngine::true_range_series(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close) {
+ const int n = high.size();
+ QVector<double> tr(n, 0);
+ if (n > 0) tr[0] = high[0] - low[0];
+ for (int i = 1; i < n; ++i) {
+ double hl = high[i] - low[i];
+ double hc = std::abs(high[i] - close[i - 1]);
+ double lc = std::abs(low[i] - close[i - 1]);
+ tr[i] = std::max({hl, hc, lc});
+ }
+ return tr;
+}
+
+static IndicatorResult make_result(double curr, double prev) {
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("value")] = curr;
+ r.previous[QStringLiteral("value")] = prev;
+ return r;
+}
+
+static IndicatorResult make_error(const QString& msg) {
+ IndicatorResult r;
+ r.error = msg;
+ return r;
+}
+
+// ── Dispatch ────────────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute(const QString& name,
+ const QVector<OhlcvCandle>& candles,
+ const QJsonObject& params,
+ const QString& /*field*/) {
+ if (candles.size() < 2)
+ return make_error(QStringLiteral("Insufficient data"));
+
+ // Stock attributes
+ if (name == "CLOSE" || name == "OPEN" || name == "HIGH" ||
+ name == "LOW" || name == "VOLUME" || name == "VWAP")
+ return compute_stock_attr(candles, name);
+
+ QVector<double> open, high, low, close, vol;
+ extract_arrays(candles, open, high, low, close, vol);
+
+ int period = params.value("period").toInt(14);
+
+ // Moving averages
+ if (name == "SMA") return compute_sma(close, period);
+ if (name == "EMA") return compute_ema(close, period);
+ if (name == "WMA") return compute_wma(close, period);
+ if (name == "DEMA") return compute_dema(close, period);
+ if (name == "TEMA") return compute_tema(close, period);
+
+ // Momentum
+ if (name == "RSI") return compute_rsi(close, period);
+ if (name == "MACD") {
+ int fast = params.value("fast").toInt(12);
+ int slow = params.value("slow").toInt(26);
+ int sig = params.value("signal").toInt(9);
+ return compute_macd(close, fast, slow, sig);
+ }
+ if (name == "STOCHASTIC") {
+ int k = params.value("k_period").toInt(14);
+ int d = params.value("d_period").toInt(3);
+ return compute_stochastic(high, low, close, k, d);
+ }
+ if (name == "CCI") return compute_cci(high, low, close, period);
+ if (name == "WILLIAMS_R") return compute_williams_r(high, low, close, period);
+ if (name == "MFI") return compute_mfi(high, low, close, vol, period);
+ if (name == "ROC") return compute_roc(close, period);
+
+ // Trend
+ if (name == "ADX") return compute_adx(high, low, close, period);
+ if (name == "SUPERTREND") {
+ double mult = params.value("multiplier").toDouble(3.0);
+ return compute_supertrend(high, low, close, period, mult);
+ }
+ if (name == "AROON") return compute_aroon(high, low, period);
+ if (name == "ICHIMOKU") {
+ int tenkan = params.value("tenkan").toInt(9);
+ int kijun = params.value("kijun").toInt(26);
+ int senkou = params.value("senkou").toInt(52);
+ return compute_ichimoku(high, low, tenkan, kijun, senkou);
+ }
+
+ // Volatility
+ if (name == "ATR") return compute_atr(high, low, close, period);
+ if (name == "BOLLINGER") {
+ double sd = params.value("std_dev").toDouble(2.0);
+ return compute_bollinger(close, period, sd);
+ }
+ if (name == "KELTNER") {
+ double mult = params.value("multiplier").toDouble(1.5);
+ return compute_keltner(high, low, close, period, mult);
+ }
+ if (name == "DONCHIAN") return compute_donchian(high, low, period);
+
+ // Volume
+ if (name == "OBV") return compute_obv(close, vol);
+ if (name == "CMF") return compute_cmf(high, low, close, vol, period);
+
+ return make_error(QStringLiteral("Unknown indicator: ") + name);
+}
+
+// ── Stock attributes ────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute_stock_attr(const QVector<OhlcvCandle>& candles,
+ const QString& attr) {
+ const auto& curr = candles.last();
+ const auto& prev = candles[candles.size() - 2];
+ IndicatorResult r;
+ r.valid = true;
+
+ double cv = 0, pv = 0;
+ if (attr == "CLOSE") { cv = curr.close; pv = prev.close; }
+ else if (attr == "OPEN") { cv = curr.open; pv = prev.open; }
+ else if (attr == "HIGH") { cv = curr.high; pv = prev.high; }
+ else if (attr == "LOW") { cv = curr.low; pv = prev.low; }
+ else if (attr == "VOLUME") { cv = curr.volume; pv = prev.volume; }
+ else if (attr == "VWAP") {
+ auto vwap = [](const OhlcvCandle& c) {
+ return c.volume > 0 ? (c.high + c.low + c.close) / 3.0 : c.close;
+ };
+ cv = vwap(curr);
+ pv = vwap(prev);
+ }
+ r.current[QStringLiteral("value")] = cv;
+ r.previous[QStringLiteral("value")] = pv;
+ return r;
+}
+
+// ── Moving Averages ─────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute_sma(const QVector<double>& src, int period) {
+ auto s = sma_series(src, period);
+ int n = s.size();
+ if (n < 2 || std::isnan(s[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for SMA"));
+ double prev = (n >= 2 && !std::isnan(s[n - 2])) ? s[n - 2] : s[n - 1];
+ return make_result(s[n - 1], prev);
+}
+
+IndicatorResult IndicatorEngine::compute_ema(const QVector<double>& src, int period) {
+ auto s = ema_series(src, period);
+ int n = s.size();
+ if (n < 2 || std::isnan(s[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for EMA"));
+ double prev = (n >= 2 && !std::isnan(s[n - 2])) ? s[n - 2] : s[n - 1];
+ return make_result(s[n - 1], prev);
+}
+
+IndicatorResult IndicatorEngine::compute_wma(const QVector<double>& src, int period) {
+ int n = src.size();
+ if (n < period)
+ return make_error(QStringLiteral("Insufficient data for WMA"));
+ double denom = period * (period + 1) / 2.0;
+ auto calc = [&](int end) {
+ double sum = 0;
+ for (int i = 0; i < period; ++i)
+ sum += src[end - period + 1 + i] * (i + 1);
+ return sum / denom;
+ };
+ double curr = calc(n - 1);
+ double prev = (n >= period + 1) ? calc(n - 2) : curr;
+ return make_result(curr, prev);
+}
+
+IndicatorResult IndicatorEngine::compute_dema(const QVector<double>& src, int period) {
+ auto e1 = ema_series(src, period);
+ auto e2 = ema_series(e1, period);
+ int n = e2.size();
+ if (n < 1 || std::isnan(e2[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for DEMA"));
+ double curr = 2.0 * e1[n - 1] - e2[n - 1];
+ double prev = curr;
+ if (n >= 2 && !std::isnan(e2[n - 2]))
+ prev = 2.0 * e1[n - 2] - e2[n - 2];
+ return make_result(curr, prev);
+}
+
+IndicatorResult IndicatorEngine::compute_tema(const QVector<double>& src, int period) {
+ auto e1 = ema_series(src, period);
+ auto e2 = ema_series(e1, period);
+ auto e3 = ema_series(e2, period);
+ int n = e3.size();
+ if (n < 1 || std::isnan(e3[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for TEMA"));
+ double curr = 3.0 * e1[n - 1] - 3.0 * e2[n - 1] + e3[n - 1];
+ double prev = curr;
+ if (n >= 2 && !std::isnan(e3[n - 2]))
+ prev = 3.0 * e1[n - 2] - 3.0 * e2[n - 2] + e3[n - 2];
+ return make_result(curr, prev);
+}
+
+// ── Momentum ────────────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute_rsi(const QVector<double>& close, int period) {
+ int n = close.size();
+ if (n < period + 1)
+ return make_error(QStringLiteral("Insufficient data for RSI"));
+
+ QVector<double> gains(n, 0), losses(n, 0);
+ for (int i = 1; i < n; ++i) {
+ double diff = close[i] - close[i - 1];
+ if (diff > 0) gains[i] = diff;
+ else losses[i] = -diff;
+ }
+
+ double avg_gain = 0, avg_loss = 0;
+ for (int i = 1; i <= period; ++i) {
+ avg_gain += gains[i];
+ avg_loss += losses[i];
+ }
+ avg_gain /= period;
+ avg_loss /= period;
+
+ QVector<double> rsi_vals(n, std::numeric_limits<double>::quiet_NaN());
+ auto calc_rsi = [](double ag, double al) -> double {
+ if (al < 1e-10) return 100.0;
+ return 100.0 - 100.0 / (1.0 + ag / al);
+ };
+ rsi_vals[period] = calc_rsi(avg_gain, avg_loss);
+
+ for (int i = period + 1; i < n; ++i) {
+ avg_gain = (avg_gain * (period - 1) + gains[i]) / period;
+ avg_loss = (avg_loss * (period - 1) + losses[i]) / period;
+ rsi_vals[i] = calc_rsi(avg_gain, avg_loss);
+ }
+
+ double prev = (n >= 2 && !std::isnan(rsi_vals[n - 2])) ? rsi_vals[n - 2] : rsi_vals[n - 1];
+ return make_result(rsi_vals[n - 1], prev);
+}
+
+IndicatorResult IndicatorEngine::compute_macd(const QVector<double>& close,
+ int fast, int slow, int signal_period) {
+ auto ema_fast = ema_series(close, fast);
+ auto ema_slow = ema_series(close, slow);
+ int n = close.size();
+
+ QVector<double> macd_line(n, std::numeric_limits<double>::quiet_NaN());
+ for (int i = 0; i < n; ++i) {
+ if (!std::isnan(ema_fast[i]) && !std::isnan(ema_slow[i]))
+ macd_line[i] = ema_fast[i] - ema_slow[i];
+ }
+
+ auto signal_line = ema_series(macd_line, signal_period);
+
+ if (std::isnan(macd_line[n - 1]) || std::isnan(signal_line[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for MACD"));
+
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("line")] = macd_line[n - 1];
+ r.current[QStringLiteral("signal_line")] = signal_line[n - 1];
+ r.current[QStringLiteral("histogram")] = macd_line[n - 1] - signal_line[n - 1];
+ if (n >= 2 && !std::isnan(macd_line[n - 2]) && !std::isnan(signal_line[n - 2])) {
+ r.previous[QStringLiteral("line")] = macd_line[n - 2];
+ r.previous[QStringLiteral("signal_line")] = signal_line[n - 2];
+ r.previous[QStringLiteral("histogram")] = macd_line[n - 2] - signal_line[n - 2];
+ }
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_stochastic(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ int k_period, int d_period) {
+ int n = close.size();
+ if (n < k_period)
+ return make_error(QStringLiteral("Insufficient data for Stochastic"));
+
+ QVector<double> k_vals(n, std::numeric_limits<double>::quiet_NaN());
+ for (int i = k_period - 1; i < n; ++i) {
+ double hh = high[i], ll = low[i];
+ for (int j = 1; j < k_period; ++j) {
+ hh = std::max(hh, high[i - j]);
+ ll = std::min(ll, low[i - j]);
+ }
+ double range = hh - ll;
+ k_vals[i] = range > 1e-10 ? (close[i] - ll) / range * 100.0 : 50.0;
+ }
+
+ auto d_vals = sma_series(k_vals, d_period);
+
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("k")] = k_vals[n - 1];
+ r.current[QStringLiteral("d")] = std::isnan(d_vals[n - 1]) ? k_vals[n - 1] : d_vals[n - 1];
+ if (n >= 2 && !std::isnan(k_vals[n - 2])) {
+ r.previous[QStringLiteral("k")] = k_vals[n - 2];
+ r.previous[QStringLiteral("d")] = std::isnan(d_vals[n - 2]) ? k_vals[n - 2] : d_vals[n - 2];
+ }
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_cci(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period) {
+ int n = close.size();
+ if (n < period)
+ return make_error(QStringLiteral("Insufficient data for CCI"));
+
+ QVector<double> tp(n);
+ for (int i = 0; i < n; ++i)
+ tp[i] = (high[i] + low[i] + close[i]) / 3.0;
+
+ auto sma = sma_series(tp, period);
+
+ auto calc_cci = [&](int idx) -> double {
+ if (std::isnan(sma[idx])) return 0;
+ double mean_dev = 0;
+ for (int j = 0; j < period; ++j)
+ mean_dev += std::abs(tp[idx - j] - sma[idx]);
+ mean_dev /= period;
+ return mean_dev > 1e-10 ? (tp[idx] - sma[idx]) / (0.015 * mean_dev) : 0;
+ };
+
+ double curr = calc_cci(n - 1);
+ double prev = (n >= period + 1) ? calc_cci(n - 2) : curr;
+ return make_result(curr, prev);
+}
+
+IndicatorResult IndicatorEngine::compute_williams_r(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period) {
+ int n = close.size();
+ if (n < period)
+ return make_error(QStringLiteral("Insufficient data for Williams %R"));
+
+ auto calc = [&](int idx) -> double {
+ double hh = high[idx], ll = low[idx];
+ for (int j = 1; j < period; ++j) {
+ hh = std::max(hh, high[idx - j]);
+ ll = std::min(ll, low[idx - j]);
+ }
+ double range = hh - ll;
+ return range > 1e-10 ? (hh - close[idx]) / range * -100.0 : -50.0;
+ };
+
+ double curr = calc(n - 1);
+ double prev = (n >= period + 1) ? calc(n - 2) : curr;
+ return make_result(curr, prev);
+}
+
+IndicatorResult IndicatorEngine::compute_mfi(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ const QVector<double>& volume, int period) {
+ int n = close.size();
+ if (n < period + 1)
+ return make_error(QStringLiteral("Insufficient data for MFI"));
+
+ QVector<double> tp(n);
+ for (int i = 0; i < n; ++i)
+ tp[i] = (high[i] + low[i] + close[i]) / 3.0;
+
+ auto calc = [&](int end) -> double {
+ double pos = 0, neg = 0;
+ for (int i = end - period + 1; i <= end; ++i) {
+ double mf = tp[i] * volume[i];
+ if (tp[i] > tp[i - 1]) pos += mf;
+ else if (tp[i] < tp[i - 1]) neg += mf;
+ }
+ return neg > 1e-10 ? 100.0 - 100.0 / (1.0 + pos / neg) : 100.0;
+ };
+
+ double curr = calc(n - 1);
+ double prev = (n >= period + 2) ? calc(n - 2) : curr;
+ return make_result(curr, prev);
+}
+
+IndicatorResult IndicatorEngine::compute_roc(const QVector<double>& close, int period) {
+ int n = close.size();
+ if (n <= period)
+ return make_error(QStringLiteral("Insufficient data for ROC"));
+ double curr = (close[n - 1] - close[n - 1 - period]) / close[n - 1 - period] * 100.0;
+ double prev = curr;
+ if (n > period + 1)
+ prev = (close[n - 2] - close[n - 2 - period]) / close[n - 2 - period] * 100.0;
+ return make_result(curr, prev);
+}
+
+// ── Trend ───────────────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute_adx(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period) {
+ int n = close.size();
+ if (n < period * 2 + 1)
+ return make_error(QStringLiteral("Insufficient data for ADX"));
+
+ auto tr = true_range_series(high, low, close);
+ QVector<double> plus_dm(n, 0), minus_dm(n, 0);
+ for (int i = 1; i < n; ++i) {
+ double up = high[i] - high[i - 1];
+ double down = low[i - 1] - low[i];
+ if (up > down && up > 0) plus_dm[i] = up;
+ if (down > up && down > 0) minus_dm[i] = down;
+ }
+
+ // Wilder's smoothing
+ double atr_smooth = 0, plus_smooth = 0, minus_smooth = 0;
+ for (int i = 1; i <= period; ++i) {
+ atr_smooth += tr[i];
+ plus_smooth += plus_dm[i];
+ minus_smooth += minus_dm[i];
+ }
+
+ QVector<double> dx_vals;
+ auto calc_dx = [&]() -> double {
+ double pdi = atr_smooth > 1e-10 ? plus_smooth / atr_smooth * 100.0 : 0;
+ double mdi = atr_smooth > 1e-10 ? minus_smooth / atr_smooth * 100.0 : 0;
+ double sum = pdi + mdi;
+ return sum > 1e-10 ? std::abs(pdi - mdi) / sum * 100.0 : 0;
+ };
+
+ dx_vals.append(calc_dx());
+ for (int i = period + 1; i < n; ++i) {
+ atr_smooth = atr_smooth - atr_smooth / period + tr[i];
+ plus_smooth = plus_smooth - plus_smooth / period + plus_dm[i];
+ minus_smooth = minus_smooth - minus_smooth / period + minus_dm[i];
+ dx_vals.append(calc_dx());
+ }
+
+ if (dx_vals.size() < period)
+ return make_error(QStringLiteral("Insufficient data for ADX"));
+
+ double adx = 0;
+ for (int i = 0; i < period; ++i)
+ adx += dx_vals[i];
+ adx /= period;
+
+ for (int i = period; i < dx_vals.size(); ++i)
+ adx = (adx * (period - 1) + dx_vals[i]) / period;
+
+ double prev_adx = adx;
+ if (dx_vals.size() > period) {
+ double adx2 = 0;
+ for (int i = 0; i < period; ++i)
+ adx2 += dx_vals[i];
+ adx2 /= period;
+ for (int i = period; i < dx_vals.size() - 1; ++i)
+ adx2 = (adx2 * (period - 1) + dx_vals[i]) / period;
+ prev_adx = adx2;
+ }
+
+ IndicatorResult r;
+ r.valid = true;
+ double pdi_curr = atr_smooth > 1e-10 ? plus_smooth / atr_smooth * 100.0 : 0;
+ double mdi_curr = atr_smooth > 1e-10 ? minus_smooth / atr_smooth * 100.0 : 0;
+ r.current[QStringLiteral("value")] = adx;
+ r.current[QStringLiteral("plus_di")] = pdi_curr;
+ r.current[QStringLiteral("minus_di")] = mdi_curr;
+ r.previous[QStringLiteral("value")] = prev_adx;
+ r.previous[QStringLiteral("plus_di")] = pdi_curr;
+ r.previous[QStringLiteral("minus_di")] = mdi_curr;
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_supertrend(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ int period, double multiplier) {
+ int n = close.size();
+ auto atr_s = true_range_series(high, low, close);
+ auto atr_ema = ema_series(atr_s, period);
+
+ if (n < period + 1 || std::isnan(atr_ema[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for SuperTrend"));
+
+ QVector<double> upper(n), lower(n), st(n);
+ QVector<int> dir(n, 1);
+
+ int start = period - 1;
+ for (int i = start; i < n; ++i) {
+ if (std::isnan(atr_ema[i])) continue;
+ double hl2 = (high[i] + low[i]) / 2.0;
+ upper[i] = hl2 + multiplier * atr_ema[i];
+ lower[i] = hl2 - multiplier * atr_ema[i];
+ }
+
+ for (int i = start + 1; i < n; ++i) {
+ if (close[i - 1] > upper[i - 1]) lower[i] = std::max(lower[i], lower[i - 1]);
+ if (close[i - 1] < lower[i - 1]) upper[i] = std::min(upper[i], upper[i - 1]);
+
+ if (close[i] > upper[i]) dir[i] = 1;
+ else if (close[i] < lower[i]) dir[i] = -1;
+ else dir[i] = dir[i - 1];
+
+ st[i] = dir[i] == 1 ? lower[i] : upper[i];
+ }
+
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("value")] = st[n - 1];
+ r.current[QStringLiteral("direction")] = dir[n - 1];
+ if (n >= 2) {
+ r.previous[QStringLiteral("value")] = st[n - 2];
+ r.previous[QStringLiteral("direction")] = dir[n - 2];
+ }
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_aroon(const QVector<double>& high,
+ const QVector<double>& low, int period) {
+ int n = high.size();
+ if (n < period + 1)
+ return make_error(QStringLiteral("Insufficient data for Aroon"));
+
+ auto calc = [&](int end) -> std::pair<double, double> {
+ int hi_idx = 0, lo_idx = 0;
+ double hh = high[end], ll = low[end];
+ for (int j = 1; j <= period; ++j) {
+ if (high[end - j] > hh) { hh = high[end - j]; hi_idx = j; }
+ if (low[end - j] < ll) { ll = low[end - j]; lo_idx = j; }
+ }
+ double up = (static_cast<double>(period - hi_idx) / period) * 100.0;
+ double down = (static_cast<double>(period - lo_idx) / period) * 100.0;
+ return {up, down};
+ };
+
+ auto [up_c, dn_c] = calc(n - 1);
+ auto [up_p, dn_p] = (n >= period + 2) ? calc(n - 2) : std::pair{up_c, dn_c};
+
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("up")] = up_c;
+ r.current[QStringLiteral("down")] = dn_c;
+ r.previous[QStringLiteral("up")] = up_p;
+ r.previous[QStringLiteral("down")] = dn_p;
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_ichimoku(const QVector<double>& high,
+ const QVector<double>& low,
+ int tenkan, int kijun, int senkou) {
+ int n = high.size();
+ if (n < senkou)
+ return make_error(QStringLiteral("Insufficient data for Ichimoku"));
+
+ auto midpoint = [&](int end, int period) -> double {
+ double hh = high[end], ll = low[end];
+ for (int j = 1; j < period; ++j) {
+ hh = std::max(hh, high[end - j]);
+ ll = std::min(ll, low[end - j]);
+ }
+ return (hh + ll) / 2.0;
+ };
+
+ int i = n - 1;
+ double ts = midpoint(i, tenkan);
+ double ks = midpoint(i, kijun);
+ double sa = (ts + ks) / 2.0;
+ double sb = midpoint(i, senkou);
+
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("tenkan_sen")] = ts;
+ r.current[QStringLiteral("kijun_sen")] = ks;
+ r.current[QStringLiteral("senkou_a")] = sa;
+ r.current[QStringLiteral("senkou_b")] = sb;
+
+ if (n > senkou) {
+ int p = n - 2;
+ r.previous[QStringLiteral("tenkan_sen")] = midpoint(p, tenkan);
+ r.previous[QStringLiteral("kijun_sen")] = midpoint(p, kijun);
+ double pts = midpoint(p, tenkan), pks = midpoint(p, kijun);
+ r.previous[QStringLiteral("senkou_a")] = (pts + pks) / 2.0;
+ r.previous[QStringLiteral("senkou_b")] = midpoint(p, senkou);
+ }
+ return r;
+}
+
+// ── Volatility ──────────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute_atr(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period) {
+ auto tr = true_range_series(high, low, close);
+ int n = tr.size();
+ if (n < period + 1)
+ return make_error(QStringLiteral("Insufficient data for ATR"));
+
+ double atr = 0;
+ for (int i = 0; i < period; ++i)
+ atr += tr[i + 1];
+ atr /= period;
+
+ for (int i = period + 1; i < n; ++i)
+ atr = (atr * (period - 1) + tr[i]) / period;
+
+ double prev_atr = atr;
+ if (n > period + 1) {
+ double a2 = 0;
+ for (int i = 0; i < period; ++i)
+ a2 += tr[i + 1];
+ a2 /= period;
+ for (int i = period + 1; i < n - 1; ++i)
+ a2 = (a2 * (period - 1) + tr[i]) / period;
+ prev_atr = a2;
+ }
+ return make_result(atr, prev_atr);
+}
+
+IndicatorResult IndicatorEngine::compute_bollinger(const QVector<double>& close,
+ int period, double std_dev_mult) {
+ int n = close.size();
+ if (n < period)
+ return make_error(QStringLiteral("Insufficient data for Bollinger"));
+
+ auto sma = sma_series(close, period);
+
+ auto calc = [&](int idx) -> std::tuple<double, double, double, double, double> {
+ double mid = sma[idx];
+ double sum_sq = 0;
+ for (int j = 0; j < period; ++j) {
+ double diff = close[idx - j] - mid;
+ sum_sq += diff * diff;
+ }
+ double sd = std::sqrt(sum_sq / period);
+ double upper = mid + std_dev_mult * sd;
+ double lower = mid - std_dev_mult * sd;
+ double width = mid > 1e-10 ? (upper - lower) / mid : 0;
+ double pct_b = (upper - lower) > 1e-10 ? (close[idx] - lower) / (upper - lower) : 0.5;
+ return {upper, mid, lower, width, pct_b};
+ };
+
+ auto [u, m, l, w, pb] = calc(n - 1);
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("upper")] = u;
+ r.current[QStringLiteral("middle")] = m;
+ r.current[QStringLiteral("lower")] = l;
+ r.current[QStringLiteral("width")] = w;
+ r.current[QStringLiteral("pct_b")] = pb;
+
+ if (n >= period + 1) {
+ auto [u2, m2, l2, w2, pb2] = calc(n - 2);
+ r.previous[QStringLiteral("upper")] = u2;
+ r.previous[QStringLiteral("middle")] = m2;
+ r.previous[QStringLiteral("lower")] = l2;
+ r.previous[QStringLiteral("width")] = w2;
+ r.previous[QStringLiteral("pct_b")] = pb2;
+ }
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_keltner(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ int period, double multiplier) {
+ auto ema = ema_series(close, period);
+ auto tr = true_range_series(high, low, close);
+ auto atr = ema_series(tr, period);
+ int n = close.size();
+
+ if (n < 1 || std::isnan(ema[n - 1]) || std::isnan(atr[n - 1]))
+ return make_error(QStringLiteral("Insufficient data for Keltner"));
+
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("upper")] = ema[n - 1] + multiplier * atr[n - 1];
+ r.current[QStringLiteral("middle")] = ema[n - 1];
+ r.current[QStringLiteral("lower")] = ema[n - 1] - multiplier * atr[n - 1];
+ if (n >= 2 && !std::isnan(ema[n - 2]) && !std::isnan(atr[n - 2])) {
+ r.previous[QStringLiteral("upper")] = ema[n - 2] + multiplier * atr[n - 2];
+ r.previous[QStringLiteral("middle")] = ema[n - 2];
+ r.previous[QStringLiteral("lower")] = ema[n - 2] - multiplier * atr[n - 2];
+ }
+ return r;
+}
+
+IndicatorResult IndicatorEngine::compute_donchian(const QVector<double>& high,
+ const QVector<double>& low, int period) {
+ int n = high.size();
+ if (n < period)
+ return make_error(QStringLiteral("Insufficient data for Donchian"));
+
+ auto calc = [&](int end) -> std::pair<double, double> {
+ double hh = high[end], ll = low[end];
+ for (int j = 1; j < period; ++j) {
+ hh = std::max(hh, high[end - j]);
+ ll = std::min(ll, low[end - j]);
+ }
+ return {hh, ll};
+ };
+
+ auto [uc, lc] = calc(n - 1);
+ IndicatorResult r;
+ r.valid = true;
+ r.current[QStringLiteral("upper")] = uc;
+ r.current[QStringLiteral("lower")] = lc;
+ if (n >= period + 1) {
+ auto [up, lp] = calc(n - 2);
+ r.previous[QStringLiteral("upper")] = up;
+ r.previous[QStringLiteral("lower")] = lp;
+ }
+ return r;
+}
+
+// ── Volume ──────────────────────────────────────────────────────────────────
+
+IndicatorResult IndicatorEngine::compute_obv(const QVector<double>& close,
+ const QVector<double>& volume) {
+ int n = close.size();
+ if (n < 2)
+ return make_error(QStringLiteral("Insufficient data for OBV"));
+
+ double obv = 0, prev_obv = 0;
+ for (int i = 1; i < n; ++i) {
+ if (i == n - 1) prev_obv = obv;
+ if (close[i] > close[i - 1]) obv += volume[i];
+ else if (close[i] < close[i - 1]) obv -= volume[i];
+ }
+ return make_result(obv, prev_obv);
+}
+
+IndicatorResult IndicatorEngine::compute_cmf(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ const QVector<double>& volume, int period) {
+ int n = close.size();
+ if (n < period)
+ return make_error(QStringLiteral("Insufficient data for CMF"));
+
+ auto calc = [&](int end) -> double {
+ double mfv_sum = 0, vol_sum = 0;
+ for (int j = 0; j < period; ++j) {
+ int idx = end - j;
+ double hl = high[idx] - low[idx];
+ double mf_mult = hl > 1e-10 ? ((close[idx] - low[idx]) - (high[idx] - close[idx])) / hl : 0;
+ mfv_sum += mf_mult * volume[idx];
+ vol_sum += volume[idx];
+ }
+ return vol_sum > 1e-10 ? mfv_sum / vol_sum : 0;
+ };
+
+ double curr = calc(n - 1);
+ double prev = (n >= period + 1) ? calc(n - 2) : curr;
+ return make_result(curr, prev);
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/IndicatorEngine.h b/fincept-qt/src/algo_engine/IndicatorEngine.h
new file mode 100644
index 000000000..e458a4314
--- /dev/null
+++ b/fincept-qt/src/algo_engine/IndicatorEngine.h
@@ -0,0 +1,98 @@
+// src/algo_engine/IndicatorEngine.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+
+#include <QJsonObject>
+#include <QString>
+#include <QVector>
+
+namespace fincept::algo {
+
+class IndicatorEngine {
+public:
+ static IndicatorResult compute(const QString& indicator_name,
+ const QVector<OhlcvCandle>& candles,
+ const QJsonObject& params,
+ const QString& field);
+
+private:
+ static void extract_arrays(const QVector<OhlcvCandle>& candles,
+ QVector<double>& open, QVector<double>& high,
+ QVector<double>& low, QVector<double>& close,
+ QVector<double>& volume);
+
+ // Moving averages
+ static IndicatorResult compute_sma(const QVector<double>& src, int period);
+ static IndicatorResult compute_ema(const QVector<double>& src, int period);
+ static IndicatorResult compute_wma(const QVector<double>& src, int period);
+ static IndicatorResult compute_dema(const QVector<double>& src, int period);
+ static IndicatorResult compute_tema(const QVector<double>& src, int period);
+
+ // Momentum
+ static IndicatorResult compute_rsi(const QVector<double>& close, int period);
+ static IndicatorResult compute_macd(const QVector<double>& close,
+ int fast, int slow, int signal_period);
+ static IndicatorResult compute_stochastic(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ int k_period, int d_period);
+ static IndicatorResult compute_cci(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period);
+ static IndicatorResult compute_williams_r(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period);
+ static IndicatorResult compute_mfi(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ const QVector<double>& volume, int period);
+ static IndicatorResult compute_roc(const QVector<double>& close, int period);
+
+ // Trend
+ static IndicatorResult compute_adx(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period);
+ static IndicatorResult compute_supertrend(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ int period, double multiplier);
+ static IndicatorResult compute_aroon(const QVector<double>& high,
+ const QVector<double>& low, int period);
+ static IndicatorResult compute_ichimoku(const QVector<double>& high,
+ const QVector<double>& low,
+ int tenkan, int kijun, int senkou);
+
+ // Volatility
+ static IndicatorResult compute_atr(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close, int period);
+ static IndicatorResult compute_bollinger(const QVector<double>& close,
+ int period, double std_dev);
+ static IndicatorResult compute_keltner(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ int period, double multiplier);
+ static IndicatorResult compute_donchian(const QVector<double>& high,
+ const QVector<double>& low, int period);
+
+ // Volume
+ static IndicatorResult compute_obv(const QVector<double>& close,
+ const QVector<double>& volume);
+ static IndicatorResult compute_cmf(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close,
+ const QVector<double>& volume, int period);
+
+ // Stock attribute pseudo-indicators
+ static IndicatorResult compute_stock_attr(const QVector<OhlcvCandle>& candles,
+ const QString& attr);
+
+ // Helpers
+ static QVector<double> ema_series(const QVector<double>& src, int period);
+ static QVector<double> sma_series(const QVector<double>& src, int period);
+ static QVector<double> true_range_series(const QVector<double>& high,
+ const QVector<double>& low,
+ const QVector<double>& close);
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/PositionManager.cpp b/fincept-qt/src/algo_engine/PositionManager.cpp
new file mode 100644
index 000000000..fb43131f8
--- /dev/null
+++ b/fincept-qt/src/algo_engine/PositionManager.cpp
@@ -0,0 +1,198 @@
+// src/algo_engine/PositionManager.cpp
+#include "algo_engine/PositionManager.h"
+
+#include <QDateTime>
+#include <QMutexLocker>
+#include <QUuid>
+
+#include <cmath>
+
+namespace fincept::algo {
+
+PositionManager::PositionManager(const QString& deployment_id,
+ double stop_loss_pct, double take_profit_pct,
+ double trailing_stop_pct, double max_order_value,
+ double max_daily_loss)
+ : deployment_id_(deployment_id)
+ , stop_loss_pct_(stop_loss_pct)
+ , take_profit_pct_(take_profit_pct)
+ , trailing_stop_pct_(trailing_stop_pct)
+ , max_order_value_(max_order_value)
+ , max_daily_loss_(max_daily_loss) {
+ risk_.day_start_epoch = QDateTime::currentMSecsSinceEpoch();
+}
+
+std::optional<AlgoOrderSignal> PositionManager::check_risk(double current_price) {
+ QMutexLocker lock(&mutex_);
+
+ if (position_.side == PositionSide::None)
+ return std::nullopt;
+
+ // Daily loss limit
+ if (max_daily_loss_ > 0 && risk_.daily_pnl <= -std::abs(max_daily_loss_)) {
+ risk_.paused_by_loss_limit = true;
+ AlgoOrderSignal sig;
+ sig.deployment_id = deployment_id_;
+ sig.side = (position_.side == PositionSide::Long) ? "SELL" : "BUY";
+ sig.quantity = position_.quantity;
+ sig.reason = "daily_loss_limit";
+ return sig;
+ }
+
+ double pnl_pct = 0;
+ if (position_.side == PositionSide::Long && position_.entry_price > 1e-10)
+ pnl_pct = (current_price - position_.entry_price) / position_.entry_price * 100.0;
+ else if (position_.side == PositionSide::Short && position_.entry_price > 1e-10)
+ pnl_pct = (position_.entry_price - current_price) / position_.entry_price * 100.0;
+
+ // Stop loss
+ if (stop_loss_pct_ > 0 && pnl_pct <= -std::abs(stop_loss_pct_)) {
+ AlgoOrderSignal sig;
+ sig.deployment_id = deployment_id_;
+ sig.side = (position_.side == PositionSide::Long) ? "SELL" : "BUY";
+ sig.quantity = position_.quantity;
+ sig.reason = "stop_loss";
+ return sig;
+ }
+
+ // Take profit
+ if (take_profit_pct_ > 0 && pnl_pct >= std::abs(take_profit_pct_)) {
+ AlgoOrderSignal sig;
+ sig.deployment_id = deployment_id_;
+ sig.side = (position_.side == PositionSide::Long) ? "SELL" : "BUY";
+ sig.quantity = position_.quantity;
+ sig.reason = "take_profit";
+ return sig;
+ }
+
+ // Trailing stop
+ if (trailing_stop_pct_ > 0) {
+ if (position_.side == PositionSide::Long) {
+ if (current_price > position_.highest_since_entry)
+ position_.highest_since_entry = current_price;
+ double peak_pnl = (position_.highest_since_entry - position_.entry_price) / position_.entry_price * 100.0;
+ if (peak_pnl - pnl_pct >= trailing_stop_pct_) {
+ AlgoOrderSignal sig;
+ sig.deployment_id = deployment_id_;
+ sig.side = "SELL";
+ sig.quantity = position_.quantity;
+ sig.reason = "trailing_stop";
+ return sig;
+ }
+ } else {
+ if (current_price < position_.lowest_since_entry || position_.lowest_since_entry < 1e-10)
+ position_.lowest_since_entry = current_price;
+ double peak_pnl = (position_.entry_price - position_.lowest_since_entry) / position_.entry_price * 100.0;
+ if (peak_pnl - pnl_pct >= trailing_stop_pct_) {
+ AlgoOrderSignal sig;
+ sig.deployment_id = deployment_id_;
+ sig.side = "BUY";
+ sig.quantity = position_.quantity;
+ sig.reason = "trailing_stop";
+ return sig;
+ }
+ }
+ }
+
+ return std::nullopt;
+}
+
+void PositionManager::record_entry(PositionSide side, double qty, double price, int64_t time_ms) {
+ QMutexLocker lock(&mutex_);
+ position_.side = side;
+ position_.quantity = qty;
+ position_.entry_price = price;
+ position_.entry_time = time_ms;
+ position_.unrealized_pnl = 0;
+ position_.highest_since_entry = price;
+ position_.lowest_since_entry = price;
+ metrics_.last_trade_time = time_ms;
+}
+
+double PositionManager::record_exit(double qty, double price, int64_t time_ms) {
+ QMutexLocker lock(&mutex_);
+ double pnl = 0;
+ if (position_.side == PositionSide::Long)
+ pnl = (price - position_.entry_price) * qty;
+ else if (position_.side == PositionSide::Short)
+ pnl = (position_.entry_price - price) * qty;
+
+ metrics_.total_pnl += pnl;
+ metrics_.total_trades++;
+ if (pnl > 0) metrics_.winning_trades++;
+ else if (pnl < 0) metrics_.losing_trades++;
+ metrics_.win_rate = metrics_.total_trades > 0
+ ? static_cast<double>(metrics_.winning_trades) / metrics_.total_trades * 100.0 : 0;
+ metrics_.last_trade_time = time_ms;
+
+ risk_.daily_pnl += pnl;
+ update_drawdown();
+
+ position_.side = PositionSide::None;
+ position_.quantity = 0;
+ position_.entry_price = 0;
+ position_.entry_time = 0;
+ position_.unrealized_pnl = 0;
+
+ return pnl;
+}
+
+void PositionManager::update_price(double price) {
+ QMutexLocker lock(&mutex_);
+ metrics_.current_price = price;
+ if (position_.side == PositionSide::Long)
+ position_.unrealized_pnl = (price - position_.entry_price) * position_.quantity;
+ else if (position_.side == PositionSide::Short)
+ position_.unrealized_pnl = (position_.entry_price - price) * position_.quantity;
+ metrics_.unrealized_pnl = position_.unrealized_pnl;
+ metrics_.current_position_qty = position_.quantity;
+ metrics_.current_position_side = position_side_to_string(position_.side);
+ metrics_.current_position_entry = position_.entry_price;
+}
+
+void PositionManager::update_drawdown() {
+ double equity = metrics_.total_pnl;
+ if (equity > risk_.peak_equity) risk_.peak_equity = equity;
+ double dd = risk_.peak_equity - equity;
+ if (dd > risk_.max_drawdown) risk_.max_drawdown = dd;
+ metrics_.max_drawdown = risk_.max_drawdown;
+}
+
+bool PositionManager::has_position() const {
+ QMutexLocker lock(&mutex_);
+ return position_.side != PositionSide::None;
+}
+
+bool PositionManager::is_paused() const {
+ QMutexLocker lock(&mutex_);
+ return risk_.paused_by_loss_limit;
+}
+
+bool PositionManager::validate_order_value(double qty, double price) const {
+ if (max_order_value_ <= 0) return true;
+ return (qty * price) <= max_order_value_;
+}
+
+AlgoPosition PositionManager::position() const {
+ QMutexLocker lock(&mutex_);
+ return position_;
+}
+
+AlgoMetrics PositionManager::metrics() const {
+ QMutexLocker lock(&mutex_);
+ return metrics_;
+}
+
+RiskState PositionManager::risk_state() const {
+ QMutexLocker lock(&mutex_);
+ return risk_;
+}
+
+void PositionManager::reset_daily() {
+ QMutexLocker lock(&mutex_);
+ risk_.daily_pnl = 0;
+ risk_.paused_by_loss_limit = false;
+ risk_.day_start_epoch = QDateTime::currentMSecsSinceEpoch();
+}
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/PositionManager.h b/fincept-qt/src/algo_engine/PositionManager.h
new file mode 100644
index 000000000..5d08f8160
--- /dev/null
+++ b/fincept-qt/src/algo_engine/PositionManager.h
@@ -0,0 +1,50 @@
+// src/algo_engine/PositionManager.h
+#pragma once
+#include "algo_engine/AlgoEngineTypes.h"
+
+#include <QMutex>
+
+#include <optional>
+
+namespace fincept::algo {
+
+class PositionManager {
+public:
+ explicit PositionManager(const QString& deployment_id,
+ double stop_loss_pct, double take_profit_pct,
+ double trailing_stop_pct, double max_order_value,
+ double max_daily_loss);
+
+ std::optional<AlgoOrderSignal> check_risk(double current_price);
+
+ void record_entry(PositionSide side, double qty, double price, int64_t time_ms);
+ double record_exit(double qty, double price, int64_t time_ms);
+
+ bool has_position() const;
+ bool is_paused() const;
+ bool validate_order_value(double qty, double price) const;
+
+ AlgoPosition position() const;
+ AlgoMetrics metrics() const;
+ RiskState risk_state() const;
+ void update_price(double price);
+ void reset_daily();
+
+private:
+ void update_drawdown();
+
+ QString deployment_id_;
+ AlgoPosition position_;
+ RiskState risk_;
+ AlgoMetrics metrics_;
+
+ double stop_loss_pct_;
+ double take_profit_pct_;
+ double trailing_stop_pct_;
+ double max_order_value_;
+ double max_daily_loss_;
+
+ mutable QMutex mutex_;
+};
+
+} // namespace fincept::algo
diff --git a/fincept-qt/src/app/WindowFrame.cpp b/fincept-qt/src/app/WindowFrame.cpp
index 9d1965429..5a90dbdaa 100644
--- a/fincept-qt/src/app/WindowFrame.cpp
+++ b/fincept-qt/src/app/WindowFrame.cpp
@@ -363,7 +363,7 @@ WindowFrame::WindowFrame(int window_id, QWidget* parent, const WindowId& adopted
// Per-screen tool filter wiring removed (Tool RAG / Tier-0 model).
// The LLM now sees a 6-tool Tier-0 prefix on every turn and discovers
- // the rest via tool.list — making per-screen scoping unnecessary and
+ // the rest via tool_list — making per-screen scoping unnecessary and
// counterproductive (it would prevent the LLM from finding tools the
// user might want regardless of which screen happens to be active).
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index e20466474..c94261a72 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -1,4 +1,5 @@
-#include "services/llm/LlmService.h"
+#include "algo_engine/AlgoEngineProducer.h"
+#include "services/llm/LlmService.h"
#include "app/MonitorPickerDialog.h"
#include "app/WindowFrame.h"
#include "app/TerminalShell.h"
@@ -418,6 +419,9 @@ int main(int argc, char* argv[]) {
fincept::wallet::WalletService::instance().ensure_registered_with_hub();
fincept::wallet::WalletService::instance().restore_from_storage();
+ // Algo Engine — `algo:metrics:*`, `algo:trade:*`, `algo:state:*`.
+ fincept::algo::AlgoEngineProducer::instance().ensure_registered_with_hub();
+
// Fee-discount eligibility producer (paid screens only).
{
static fincept::billing::FeeDiscountService discount_service;
diff --git a/fincept-qt/src/core/layout/WorkspaceShell.cpp b/fincept-qt/src/core/layout/WorkspaceShell.cpp
index 6d8437b50..ee9cfc05a 100644
--- a/fincept-qt/src/core/layout/WorkspaceShell.cpp
+++ b/fincept-qt/src/core/layout/WorkspaceShell.cpp
@@ -193,11 +193,19 @@ int WorkspaceShell::apply(const Workspace& workspace) {
}
}
if (!target) {
- // Spawn a fresh frame and adopt the persisted WindowId via the
- // constructor — must happen before setup_docking_mode's default
- // navigate creates panels that capture frame_uuid(). Without
- // this, the variant geometry/screen lookups (keyed on
- // fl.window_id) would miss for every spawned frame.
+ // Before spawning, reuse any existing unbound frame. Common
+ // after PIN unlock: main.cpp created the window with a fresh
+ // UUID that doesn't match the saved workspace's frame UUID.
+ // Without this, apply() spawns a duplicate window.
+ for (auto* f : frames_now) {
+ if (f && !bound.contains(f)) {
+ target = f;
+ break;
+ }
+ }
+ }
+ if (!target) {
+ // No existing frame to reuse — genuinely need a new window.
target = new fincept::WindowFrame(
fincept::WindowFrame::next_window_id(),
/*parent=*/nullptr,
diff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cpp
index 27d93b5b1..26ecf1d41 100644
--- a/fincept-qt/src/mcp/McpInit.cpp
+++ b/fincept-qt/src/mcp/McpInit.cpp
@@ -181,7 +181,7 @@ void initialize_all_tools() {
// surface-analytics — 35-surface capability catalog + Databento fetches
provider.register_tools(tools::get_surface_analytics_tools());
- // Phase 6: meta tools — tool.list, tool.describe, mcp.health.
+ // Phase 6: meta tools — tool_list, tool_describe, mcp_health.
// Always exposed so the LLM can lazy-discover specialised tools.
provider.register_tools(tools::get_meta_tools());
diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cpp
index cf4380c49..ebc2f5e71 100644
--- a/fincept-qt/src/mcp/McpProvider.cpp
+++ b/fincept-qt/src/mcp/McpProvider.cpp
@@ -372,10 +372,9 @@ QPair<QString, QString> McpProvider::parse_openai_function_name(const QString& f
return {fn_name.left(pos), decode_tool_name_from_wire(fn_name.mid(pos + 2))};
// Fallback: some models (minimax, certain OpenRouter routes) drop the
- // "<server>__" prefix and call the tool by its bare advertised name
- // (e.g. "tool.list" instead of "fincept-terminal__tool-dot-list").
- // Accept either the raw dotted form or the wire-encoded form if it
- // matches a known internal tool — anything else is still rejected.
+ // "<server>__" prefix and call the tool by its bare advertised name.
+ // Accept either the raw form or the wire-encoded form if it matches
+ // a known internal tool — anything else is still rejected.
if (!fn_name.isEmpty()) {
const QString decoded = decode_tool_name_from_wire(fn_name);
if (instance().has_tool(decoded))
diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.h
index 583c1b20b..a71844b25 100644
--- a/fincept-qt/src/mcp/McpProvider.h
+++ b/fincept-qt/src/mcp/McpProvider.h
@@ -43,7 +43,7 @@ class McpProvider {
/// O(1) lookup of a single tool's UnifiedTool snapshot by canonical name.
/// Returns `std::nullopt` if the name is unknown or disabled. Used by
- /// tool.describe so the hot tool-pick path doesn't pay the O(N) cost of
+ /// tool_describe so the hot tool-pick path doesn't pay the O(N) cost of
/// list_tools()+linear-scan (was ~3 ms p95 across the 583-tool catalog).
std::optional<UnifiedTool> find_tool(const QString& name) const;
diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cpp
index 2cf1354ba..6d76b5c79 100644
--- a/fincept-qt/src/mcp/McpService.cpp
+++ b/fincept-qt/src/mcp/McpService.cpp
@@ -217,21 +217,21 @@ QJsonArray McpService::format_tools_for_openai() {
//
// Rationale: when Tool RAG is active we send only this 6-tool prefix to the
// LLM each turn (~3 KB of schema vs ~25 KB previously). Everything else is
-// discoverable via tool.list. Anthropic's recommended band is 3-5 always-on
+// discoverable via tool_list. Anthropic's recommended band is 3-5 always-on
// tools — we go to 6 to keep navigation working without a search round-trip.
//
// Picked because they're (1) high-frequency, (2) safe (no destructive ops),
// (3) needed before a search would even make sense:
-// tool.list — entry point to discover everything else
-// tool.describe — fetch full schema for a discovered tool
+// tool_list — entry point to discover everything else
+// tool_describe — fetch full schema for a discovered tool
// navigate_to_tab — UI navigation is the LLM's primary side-effect
// list_tabs — what tabs exist?
// get_current_tab — where is the user?
// get_auth_status — guest vs signed-in changes valid actions
static const QSet<QString>& tier_0_tool_names() {
static const QSet<QString> kTier0 = {
- "tool.list",
- "tool.describe",
+ "tool_list",
+ "tool_describe",
"navigate_to_tab",
"list_tabs",
"get_current_tab",
@@ -249,7 +249,7 @@ static const QSet<QString>& tier_0_tool_names() {
//
// Default = TRUE.
//
-// Rationale: Tool RAG (BM25 retrieval over the catalog via tool.list) lifts
+// Rationale: Tool RAG (BM25 retrieval over the catalog via tool_list) lifts
// tool-pick accuracy from ~49 → ~74% on Opus 4-class models per Anthropic's
// published numbers, and from ~80 → ~88% on 4.5-class. Sending only ~6
// Tier-0 tools per turn (vs. previously ~50) reduces prompt tokens by ~85%.
@@ -304,7 +304,7 @@ QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter) {
QJsonArray result;
for (const auto& tool : tools) {
// Encode tool name for the wire so dotted internal names like
- // `tool.list` become `tool-dot-list` — Kimi / OpenAI / Groq reject
+ // `tool.list` becomes `tool-dot-list` — Kimi / OpenAI / Groq reject
// dots in function names. parse_openai_function_name reverses this
// when the model invokes the tool.
QString fn_name = tool.server_id + "__" + McpProvider::encode_tool_name_for_wire(tool.name);
diff --git a/fincept-qt/src/mcp/McpTypes.h b/fincept-qt/src/mcp/McpTypes.h
index 56c32efb3..eac8f736d 100644
--- a/fincept-qt/src/mcp/McpTypes.h
+++ b/fincept-qt/src/mcp/McpTypes.h
@@ -308,7 +308,7 @@ struct ToolDef {
// • prompt cost shrinks for non-cached providers
// • the LLM has fewer distractors when picking a tool
// • dangerous categories can be excluded by default and lazy-discovered
-// via the tool.list / tool.describe meta-tools (Phase 6.2).
+// via the tool_list / tool_describe meta-tools (Phase 6.2).
struct ToolFilter {
/// Inclusive — only tools whose category matches one of these are kept.
@@ -375,7 +375,7 @@ struct UnifiedTool {
QJsonObject input_schema;
bool is_internal = false;
QString category; // Phase 6: enables ToolFilter category include/exclude
- bool is_destructive = false; // Tool RAG / tool.list surfacing — flag mutating tools
+ bool is_destructive = false; // Tool RAG / tool_list surfacing — flag mutating tools
};
// ============================================================================
diff --git a/fincept-qt/src/mcp/ToolRetriever.cpp b/fincept-qt/src/mcp/ToolRetriever.cpp
index 0f97bcf85..cc9921e2f 100644
--- a/fincept-qt/src/mcp/ToolRetriever.cpp
+++ b/fincept-qt/src/mcp/ToolRetriever.cpp
@@ -148,12 +148,13 @@ bool ToolRetriever::is_stop_word(const QString& token) {
}
QStringList ToolRetriever::tokenise(const QString& text) {
- // Same convention as services/news/NewsClusterService.cpp — split on
- // non-word, lowercase, drop tokens shorter than 2 chars. This catches
- // CamelCase boundaries via the snake_case + camelCase mix already in
- // tool names: e.g. "report_apply_template" → ["report","apply","template"].
+ // Split on non-word characters AND underscores, lowercase, drop tokens
+ // shorter than 2 chars. Splitting on underscores is essential because
+ // tool names are snake_case: "report_apply_template" → ["report","apply","template"].
+ // Without this, the entire snake_case name would be one token and
+ // individual-word queries ("apply template") would miss the name-match bonus.
QStringList out;
- static const QRegularExpression kSplit("\\W+");
+ static const QRegularExpression kSplit("[\\W_]+");
const auto raw = text.toLower().split(kSplit, Qt::SkipEmptyParts);
out.reserve(raw.size());
for (const auto& w : raw) {
@@ -412,8 +413,8 @@ std::vector<ToolMatch> ToolRetriever::search(const QString& query, int top_k,
ToolMatch m;
m.name = d.name;
m.category = d.category;
- // Truncate long descriptions to keep tool.list payload small. Full
- // schema is a tool.describe() call away.
+ // Truncate long descriptions to keep tool_list payload small. Full
+ // schema is a tool_describe() call away.
m.description = d.description.left(200);
if (d.description.size() > 200)
m.description += QStringLiteral("…");
diff --git a/fincept-qt/src/mcp/ToolRetriever.h b/fincept-qt/src/mcp/ToolRetriever.h
index 1d188b4d1..31884ff12 100644
--- a/fincept-qt/src/mcp/ToolRetriever.h
+++ b/fincept-qt/src/mcp/ToolRetriever.h
@@ -5,7 +5,7 @@
// the broader "Tool RAG" literature (Red Hat, IBM, RAG-MCP arXiv 2025/26):
// once a tool catalog exceeds ~30-50 tools, sending all definitions to the
// LLM each turn collapses tool-pick accuracy. The fix is on-demand retrieval:
-// expose ONE meta-tool ("tool.list") that semantically searches the catalog
+// expose ONE meta-tool ("tool_list") that semantically searches the catalog
// and returns the top-K most-relevant tools as references, then the LLM
// fetches the full schema for the one it wants and invokes it.
//
diff --git a/fincept-qt/src/mcp/tools/MetaTools.cpp b/fincept-qt/src/mcp/tools/MetaTools.cpp
index ce2b77ca0..61ca6abde 100644
--- a/fincept-qt/src/mcp/tools/MetaTools.cpp
+++ b/fincept-qt/src/mcp/tools/MetaTools.cpp
@@ -1,4 +1,4 @@
-// MetaTools.cpp — Self-introspection tools (tool.list, tool.describe, mcp.health).
+// MetaTools.cpp — Self-introspection tools (tool_list, tool_describe, mcp_health).
#include "mcp/tools/MetaTools.h"
@@ -27,8 +27,8 @@ static constexpr const char* TAG = "MetaTools";
//
// Why file-local statics rather than a singleton service: the MCP system
// already has too many singletons. These counters are read by exactly one
-// consumer (mcp.health) and written by exactly two writers (tool.list and
-// tool.describe). A class wrapper would be overhead.
+// consumer (mcp_health) and written by exactly two writers (tool_list and
+// tool_describe). A class wrapper would be overhead.
//
// Thread safety: tool handlers run on QtConcurrent worker threads. Atomics
// for scalar counters; mutex+QHash for the per-tool surface map.
@@ -40,7 +40,7 @@ namespace telemetry {
static std::atomic<qint64> g_tool_describe_misses{0};
static QMutex g_surface_mutex;
- static QHash<QString, qint64> g_surfaces; // tool name → times surfaced by tool.list
+ static QHash<QString, qint64> g_surfaces; // tool name → times surfaced by tool_list
static void record_surfaces(const QStringList& names) {
if (names.isEmpty())
@@ -81,7 +81,7 @@ namespace telemetry {
std::vector<ToolDef> get_meta_tools() {
std::vector<ToolDef> tools;
- // ── tool.list ───────────────────────────────────────────────────────
+ // ── tool_list ────────────────────────────────────────────────────────
//
// Tool RAG entry point. Replaces the old regex-over-everything variant
// with BM25 semantic ranking — proven by Anthropic's own Tool Search
@@ -91,16 +91,16 @@ std::vector<ToolDef> get_meta_tools() {
// The LLM is expected to call this with a NATURAL LANGUAGE query
// describing the action it wants to perform. Multi-intent requests
// ("get news on AAPL and add to watchlist") should issue MULTIPLE
- // tool.list calls, one per intent — Anthropic's recommended pattern.
+ // tool_list calls, one per intent — Anthropic's recommended pattern.
{
ToolDef t;
- t.name = "tool.list";
+ t.name = "tool_list";
t.description =
"Search the tool catalog by natural-language query (BM25). Returns the top-K most "
"relevant tools as {name, category, description, destructive, score}. "
"Use this whenever you need a capability you don't already have a tool for. "
"For multi-intent requests, call multiple times — once per intent. "
- "After picking a tool, call tool.describe(name) for the full input schema.";
+ "After picking a tool, call tool_describe(name) for the full input schema.";
t.category = "meta";
t.input_schema = ToolSchemaBuilder()
.string("query", "Natural-language description of the capability you need "
@@ -154,12 +154,12 @@ std::vector<ToolDef> get_meta_tools() {
tools.push_back(std::move(t));
}
- // ── tool.describe ───────────────────────────────────────────────────
+ // ── tool_describe ────────────────────────────────────────────────────
{
ToolDef t;
- t.name = "tool.describe";
+ t.name = "tool_describe";
t.description = "Return the full description and JSON Schema for one MCP tool. "
- "Use after tool.list to fetch the parameter shape before calling.";
+ "Use after tool_list to fetch the parameter shape before calling.";
t.category = "meta";
t.input_schema = ToolSchemaBuilder()
.string("name", "Bare tool name (without server_id__ prefix)").required().length(1, 128)
@@ -185,10 +185,10 @@ std::vector<ToolDef> get_meta_tools() {
tools.push_back(std::move(t));
}
- // ── mcp.health ──────────────────────────────────────────────────────
+ // ── mcp_health ───────────────────────────────────────────────────────
{
ToolDef t;
- t.name = "mcp.health";
+ t.name = "mcp_health";
t.description = "Snapshot of MCP system health: internal tool counts by category, "
"external server statuses + last errors, and DataHub topic activity. "
"Useful for agents to self-diagnose ('why is my tool failing?').";
diff --git a/fincept-qt/src/mcp/tools/MetaTools.h b/fincept-qt/src/mcp/tools/MetaTools.h
index f8b773542..f67c1b638 100644
--- a/fincept-qt/src/mcp/tools/MetaTools.h
+++ b/fincept-qt/src/mcp/tools/MetaTools.h
@@ -3,16 +3,16 @@
//
// Three always-available tools the LLM can call to explore the catalogue:
//
-// tool.list(category?, search?, limit?)
+// tool_list(category?, search?, limit?)
// One-line summary per matching tool (no schemas). Cheap to embed in
// prompts. Lets the LLM discover specialised tools without the full
// 237-tool catalogue ballooning every request.
//
-// tool.describe(name)
+// tool_describe(name)
// Full schema + description for a single tool. Called when the LLM has
// identified which tool it wants and now needs the parameter shape.
//
-// mcp.health
+// mcp_health
// Snapshot of the MCP system: internal tool count by category, external
// server statuses + last errors, DataHub topic count. Lets agents
// self-diagnose ("why is my tool failing?") and surfaces ops state to
diff --git a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp
index c5fe085b7..4d0942c7b 100644
--- a/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp
+++ b/fincept-qt/src/mcp/tools/ReportBuilderTools.cpp
@@ -657,7 +657,7 @@ std::vector<ToolDef> get_report_builder_tools() {
}
// ── report_list_component_types ─────────────────────────────────────────
- // Saves the LLM from calling tool.describe for every type variant.
+ // Saves the LLM from calling tool_describe for every type variant.
{
ToolDef t;
t.name = "report_list_component_types";
diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
new file mode 100644
index 000000000..784006ebc
--- /dev/null
+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.cpp
@@ -0,0 +1,233 @@
+#include "screens/algo_trading/AlgoDeployDialog.h"
+
+#include "services/algo_trading/AlgoTradingTypes.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
+#include "ui/theme/Theme.h"
+
+#include <QDialogButtonBox>
+#include <QFormLayout>
+#include <QMessageBox>
+#include <QVBoxLayout>
+
+namespace fincept::screens {
+
+using namespace fincept::ui;
+using namespace fincept::trading;
+using namespace fincept::services::algo;
+
+AlgoDeployDialog::AlgoDeployDialog(const QString& strategy_id, const QString& strategy_name, QWidget* parent)
+ : QDialog(parent), strategy_id_(strategy_id), strategy_name_(strategy_name) {
+ setWindowTitle("Deploy Strategy");
+ setMinimumWidth(420);
+ setStyleSheet(QString("QDialog { background: %1; color: %2; }"
+ "QLabel { color: %3; font-size: 11px; background: transparent; }"
+ "QLineEdit, QComboBox, QDoubleSpinBox { background: %4; color: %2;"
+ " border: 1px solid %5; padding: 4px 8px; font-size: 11px; }"
+ "QLineEdit:focus, QComboBox:focus, QDoubleSpinBox:focus { border-color: %6; }")
+ .arg(colors::BG_SURFACE(), colors::TEXT_PRIMARY(), colors::TEXT_SECONDARY(),
+ colors::BG_BASE(), colors::BORDER_DIM(), colors::CYAN()));
+ build_ui();
+}
+
+AlgoDeployDialog::AlgoDeployDialog(const AlgoStrategy& strategy, QWidget* parent)
+ : AlgoDeployDialog(strategy.id, strategy.name, parent) {
+ result_.strategy_id = strategy.id;
+ result_.strategy_name = strategy.name;
+ result_.timeframe = strategy.timeframe;
+}
+
+void AlgoDeployDialog::build_ui() {
+ auto* root = new QVBoxLayout(this);
+ root->setSpacing(12);
+ root->setContentsMargins(16, 16, 16, 16);
+
+ auto* title = new QLabel(QString("DEPLOY: %1").arg(strategy_name_), this);
+ title->setStyleSheet(QString("color: %1; font-size: 13px; font-weight: 700; font-family: %2;")
+ .arg(colors::AMBER(), fonts::DATA_FAMILY()));
+ root->addWidget(title);
+
+ auto* id_label = new QLabel(strategy_id_, this);
+ id_label->setStyleSheet(QString("color: %1; font-size: 9px; font-family: %2;")
+ .arg(colors::TEXT_TERTIARY(), fonts::DATA_FAMILY()));
+ root->addWidget(id_label);
+
+ auto* form = new QFormLayout;
+ form->setSpacing(8);
+ form->setLabelAlignment(Qt::AlignRight);
+
+ symbol_edit_ = new QLineEdit(this);
+ symbol_edit_->setPlaceholderText("e.g. RELIANCE");
+ form->addRow("Symbol:", symbol_edit_);
+
+ mode_combo_ = new QComboBox(this);
+ mode_combo_->addItem("Paper", "paper");
+ mode_combo_->addItem("Live", "live");
+ connect(mode_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AlgoDeployDialog::on_mode_changed);
+ form->addRow("Mode:", mode_combo_);
+
+ // Entry Side
+ side_combo_ = new QComboBox(this);
+ side_combo_->addItem("BUY", "BUY");
+ side_combo_->addItem("SELL", "SELL");
+ form->addRow("Entry Side:", side_combo_);
+
+ account_label_ = new QLabel("Account:", this);
+ account_combo_ = new QComboBox(this);
+ connect(account_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AlgoDeployDialog::on_account_changed);
+ form->addRow(account_label_, account_combo_);
+
+ exchange_label_ = new QLabel("Exchange:", this);
+ exchange_combo_ = new QComboBox(this);
+ form->addRow(exchange_label_, exchange_combo_);
+
+ product_type_label_ = new QLabel("Product Type:", this);
+ product_type_combo_ = new QComboBox(this);
+ form->addRow(product_type_label_, product_type_combo_);
+
+ timeframe_combo_ = new QComboBox(this);
+ for (const auto& tf : algo_timeframes())
+ timeframe_combo_->addItem(tf);
+ timeframe_combo_->setCurrentIndex(4);
+ form->addRow("Timeframe:", timeframe_combo_);
+
+ quantity_spin_ = new QDoubleSpinBox(this);
+ quantity_spin_->setRange(0.01, 999999);
+ quantity_spin_->setValue(1.0);
+ quantity_spin_->setDecimals(2);
+ form->addRow("Quantity:", quantity_spin_);
+
+ max_order_spin_ = new QDoubleSpinBox(this);
+ max_order_spin_->setRange(0, 99999999);
+ max_order_spin_->setValue(0);
+ max_order_spin_->setDecimals(0);
+ max_order_spin_->setSpecialValueText("No limit");
+ form->addRow("Max Order Value:", max_order_spin_);
+
+ max_loss_spin_ = new QDoubleSpinBox(this);
+ max_loss_spin_->setRange(0, 99999999);
+ max_loss_spin_->setValue(0);
+ max_loss_spin_->setDecimals(0);
+ max_loss_spin_->setSpecialValueText("No limit");
+ form->addRow("Max Daily Loss:", max_loss_spin_);
+
+ root->addLayout(form);
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
+ buttons->button(QDialogButtonBox::Ok)->setText("DEPLOY");
+ buttons->setStyleSheet(
+ QString("QPushButton { background: %1; color: %2; border: 1px solid %3;"
+ " font-size: 11px; font-weight: 700; padding: 6px 20px; }"
+ "QPushButton:hover { border-color: %4; color: %4; }")
+ .arg(colors::BG_RAISED(), colors::TEXT_PRIMARY(), colors::BORDER_DIM(), colors::CYAN()));
+ connect(buttons, &QDialogButtonBox::accepted, this, &AlgoDeployDialog::on_ok);
+ connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ root->addWidget(buttons);
+
+ on_mode_changed(0);
+ populate_accounts();
+}
+
+void AlgoDeployDialog::on_mode_changed(int index) {
+ bool is_live = (mode_combo_->itemData(index).toString() == "live");
+ account_label_->setVisible(is_live);
+ account_combo_->setVisible(is_live);
+ exchange_label_->setVisible(is_live);
+ exchange_combo_->setVisible(is_live);
+ product_type_label_->setVisible(is_live);
+ product_type_combo_->setVisible(is_live);
+}
+
+void AlgoDeployDialog::populate_accounts() {
+ account_combo_->clear();
+ auto accounts = AccountManager::instance().active_accounts();
+ for (const auto& acct : accounts) {
+ if (AccountManager::instance().connection_state(acct.account_id) == ConnectionState::Connected) {
+ account_combo_->addItem(acct.display_name, acct.account_id);
+ }
+ }
+ if (account_combo_->count() == 0) {
+ account_combo_->addItem("No connected accounts", "");
+ }
+}
+
+void AlgoDeployDialog::on_account_changed(int index) {
+ if (index < 0)
+ return;
+ populate_broker_fields(account_combo_->itemData(index).toString());
+}
+
+void AlgoDeployDialog::populate_broker_fields(const QString& account_id) {
+ exchange_combo_->clear();
+ product_type_combo_->clear();
+
+ if (account_id.isEmpty())
+ return;
+
+ auto* broker = AccountManager::instance().broker_for(account_id);
+ if (!broker)
+ return;
+
+ auto profile = broker->profile();
+ for (const auto& ex : profile.exchanges)
+ exchange_combo_->addItem(ex);
+ for (const auto& pt : profile.product_types)
+ product_type_combo_->addItem(pt.label, static_cast<int>(pt.value));
+}
+
+void AlgoDeployDialog::on_ok() {
+ if (symbol_edit_->text().trimmed().isEmpty()) {
+ QMessageBox::warning(this, "Validation", "Symbol is required.");
+ return;
+ }
+ if (quantity_spin_->value() <= 0) {
+ QMessageBox::warning(this, "Validation", "Quantity must be > 0.");
+ return;
+ }
+
+ QString mode = mode_combo_->currentData().toString();
+ if (mode == "live") {
+ QString account_id = account_combo_->currentData().toString();
+ if (account_id.isEmpty()) {
+ QMessageBox::warning(this, "Validation", "Select a connected broker account for live mode.");
+ return;
+ }
+ auto creds = AccountManager::instance().load_credentials(account_id);
+ if (creds.access_token.isEmpty()) {
+ QMessageBox::warning(this, "Validation", "Account credentials expired. Re-authenticate in Equity Trading.");
+ return;
+ }
+ }
+
+ result_.strategy_id = strategy_id_;
+ result_.strategy_name = strategy_name_;
+ result_.strategy_kind = kind_to_string(kind_from_id(strategy_id_));
+ result_.symbol = symbol_edit_->text().trimmed().toUpper();
+ result_.mode = mode;
+ result_.entry_side = side_combo_->currentData().toString();
+ result_.timeframe = timeframe_combo_->currentText();
+ result_.quantity = quantity_spin_->value();
+ result_.max_order_value = max_order_spin_->value();
+ result_.max_daily_loss = max_loss_spin_->value();
+
+ if (mode == "live") {
+ auto account_id = account_combo_->currentData().toString();
+ auto account = AccountManager::instance().get_account(account_id);
+ result_.backend = backend_to_string(TradingBackend::EquityBroker);
+ result_.broker_id = account.broker_id;
+ result_.broker_account_id = account_id;
+ result_.exchange = exchange_combo_->currentText();
+ int pt_index = product_type_combo_->currentData().toInt();
+ result_.product_type = product_type_str(static_cast<trading::ProductType>(pt_index));
+ } else {
+ result_.backend = backend_to_string(TradingBackend::Paper);
+ }
+
+ accept();
+}
+
+AlgoDeployment AlgoDeployDialog::result() const {
+ return result_;
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
new file mode 100644
index 000000000..2c0f8aced
--- /dev/null
+++ b/fincept-qt/src/screens/algo_trading/AlgoDeployDialog.h
@@ -0,0 +1,52 @@
+#pragma once
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QComboBox>
+#include <QDialog>
+#include <QDoubleSpinBox>
+#include <QLabel>
+#include <QLineEdit>
+
+namespace fincept::screens {
+
+class AlgoDeployDialog : public QDialog {
+ Q_OBJECT
+ public:
+ explicit AlgoDeployDialog(const QString& strategy_id, const QString& strategy_name, QWidget* parent = nullptr);
+ explicit AlgoDeployDialog(const fincept::services::algo::AlgoStrategy& strategy, QWidget* parent = nullptr);
+
+ fincept::services::algo::AlgoDeployment result() const;
+ fincept::services::algo::AlgoDeployment deployment() const { return result_; }
+
+ private slots:
+ void on_mode_changed(int index);
+ void on_account_changed(int index);
+ void on_ok();
+
+ private:
+ void build_ui();
+ void populate_accounts();
+ void populate_broker_fields(const QString& account_id);
+
+ QString strategy_id_;
+ QString strategy_name_;
+
+ QLineEdit* symbol_edit_ = nullptr;
+ QComboBox* mode_combo_ = nullptr;
+ QComboBox* side_combo_ = nullptr;
+ QComboBox* account_combo_ = nullptr;
+ QComboBox* exchange_combo_ = nullptr;
+ QComboBox* product_type_combo_ = nullptr;
+ QComboBox* timeframe_combo_ = nullptr;
+ QDoubleSpinBox* quantity_spin_ = nullptr;
+ QDoubleSpinBox* max_order_spin_ = nullptr;
+ QDoubleSpinBox* max_loss_spin_ = nullptr;
+
+ QLabel* account_label_ = nullptr;
+ QLabel* exchange_label_ = nullptr;
+ QLabel* product_type_label_ = nullptr;
+
+ fincept::services::algo::AlgoDeployment result_;
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
index e7ff3f61b..8333dd3bc 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -1,6 +1,7 @@
// src/screens/algo_trading/AlgoTradingScreen.cpp
#include "screens/algo_trading/AlgoTradingScreen.h"
+#include "algo_engine/AlgoEngine.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "screens/algo_trading/DeploymentDashboard.h"
@@ -21,14 +22,13 @@ AlgoTradingScreen::AlgoTradingScreen(QWidget* parent) : QWidget(parent) {
build_ui();
poll_timer_ = new QTimer(this);
- poll_timer_->setInterval(5000); // 5s deployment polling
+ poll_timer_->setInterval(5000);
connect(poll_timer_, &QTimer::timeout, this, [this]() {
- if (active_tab_ == 3) // Dashboard tab
- AlgoTradingService::instance().list_deployments();
+ if (active_tab_ == 3)
+ fincept::algo::AlgoEngine::instance().list_deployments();
});
- // Keep deploy count badge in sync whenever deployments are loaded
- connect(&AlgoTradingService::instance(), &AlgoTradingService::deployments_loaded, this,
+ connect(&fincept::algo::AlgoEngine::instance(), &fincept::algo::AlgoEngine::deployments_loaded, this,
[this](const QVector<AlgoDeployment>& deps) {
int active = 0;
for (const auto& d : deps) {
@@ -177,7 +177,7 @@ void AlgoTradingScreen::on_tab_changed(int index) {
if (index == 1)
AlgoTradingService::instance().list_strategies();
if (index == 3)
- AlgoTradingService::instance().list_deployments();
+ fincept::algo::AlgoEngine::instance().list_deployments();
}
void AlgoTradingScreen::update_tab_buttons() {
diff --git a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
index 26bf8cb0a..d1c5e82f2 100644
--- a/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
+++ b/fincept-qt/src/screens/algo_trading/DeploymentDashboard.cpp
@@ -1,8 +1,10 @@
// src/screens/algo_trading/DeploymentDashboard.cpp
#include "screens/algo_trading/DeploymentDashboard.h"
+#include "algo_engine/AlgoEngine.h"
#include "core/logging/Logger.h"
#include "services/algo_trading/AlgoTradingService.h"
+#include "trading/BrokerRegistry.h"
#include "ui/theme/Theme.h"
#include <QFrame>
@@ -29,11 +31,30 @@ inline QString kSectionLabel() {
.arg(kMonoFont());
}
+inline QString currency_symbol(const QString& broker_id) {
+ if (broker_id.isEmpty())
+ return QStringLiteral("$");
+ auto* broker = fincept::trading::BrokerRegistry::instance().get(broker_id);
+ if (!broker)
+ return QStringLiteral("$");
+ const auto currency = broker->profile().currency;
+ if (currency == "INR")
+ return QStringLiteral("₹");
+ if (currency == "EUR")
+ return QStringLiteral("€");
+ if (currency == "GBP")
+ return QStringLiteral("£");
+ if (currency == "JPY")
+ return QStringLiteral("¥");
+ return QStringLiteral("$");
+}
+
} // namespace
namespace fincept::screens {
using namespace fincept::services::algo;
+namespace algo_ns = fincept::algo;
// ── Constructor ─────────────────────────────────────────────────────────────
@@ -46,12 +67,16 @@ DeploymentDashboard::DeploymentDashboard(QWidget* parent) : QWidget(parent) {
// ── Service connections ─────────────────────────────────────────────────────
void DeploymentDashboard::connect_service() {
- auto& svc = AlgoTradingService::instance();
- connect(&svc, &AlgoTradingService::deployments_loaded, this, &DeploymentDashboard::on_deployments_loaded);
- connect(&svc, &AlgoTradingService::deployment_stopped, this, [](const QString& id) {
+ auto& engine = algo_ns::AlgoEngine::instance();
+ connect(&engine, &algo_ns::AlgoEngine::deployments_loaded, this, &DeploymentDashboard::on_deployments_loaded);
+ connect(&engine, &algo_ns::AlgoEngine::deployment_stopped, this, [](const QString& id) {
LOG_INFO("AlgoTrading", QString("Deployment stopped: %1").arg(id));
- AlgoTradingService::instance().list_deployments();
+ algo_ns::AlgoEngine::instance().list_deployments();
});
+ connect(&engine, &algo_ns::AlgoEngine::error_occurred, this, &DeploymentDashboard::on_error);
+
+ // Also connect to legacy service for QC deployments
+ auto& svc = AlgoTradingService::instance();
connect(&svc, &AlgoTradingService::error_occurred, this, &DeploymentDashboard::on_error);
}
@@ -140,6 +165,18 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
.arg(is_paper ? "22,163,74" : "217,119,6"));
top->addWidget(mode_badge);
+ // Entry side badge
+ bool is_sell = (d.entry_side == "SELL");
+ auto* side_badge = new QLabel(d.entry_side.isEmpty() ? "BUY" : d.entry_side, card);
+ side_badge->setStyleSheet(QString("color: %1; font-size: %2px; font-weight: 700; %3"
+ " padding: 2px 6px; background: rgba(%4,0.08);"
+ " border: 1px solid rgba(%4,0.25);")
+ .arg(is_sell ? fincept::ui::colors::NEGATIVE() : fincept::ui::colors::POSITIVE())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont())
+ .arg(is_sell ? "220,38,38" : "22,163,74"));
+ top->addWidget(side_badge);
+
top->addStretch();
// Status badge with dot prefix
@@ -189,10 +226,17 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
// P&L — larger font to match Quant Lab KPI style
double total_pnl = d.total_pnl + d.unrealized_pnl;
- add_metric("P&L", QString("%1$%2").arg(total_pnl >= 0 ? "+" : "-").arg(std::abs(total_pnl), 0, 'f', 2),
+ const auto cs = currency_symbol(d.broker_id);
+ add_metric("P&L", QString("%1%2%3").arg(total_pnl >= 0 ? "+" : "-", cs).arg(std::abs(total_pnl), 0, 'f', 2),
total_pnl >= 0 ? fincept::ui::colors::POSITIVE : fincept::ui::colors::NEGATIVE,
fincept::ui::fonts::TITLE);
+ // Current price
+ if (d.current_price > 0) {
+ add_metric("LTP", QString("%1%2").arg(cs).arg(d.current_price, 0, 'f', 2),
+ fincept::ui::colors::CYAN);
+ }
+
// Win Rate
add_metric("WIN RATE", QString("%1%").arg(d.win_rate, 0, 'f', 1), fincept::ui::colors::TEXT_PRIMARY);
@@ -257,10 +301,24 @@ QWidget* DeploymentDashboard::build_deployment_card(const AlgoDeployment& d, QWi
.arg(fincept::ui::fonts::TINY)
.arg(kMonoFont()));
connect(stop_btn, &QPushButton::clicked, card, [dep_id = d.id]() {
- AlgoTradingService::instance().stop_deployment(dep_id);
+ algo_ns::AlgoEngine::instance().stop_deployment(dep_id);
LOG_INFO("AlgoTrading", QString("Stop requested: %1").arg(dep_id));
});
btn_row->addWidget(stop_btn);
+ } else {
+ auto* remove_btn = new QPushButton("REMOVE", card);
+ remove_btn->setCursor(Qt::PointingHandCursor);
+ remove_btn->setFixedHeight(26);
+ remove_btn->setStyleSheet(QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
+ " font-size: %2px; font-weight: 700; %3 padding: 2px 16px; }"
+ "QPushButton:hover { background: rgba(120,120,120,0.1); }")
+ .arg(fincept::ui::colors::TEXT_TERTIARY())
+ .arg(fincept::ui::fonts::TINY)
+ .arg(kMonoFont()));
+ connect(remove_btn, &QPushButton::clicked, card, [dep_id = d.id]() {
+ algo_ns::AlgoEngine::instance().stop_deployment(dep_id);
+ });
+ btn_row->addWidget(remove_btn);
}
vl->addLayout(btn_row);
@@ -295,7 +353,8 @@ void DeploymentDashboard::update_summary(const QVector<AlgoDeployment>& deployme
active_count_->setText(QString::number(active));
if (total_pnl_) {
- total_pnl_->setText(QString("%1$%2").arg(pnl_sum >= 0 ? "+" : "-").arg(std::abs(pnl_sum), 0, 'f', 2));
+ QString sum_cs = deployments.isEmpty() ? QStringLiteral("$") : currency_symbol(deployments.first().broker_id);
+ total_pnl_->setText(QString("%1%2%3").arg(pnl_sum >= 0 ? "+" : "-", sum_cs).arg(std::abs(pnl_sum), 0, 'f', 2));
total_pnl_->setStyleSheet(QString("color: %1; font-size: %2px; font-weight: 700; %3"
" background: transparent; border: none;")
.arg(pnl_sum >= 0 ? fincept::ui::colors::POSITIVE() : fincept::ui::colors::NEGATIVE())
@@ -339,7 +398,7 @@ void DeploymentDashboard::build_ui() {
summary_row->addWidget(
build_stat_card("ACTIVE DEPLOYMENTS", "0", fincept::ui::colors::CYAN, &active_count_, content));
- summary_row->addWidget(build_stat_card("TOTAL P&L", "$0.00", fincept::ui::colors::POSITIVE, &total_pnl_, content));
+ summary_row->addWidget(build_stat_card("TOTAL P&L", "0.00", fincept::ui::colors::POSITIVE, &total_pnl_, content));
summary_row->addWidget(
build_stat_card("TOTAL TRADES", "0", fincept::ui::colors::TEXT_PRIMARY, &total_trades_, content));
summary_row->addWidget(
@@ -395,7 +454,7 @@ void DeploymentDashboard::build_ui() {
.arg(fincept::ui::fonts::TINY)
.arg(kMonoFont())
.arg(fincept::ui::colors::BG_HOVER(), fincept::ui::colors::TEXT_PRIMARY()));
- connect(refresh_btn, &QPushButton::clicked, this, []() { AlgoTradingService::instance().list_deployments(); });
+ connect(refresh_btn, &QPushButton::clicked, this, []() { algo_ns::AlgoEngine::instance().list_deployments(); });
control_bar->addWidget(refresh_btn);
control_bar->addStretch();
@@ -412,7 +471,7 @@ void DeploymentDashboard::build_ui() {
.arg(kMonoFont())
.arg(fincept::ui::colors::TEXT_PRIMARY()));
connect(stop_all_btn, &QPushButton::clicked, this, []() {
- AlgoTradingService::instance().stop_all_deployments();
+ algo_ns::AlgoEngine::instance().stop_all();
LOG_INFO("AlgoTrading", "Stop all deployments requested");
});
control_bar->addWidget(stop_all_btn);
diff --git a/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp b/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp
index caec38bd6..8e167a6df 100644
--- a/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/ScannerPanel.cpp
@@ -1,8 +1,11 @@
// src/screens/algo_trading/ScannerPanel.cpp
#include "screens/algo_trading/ScannerPanel.h"
+#include "algo_engine/AlgoScanner.h"
+#include "algo_engine/CandleDataFetcher.h"
#include "core/logging/Logger.h"
#include "services/algo_trading/AlgoTradingService.h"
+#include "trading/AccountManager.h"
#include "ui/theme/Theme.h"
#include <QComboBox>
@@ -191,9 +194,11 @@ ScannerPanel::ScannerPanel(QWidget* parent) : QWidget(parent) {
// ── Service connections ─────────────────────────────────────────────────────
void ScannerPanel::connect_service() {
- auto& svc = AlgoTradingService::instance();
- connect(&svc, &AlgoTradingService::scan_result, this, &ScannerPanel::on_scan_result);
- connect(&svc, &AlgoTradingService::error_occurred, this, &ScannerPanel::on_error);
+ auto& scanner = fincept::algo::AlgoScanner::instance();
+ connect(&scanner, &fincept::algo::AlgoScanner::scan_complete, this, &ScannerPanel::on_scan_result);
+ connect(&scanner, &fincept::algo::AlgoScanner::scan_error, this, [this](const QString& err) {
+ on_error(QStringLiteral("scan"), err);
+ });
}
// ── Apply preset ────────────────────────────────────────────────────────────
@@ -414,6 +419,41 @@ void ScannerPanel::build_ui() {
lookback_spin_->setValue(365);
right_vl->addWidget(lookback_spin_);
+ // Data source
+ auto* ds_lbl = new QLabel("DATA SOURCE", right_col);
+ ds_lbl->setStyleSheet(kLabelStyle());
+ right_vl->addWidget(ds_lbl);
+
+ data_source_combo_ = new QComboBox(right_col);
+ data_source_combo_->addItem("Auto (Broker → YFinance)", "Auto");
+ data_source_combo_->addItem("Broker Only", "Broker");
+ data_source_combo_->addItem("YFinance Only", "YFinance");
+ data_source_combo_->setStyleSheet(kComboStyle());
+ data_source_combo_->setFixedHeight(30);
+ right_vl->addWidget(data_source_combo_);
+
+ // Broker account selector (visible when Broker or Auto is selected)
+ auto* acct_lbl = new QLabel("BROKER ACCOUNT", right_col);
+ acct_lbl->setStyleSheet(kLabelStyle());
+ right_vl->addWidget(acct_lbl);
+
+ account_combo_ = new QComboBox(right_col);
+ account_combo_->setStyleSheet(kComboStyle());
+ account_combo_->setFixedHeight(30);
+ account_combo_->addItem("None (use YFinance fallback)", "");
+ auto accounts = fincept::trading::AccountManager::instance().list_accounts();
+ for (const auto& acct : accounts)
+ account_combo_->addItem(
+ QString("%1 (%2)").arg(acct.display_name, acct.broker_id), acct.account_id);
+ right_vl->addWidget(account_combo_);
+
+ connect(data_source_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ right_col, [acct_lbl, this](int idx) {
+ bool show = (idx != 2); // hide account for "YFinance Only"
+ account_combo_->setVisible(show);
+ acct_lbl->setVisible(show);
+ });
+
right_vl->addStretch();
columns->addWidget(right_col, 1);
@@ -525,8 +565,22 @@ void ScannerPanel::on_scan() {
.arg(fincept::ui::fonts::SMALL)
.arg(kMonoFont()));
- AlgoTradingService::instance().run_scan(conditions, symbols, timeframe_combo_->currentText(),
- lookback_spin_->value(), logic_combo_->currentText());
+ auto source = fincept::algo::data_source_from_string(
+ data_source_combo_->currentData().toString());
+
+ QString broker_id, account_id;
+ if (source != fincept::algo::DataSource::YFinance) {
+ account_id = account_combo_->currentData().toString();
+ if (!account_id.isEmpty()) {
+ auto acct = fincept::trading::AccountManager::instance().get_account(account_id);
+ broker_id = acct.broker_id;
+ }
+ }
+
+ fincept::algo::AlgoScanner::instance().scan(
+ conditions, symbols, timeframe_combo_->currentText(),
+ lookback_spin_->value(), logic_combo_->currentText(),
+ source, broker_id, account_id);
LOG_INFO("AlgoTrading",
QString("Scan started: %1 conditions, %2 symbols").arg(conditions.size()).arg(symbols.size()));
diff --git a/fincept-qt/src/screens/algo_trading/ScannerPanel.h b/fincept-qt/src/screens/algo_trading/ScannerPanel.h
index f5ee263ba..a6869360a 100644
--- a/fincept-qt/src/screens/algo_trading/ScannerPanel.h
+++ b/fincept-qt/src/screens/algo_trading/ScannerPanel.h
@@ -36,7 +36,9 @@ class ScannerPanel : public QWidget {
QSpinBox* lookback_spin_ = nullptr;
QComboBox* preset_combo_ = nullptr;
QComboBox* logic_combo_ = nullptr;
- QTableWidget* results_table_ = nullptr; // replaced QVBoxLayout
+ QComboBox* data_source_combo_ = nullptr;
+ QComboBox* account_combo_ = nullptr;
+ QTableWidget* results_table_ = nullptr;
QLabel* status_label_ = nullptr;
};
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
index ef73b6459..cf6d9cdcc 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
@@ -1,881 +1,397 @@
// src/screens/algo_trading/StrategyBuilderPanel.cpp
#include "screens/algo_trading/StrategyBuilderPanel.h"
+#include "algo_engine/AlgoEngine.h"
#include "core/events/EventBus.h"
#include "core/logging/Logger.h"
+#include "screens/algo_trading/AlgoDeployDialog.h"
#include "services/algo_trading/AlgoTradingService.h"
-#include "services/backtesting/BacktestingService.h"
-#include "services/file_manager/FileManagerService.h"
#include "ui/theme/Theme.h"
-#include <QFile>
-#include <QFileInfo>
#include <QGridLayout>
#include <QHBoxLayout>
-#include <QJsonArray>
#include <QJsonDocument>
-#include <QJsonObject>
-#include <QRegularExpression>
#include <QScrollArea>
#include <QSplitter>
#include <QUuid>
-
-// ── Shared style helpers ────────────────────────────────────────────────────
-
-namespace {
-
-inline QString kMonoFont() {
- return QString("font-family: %1;").arg(fincept::ui::fonts::DATA_FAMILY);
-}
-inline QString kLabelStyle() {
- return QString("color: %1; font-size: %2px; font-weight: 700; letter-spacing: 0.5px; %3"
- "background: transparent; border: none;")
- .arg(fincept::ui::colors::TEXT_SECONDARY())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont());
-}
-inline QString kSectionLabel() {
- return QString("color: %1; font-size: %2px; font-weight: 700; letter-spacing: 0.5px; %3"
- "background: transparent; border: none;")
- .arg(fincept::ui::colors::AMBER())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont());
-}
-inline QString kInputStyle() {
- return QString("QLineEdit { background: %1; border: 1px solid %2; color: %3; padding: 4px 8px;"
- " font-size: %4px; %5 }"
- "QLineEdit:focus { border-color: %6; }")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM(),
- fincept::ui::colors::TEXT_PRIMARY())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::BORDER_BRIGHT());
-}
-inline QString kComboStyle() {
- return QString("QComboBox { background: %1; color: %2; border: 1px solid %3; padding: 4px 8px;"
- " font-size: %4px; %5 }"
- "QComboBox::drop-down { border: none; }"
- "QComboBox QAbstractItemView { background: %1; color: %2; border: 1px solid %3;"
- " selection-background-color: %6; %5 }")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(),
- fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::BG_HOVER());
-}
-inline QString kSpinStyle() {
- return QString("QDoubleSpinBox { background: %1; color: %2; border: 1px solid %3; padding: 4px 8px;"
- " font-size: %4px; %5 }"
- "QDoubleSpinBox::up-button, QDoubleSpinBox::down-button { width: 14px; }")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::TEXT_PRIMARY(),
- fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont());
-}
-
-} // namespace
+#include <QVBoxLayout>
namespace fincept::screens {
+namespace algo_ns = fincept::algo;
-using namespace fincept::services::algo;
-
-// ── gather_from_layout ──────────────────────────────────────────────────────
-
-static QJsonArray gather_from_layout(QVBoxLayout* layout) {
- QJsonArray arr;
- for (int i = 0; i < layout->count(); ++i) {
- auto* item = layout->itemAt(i);
- auto* row = item ? item->widget() : nullptr;
- if (!row) continue;
- auto* ind_combo = qobject_cast<QComboBox*>(row->property("ind_combo").value<QObject*>());
- auto* field_combo = qobject_cast<QComboBox*>(row->property("field_combo").value<QObject*>());
- auto* op_combo = qobject_cast<QComboBox*>(row->property("op_combo").value<QObject*>());
- auto* val_spin = qobject_cast<QDoubleSpinBox*>(row->property("val_spin").value<QObject*>());
- if (!ind_combo || !field_combo || !op_combo || !val_spin) continue;
- QJsonObject cond;
- cond["indicator"] = ind_combo->currentData().toString();
- cond["field"] = field_combo->currentText();
- cond["operator"] = op_combo->currentText();
- cond["value"] = val_spin->value();
- cond["params"] = QJsonObject{};
- arr.append(cond);
- }
- return arr;
-}
-
-// ── Constructor ─────────────────────────────────────────────────────────────
-
-StrategyBuilderPanel::StrategyBuilderPanel(QWidget* parent) : QWidget(parent) {
+StrategyBuilderPanel::StrategyBuilderPanel(QWidget* parent)
+ : QWidget(parent) {
+ setObjectName(QStringLiteral("strategyBuilderPanel"));
build_ui();
connect_service();
- LOG_INFO("AlgoTrading", "StrategyBuilderPanel constructed");
}
-// ── Service connections ─────────────────────────────────────────────────────
+void StrategyBuilderPanel::build_ui() {
+ auto* main_layout = new QVBoxLayout(this);
+ main_layout->setContentsMargins(0, 0, 0, 0);
+ main_layout->setSpacing(0);
-void StrategyBuilderPanel::connect_service() {
- auto& svc = AlgoTradingService::instance();
- connect(&svc, &AlgoTradingService::strategy_saved, this, [this](const QString& id) {
- if (status_label_)
- status_label_->setText(QString("Strategy saved: %1").arg(id));
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::POSITIVE())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- });
- connect(&svc, &AlgoTradingService::backtest_result, this,
- &StrategyBuilderPanel::on_backtest_result);
- connect(&svc, &AlgoTradingService::error_occurred, this,
- &StrategyBuilderPanel::on_error);
-}
+ main_layout->addWidget(build_top_toolbar());
-// ── Condition row ───────────────────────────────────────────────────────────
-
-QWidget* StrategyBuilderPanel::build_condition_row(QWidget* parent) {
- auto* row = new QWidget(parent);
- row->setStyleSheet(QString("background: %1; border: 1px solid %2;")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM()));
- auto* hl = new QHBoxLayout(row);
- hl->setContentsMargins(6, 4, 6, 4);
- hl->setSpacing(4);
-
- auto* ind_combo = new QComboBox(row);
- ind_combo->setStyleSheet(kComboStyle());
- ind_combo->setFixedHeight(28);
- ind_combo->setMinimumWidth(120);
- const auto indicators = algo_indicators();
- for (const auto& ind : indicators)
- ind_combo->addItem(ind.label, ind.id);
-
- auto* field_combo = new QComboBox(row);
- field_combo->setStyleSheet(kComboStyle());
- field_combo->setFixedHeight(28);
- field_combo->setMinimumWidth(90);
-
- connect(ind_combo, QOverload<int>::of(&QComboBox::currentIndexChanged), row,
- [field_combo, indicators](int idx) {
- field_combo->clear();
- if (idx >= 0 && idx < indicators.size())
- field_combo->addItems(indicators[idx].fields);
- });
+ auto* splitter = new QSplitter(Qt::Horizontal, this);
+ splitter->setObjectName(QStringLiteral("builderSplitter"));
+ splitter->addWidget(build_left_panel());
+ splitter->addWidget(build_right_panel());
+ splitter->setStretchFactor(0, 45);
+ splitter->setStretchFactor(1, 55);
- auto* op_combo = new QComboBox(row);
- op_combo->setStyleSheet(kComboStyle());
- op_combo->setFixedHeight(28);
- op_combo->setMinimumWidth(100);
- op_combo->addItems(algo_operators());
-
- auto* val_spin = new QDoubleSpinBox(row);
- val_spin->setStyleSheet(kSpinStyle());
- val_spin->setFixedHeight(28);
- val_spin->setMinimumWidth(90);
- val_spin->setRange(-1e9, 1e9);
- val_spin->setDecimals(4);
- val_spin->setValue(0);
-
- auto* rm_btn = new QPushButton("X", row);
- rm_btn->setFixedSize(28, 28);
- rm_btn->setCursor(Qt::PointingHandCursor);
- rm_btn->setStyleSheet(
- QString("QPushButton { background: transparent; color: %1; border: 1px solid %2;"
- " font-size: %3px; font-weight: 700; %4 }"
- "QPushButton:hover { color: %5; border-color: %5; }")
- .arg(fincept::ui::colors::TEXT_TERTIARY(), fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::NEGATIVE()));
- connect(rm_btn, &QPushButton::clicked, row, [row]() { row->deleteLater(); });
-
- hl->addWidget(ind_combo);
- hl->addWidget(field_combo);
- hl->addWidget(op_combo);
- hl->addWidget(val_spin);
- hl->addWidget(rm_btn);
-
- if (ind_combo->count() > 0)
- emit ind_combo->currentIndexChanged(0);
-
- row->setProperty("ind_combo", QVariant::fromValue(static_cast<QObject*>(ind_combo)));
- row->setProperty("field_combo", QVariant::fromValue(static_cast<QObject*>(field_combo)));
- row->setProperty("op_combo", QVariant::fromValue(static_cast<QObject*>(op_combo)));
- row->setProperty("val_spin", QVariant::fromValue(static_cast<QObject*>(val_spin)));
-
- return row;
+ main_layout->addWidget(splitter, 1);
}
-// ── Left pane: strategy editor ──────────────────────────────────────────────
+QWidget* StrategyBuilderPanel::build_top_toolbar() {
+ auto* toolbar = new QWidget(this);
+ toolbar->setObjectName(QStringLiteral("builderToolbar"));
+ toolbar->setFixedHeight(44);
+ auto* layout = new QHBoxLayout(toolbar);
+ layout->setContentsMargins(12, 4, 12, 4);
+ layout->setSpacing(8);
+
+ name_edit_ = new QLineEdit(this);
+ name_edit_->setObjectName(QStringLiteral("builderNameEdit"));
+ name_edit_->setPlaceholderText(tr("Strategy Name"));
+ name_edit_->setMinimumWidth(160);
+
+ desc_edit_ = new QLineEdit(this);
+ desc_edit_->setObjectName(QStringLiteral("builderDescEdit"));
+ desc_edit_->setPlaceholderText(tr("Description (optional)"));
+ desc_edit_->setMinimumWidth(160);
+
+ symbol_combo_ = new ui::algo::SymbolSearchCombo(this);
+ symbol_combo_->setMinimumWidth(120);
+
+ timeframe_combo_ = new QComboBox(this);
+ timeframe_combo_->setObjectName(QStringLiteral("builderTimeframe"));
+ for (const auto& tf : services::algo::algo_timeframes())
+ timeframe_combo_->addItem(tf);
+ timeframe_combo_->setCurrentText(QStringLiteral("5m"));
+
+ save_btn_ = new QPushButton(tr("Save"), this);
+ save_btn_->setObjectName(QStringLiteral("builderSaveBtn"));
+ backtest_btn_ = new QPushButton(tr("Backtest"), this);
+ backtest_btn_->setObjectName(QStringLiteral("builderBacktestBtn"));
+ deploy_btn_ = new QPushButton(tr("Deploy"), this);
+ deploy_btn_->setObjectName(QStringLiteral("builderDeployBtn"));
+
+ layout->addWidget(name_edit_);
+ layout->addWidget(desc_edit_);
+ layout->addWidget(symbol_combo_);
+ layout->addWidget(timeframe_combo_);
+ layout->addStretch();
+ layout->addWidget(save_btn_);
+ layout->addWidget(backtest_btn_);
+ layout->addWidget(deploy_btn_);
+
+ connect(save_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_save);
+ connect(backtest_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_backtest);
+ connect(deploy_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_deploy);
+
+ return toolbar;
+}
-QWidget* StrategyBuilderPanel::build_left_pane() {
- auto* pane = new QWidget(this);
- pane->setStyleSheet(
- QString("background: %1; border-right: 1px solid %2;")
- .arg(fincept::ui::colors::BG_BASE(), fincept::ui::colors::BORDER_DIM()));
+QWidget* StrategyBuilderPanel::build_left_panel() {
+ auto* scroll = new QScrollArea(this);
+ scroll->setObjectName(QStringLiteral("builderLeftScroll"));
+ scroll->setWidgetResizable(true);
+ scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- auto* root_layout = new QVBoxLayout(pane);
- root_layout->setContentsMargins(0, 0, 0, 0);
- root_layout->setSpacing(0);
+ auto* content = new QWidget(this);
+ auto* layout = new QVBoxLayout(content);
+ layout->setContentsMargins(12, 8, 12, 8);
+ layout->setSpacing(12);
- auto* scroll = new QScrollArea(pane);
- scroll->setWidgetResizable(true);
- scroll->setFrameShape(QFrame::NoFrame);
- scroll->setStyleSheet(
- QString("QScrollArea { background: %1; border: none; }"
- "QScrollBar:vertical { background: %1; width: 6px; }"
- "QScrollBar::handle:vertical { background: %2; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")
- .arg(fincept::ui::colors::BG_BASE(), fincept::ui::colors::BORDER_MED()));
-
- auto* content = new QWidget;
- content->setStyleSheet(QString("background: %1;").arg(fincept::ui::colors::BG_BASE()));
- auto* vl = new QVBoxLayout(content);
- vl->setContentsMargins(16, 12, 16, 12);
- vl->setSpacing(8);
-
- // ── Strategy Definition ─────────────────────────────────────────────────
- auto* id_sec = new QLabel("STRATEGY DEFINITION", content);
- id_sec->setStyleSheet(kSectionLabel());
- vl->addWidget(id_sec);
-
- auto* name_lbl = new QLabel("NAME", content);
- name_lbl->setStyleSheet(kLabelStyle());
- vl->addWidget(name_lbl);
- name_edit_ = new QLineEdit(content);
- name_edit_->setPlaceholderText("My Strategy");
- name_edit_->setStyleSheet(kInputStyle());
- name_edit_->setFixedHeight(30);
- vl->addWidget(name_edit_);
-
- auto* desc_lbl = new QLabel("DESCRIPTION", content);
- desc_lbl->setStyleSheet(kLabelStyle());
- vl->addWidget(desc_lbl);
- desc_edit_ = new QLineEdit(content);
- desc_edit_->setPlaceholderText("Strategy description...");
- desc_edit_->setStyleSheet(kInputStyle());
- desc_edit_->setFixedHeight(30);
- vl->addWidget(desc_edit_);
-
- auto* tf_lbl = new QLabel("TIMEFRAME", content);
- tf_lbl->setStyleSheet(kLabelStyle());
- vl->addWidget(tf_lbl);
- timeframe_combo_ = new QComboBox(content);
- timeframe_combo_->addItems(algo_timeframes());
- timeframe_combo_->setStyleSheet(kComboStyle());
- timeframe_combo_->setFixedHeight(30);
- vl->addWidget(timeframe_combo_);
-
- // ── Entry Conditions ────────────────────────────────────────────────────
- auto* entry_hdr = new QWidget(content);
- auto* entry_hdr_hl = new QHBoxLayout(entry_hdr);
- entry_hdr_hl->setContentsMargins(0, 8, 0, 0);
- entry_hdr_hl->setSpacing(8);
- auto* entry_lbl = new QLabel("ENTRY CONDITIONS", entry_hdr);
- entry_lbl->setStyleSheet(kSectionLabel());
- entry_hdr_hl->addWidget(entry_lbl);
- auto* entry_logic_lbl = new QLabel("Logic:", entry_hdr);
- entry_logic_lbl->setStyleSheet(kLabelStyle());
- entry_hdr_hl->addWidget(entry_logic_lbl);
- entry_logic_combo_ = new QComboBox(entry_hdr);
- entry_logic_combo_->addItems({"AND", "OR"});
- entry_logic_combo_->setStyleSheet(kComboStyle());
- entry_logic_combo_->setFixedHeight(26);
- entry_logic_combo_->setFixedWidth(80);
- entry_hdr_hl->addWidget(entry_logic_combo_);
- entry_hdr_hl->addStretch();
- vl->addWidget(entry_hdr);
-
- auto* entry_container = new QWidget(content);
- entry_conditions_layout_ = new QVBoxLayout(entry_container);
- entry_conditions_layout_->setContentsMargins(0, 0, 0, 0);
- entry_conditions_layout_->setSpacing(4);
- vl->addWidget(entry_container);
-
- auto* add_entry_btn = new QPushButton("+ ADD ENTRY CONDITION", content);
- add_entry_btn->setCursor(Qt::PointingHandCursor);
- add_entry_btn->setFixedHeight(28);
- add_entry_btn->setStyleSheet(
- QString("QPushButton { background: transparent; color: %1; border: 1px dashed %2;"
- " font-size: %3px; font-weight: 700; %4 }"
- "QPushButton:hover { color: %5; border-color: %5; }")
- .arg(fincept::ui::colors::TEXT_TERTIARY(), fincept::ui::colors::BORDER_DIM())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::AMBER()));
- connect(add_entry_btn, &QPushButton::clicked, this, [this, entry_container]() {
- entry_conditions_layout_->addWidget(build_condition_row(entry_container));
- });
- vl->addWidget(add_entry_btn);
-
- // ── Exit Conditions ─────────────────────────────────────────────────────
- auto* exit_hdr = new QWidget(content);
- auto* exit_hdr_hl = new QHBoxLayout(exit_hdr);
- exit_hdr_hl->setContentsMargins(0, 8, 0, 0);
- exit_hdr_hl->setSpacing(8);
- auto* exit_lbl = new QLabel("EXIT CONDITIONS", exit_hdr);
- exit_lbl->setStyleSheet(kSectionLabel());
- exit_hdr_hl->addWidget(exit_lbl);
- auto* exit_logic_lbl = new QLabel("Logic:", exit_hdr);
- exit_logic_lbl->setStyleSheet(kLabelStyle());
- exit_hdr_hl->addWidget(exit_logic_lbl);
- exit_logic_combo_ = new QComboBox(exit_hdr);
- exit_logic_combo_->addItems({"AND", "OR"});
- exit_logic_combo_->setStyleSheet(kComboStyle());
- exit_logic_combo_->setFixedHeight(26);
- exit_logic_combo_->setFixedWidth(80);
- exit_hdr_hl->addWidget(exit_logic_combo_);
- exit_hdr_hl->addStretch();
- vl->addWidget(exit_hdr);
-
- auto* exit_container = new QWidget(content);
- exit_conditions_layout_ = new QVBoxLayout(exit_container);
- exit_conditions_layout_->setContentsMargins(0, 0, 0, 0);
- exit_conditions_layout_->setSpacing(4);
- vl->addWidget(exit_container);
-
- auto* add_exit_btn = new QPushButton("+ ADD EXIT CONDITION", content);
- add_exit_btn->setCursor(Qt::PointingHandCursor);
- add_exit_btn->setFixedHeight(28);
- add_exit_btn->setStyleSheet(add_entry_btn->styleSheet());
- connect(add_exit_btn, &QPushButton::clicked, this, [this, exit_container]() {
- exit_conditions_layout_->addWidget(build_condition_row(exit_container));
- });
- vl->addWidget(add_exit_btn);
-
- // ── Risk Management ─────────────────────────────────────────────────────
- auto* risk_lbl = new QLabel("RISK MANAGEMENT", content);
- risk_lbl->setStyleSheet(kSectionLabel());
- vl->addWidget(risk_lbl);
-
- auto* risk_grid = new QWidget(content);
- auto* rgl = new QHBoxLayout(risk_grid);
- rgl->setContentsMargins(0, 0, 0, 0);
- rgl->setSpacing(12);
-
- auto make_risk_field = [&](const QString& label, double def_val) -> QDoubleSpinBox* {
- auto* col = new QWidget(risk_grid);
- auto* cvl = new QVBoxLayout(col);
- cvl->setContentsMargins(0, 0, 0, 0);
- cvl->setSpacing(2);
- auto* lbl = new QLabel(label, col);
- lbl->setStyleSheet(kLabelStyle());
- cvl->addWidget(lbl);
- auto* spin = new QDoubleSpinBox(col);
- spin->setStyleSheet(kSpinStyle());
- spin->setFixedHeight(30);
- spin->setRange(0.0, 100.0);
- spin->setDecimals(2);
- spin->setSuffix(" %");
- spin->setValue(def_val);
- spin->setSpecialValueText("DISABLED");
- cvl->addWidget(spin);
- rgl->addWidget(col);
- return spin;
- };
+ entry_section_ = new ui::algo::ConditionSection(
+ ui::algo::ConditionSection::Type::Entry, this);
+ exit_section_ = new ui::algo::ConditionSection(
+ ui::algo::ConditionSection::Type::Exit, this);
+ risk_panel_ = new ui::algo::RiskManagementPanel(this);
- stop_loss_spin_ = make_risk_field("STOP LOSS %", 0.0);
- take_profit_spin_ = make_risk_field("TAKE PROFIT %", 0.0);
- trailing_stop_spin_ = make_risk_field("TRAILING STOP %", 0.0);
- vl->addWidget(risk_grid);
-
- vl->addStretch();
-
- // ── Save button ─────────────────────────────────────────────────────────
- auto* save_btn = new QPushButton("SAVE STRATEGY", content);
- save_btn->setCursor(Qt::PointingHandCursor);
- save_btn->setFixedHeight(36);
- save_btn->setStyleSheet(
- QString("QPushButton { background: rgba(217,119,6,0.1); color: %1; border: 1px solid %1;"
- " font-size: %2px; font-weight: 700; %3 padding: 6px 24px; }"
- "QPushButton:hover { background: %1; color: %4; }")
- .arg(fincept::ui::colors::AMBER())
- .arg(fincept::ui::fonts::DATA)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::BG_BASE()));
- connect(save_btn, &QPushButton::clicked, this, &StrategyBuilderPanel::on_save);
- vl->addWidget(save_btn);
+ layout->addWidget(entry_section_);
+ layout->addWidget(exit_section_);
+ layout->addWidget(risk_panel_);
+ layout->addStretch();
scroll->setWidget(content);
- root_layout->addWidget(scroll);
- return pane;
+ return scroll;
}
-// ── Right pane: backtest workbench ──────────────────────────────────────────
-
-QWidget* StrategyBuilderPanel::build_right_pane() {
- auto* pane = new QWidget(this);
- pane->setStyleSheet(QString("background: %1;").arg(fincept::ui::colors::BG_BASE()));
-
- auto* root_layout = new QVBoxLayout(pane);
- root_layout->setContentsMargins(0, 0, 0, 0);
- root_layout->setSpacing(0);
-
- auto* scroll = new QScrollArea(pane);
- scroll->setWidgetResizable(true);
- scroll->setFrameShape(QFrame::NoFrame);
- scroll->setStyleSheet(
- QString("QScrollArea { background: %1; border: none; }"
- "QScrollBar:vertical { background: %1; width: 6px; }"
- "QScrollBar::handle:vertical { background: %2; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }")
- .arg(fincept::ui::colors::BG_BASE(), fincept::ui::colors::BORDER_MED()));
-
- auto* content = new QWidget;
- content->setStyleSheet(QString("background: %1;").arg(fincept::ui::colors::BG_BASE()));
- auto* vl = new QVBoxLayout(content);
- vl->setContentsMargins(16, 12, 16, 12);
- vl->setSpacing(8);
-
- // ── Backtest Parameters ─────────────────────────────────────────────────
- auto* bt_sec = new QLabel("BACKTEST PARAMETERS", content);
- bt_sec->setStyleSheet(kSectionLabel());
- vl->addWidget(bt_sec);
-
- // 2×2 grid of params
- auto* params_grid = new QWidget(content);
- auto* params_gl = new QGridLayout(params_grid);
- params_gl->setContentsMargins(0, 0, 0, 0);
- params_gl->setSpacing(8);
-
- auto make_param_col = [&](const QString& label_text, QWidget* input) -> QWidget* {
- auto* col = new QWidget(params_grid);
- auto* cvl = new QVBoxLayout(col);
- cvl->setContentsMargins(0, 0, 0, 0);
- cvl->setSpacing(2);
- auto* lbl = new QLabel(label_text, col);
- lbl->setStyleSheet(kLabelStyle());
- cvl->addWidget(lbl);
- input->setParent(col);
- cvl->addWidget(input);
- return col;
- };
-
- bt_symbol_ = new QLineEdit;
- bt_symbol_->setPlaceholderText("RELIANCE");
- bt_symbol_->setStyleSheet(kInputStyle());
- bt_symbol_->setFixedHeight(30);
- params_gl->addWidget(make_param_col("SYMBOL", bt_symbol_), 0, 0);
-
- bt_capital_ = new QDoubleSpinBox;
- bt_capital_->setStyleSheet(kSpinStyle());
- bt_capital_->setFixedHeight(30);
- bt_capital_->setRange(100, 1e9);
+QWidget* StrategyBuilderPanel::build_right_panel() {
+ auto* right = new QWidget(this);
+ auto* layout = new QVBoxLayout(right);
+ layout->setContentsMargins(12, 8, 12, 8);
+ layout->setSpacing(8);
+
+ // Chart placeholder
+ auto* chart_placeholder = new QWidget(this);
+ chart_placeholder->setObjectName(QStringLiteral("builderChartPlaceholder"));
+ chart_placeholder->setMinimumHeight(200);
+ auto* chart_layout = new QVBoxLayout(chart_placeholder);
+ auto* chart_label = new QLabel(tr("Select a symbol and deploy to view live chart"), this);
+ chart_label->setObjectName(QStringLiteral("builderChartLabel"));
+ chart_label->setAlignment(Qt::AlignCenter);
+ chart_layout->addWidget(chart_label);
+ layout->addWidget(chart_placeholder, 1);
+
+ // Backtest params
+ auto* bt_section = new QLabel(tr("BACKTEST"), this);
+ bt_section->setObjectName(QStringLiteral("builderBtHeader"));
+ layout->addWidget(bt_section);
+
+ auto* bt_grid = new QGridLayout();
+ bt_grid->setSpacing(6);
+
+ bt_capital_ = new QDoubleSpinBox(this);
+ bt_capital_->setObjectName(QStringLiteral("builderBtCapital"));
+ bt_capital_->setRange(1000, 100000000);
bt_capital_->setDecimals(0);
- bt_capital_->setPrefix("$ ");
bt_capital_->setValue(100000);
- params_gl->addWidget(make_param_col("CAPITAL ($)", bt_capital_), 0, 1);
-
- bt_start_date_ = new QLineEdit;
- bt_start_date_->setPlaceholderText("YYYY-MM-DD");
- bt_start_date_->setText("2024-01-01");
- bt_start_date_->setStyleSheet(kInputStyle());
- bt_start_date_->setFixedHeight(30);
- params_gl->addWidget(make_param_col("START DATE", bt_start_date_), 1, 0);
-
- bt_end_date_ = new QLineEdit;
- bt_end_date_->setPlaceholderText("YYYY-MM-DD");
- bt_end_date_->setText("2025-01-01");
- bt_end_date_->setStyleSheet(kInputStyle());
- bt_end_date_->setFixedHeight(30);
- params_gl->addWidget(make_param_col("END DATE", bt_end_date_), 1, 1);
-
- vl->addWidget(params_grid);
-
- // RUN BACKTEST button
- auto* bt_btn = new QPushButton("RUN BACKTEST", content);
- bt_btn->setCursor(Qt::PointingHandCursor);
- bt_btn->setFixedHeight(36);
- bt_btn->setStyleSheet(
- QString("QPushButton { background: rgba(8,145,178,0.1); color: %1; border: 1px solid %1;"
- " font-size: %2px; font-weight: 700; %3 padding: 6px 24px; }"
- "QPushButton:hover { background: %1; color: %4; }")
- .arg(fincept::ui::colors::CYAN())
- .arg(fincept::ui::fonts::DATA)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::BG_BASE()));
- connect(bt_btn, &QPushButton::clicked, this, &StrategyBuilderPanel::on_backtest);
- vl->addWidget(bt_btn);
-
- auto* open_terminal_btn = new QPushButton("OPEN IN BACKTESTING TERMINAL", content);
- open_terminal_btn->setCursor(Qt::PointingHandCursor);
- open_terminal_btn->setFixedHeight(30);
- open_terminal_btn->setStyleSheet(
- QString("QPushButton { background:transparent; color:%1; border:1px solid %2;"
- "font-size:%3px; font-family:%4; font-weight:700; letter-spacing:0.5px; }"
- "QPushButton:hover { background:%1; color:%5; }")
- .arg(fincept::ui::colors::AMBER(), fincept::ui::colors::AMBER_DIM())
- .arg(fincept::ui::fonts::TINY)
- .arg(kMonoFont())
- .arg(fincept::ui::colors::BG_BASE()));
- connect(open_terminal_btn, &QPushButton::clicked, this, [this]() {
- QString symbol = bt_symbol_->text().trimmed();
- if (symbol.isEmpty()) return;
- QJsonObject config;
- QJsonArray symbols;
- symbols.append(symbol);
- config["symbols"] = symbols;
- if (bt_capital_)
- config["initialCapital"] = bt_capital_->value();
- fincept::services::backtest::BacktestingService::instance().set_pending_portfolio_config(config);
- fincept::EventBus::instance().publish("nav.switch_screen", {{"screen_id", QString("backtesting")}});
- });
- vl->addWidget(open_terminal_btn);
-
- // Status label
- status_label_ = new QLabel("", content);
- status_label_->setWordWrap(true);
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::TEXT_TERTIARY())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- vl->addWidget(status_label_);
-
- // ── Results area ────────────────────────────────────────────────────────
- auto* results_container = new QWidget(content);
- results_layout_ = new QVBoxLayout(results_container);
- results_layout_->setContentsMargins(0, 4, 0, 0);
- results_layout_->setSpacing(8);
-
- // Empty state
- bt_empty_label_ = new QLabel("Run a backtest to see results", results_container);
- bt_empty_label_->setAlignment(Qt::AlignCenter);
- bt_empty_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none; padding: 24px;")
- .arg(fincept::ui::colors::TEXT_TERTIARY())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- results_layout_->addWidget(bt_empty_label_);
-
- // KPI grid — hidden until first result
- kpi_grid_widget_ = new QWidget(results_container);
+ bt_capital_->setPrefix(QStringLiteral("$ "));
+
+ bt_start_date_ = new QLineEdit(this);
+ bt_start_date_->setObjectName(QStringLiteral("builderBtStart"));
+ bt_start_date_->setPlaceholderText(QStringLiteral("2024-01-01"));
+ bt_start_date_->setText(QStringLiteral("2024-01-01"));
+
+ bt_end_date_ = new QLineEdit(this);
+ bt_end_date_->setObjectName(QStringLiteral("builderBtEnd"));
+ bt_end_date_->setPlaceholderText(QStringLiteral("2024-12-31"));
+ bt_end_date_->setText(QStringLiteral("2024-12-31"));
+
+ bt_grid->addWidget(new QLabel(tr("Capital"), this), 0, 0);
+ bt_grid->addWidget(bt_capital_, 0, 1);
+ bt_grid->addWidget(new QLabel(tr("Start"), this), 1, 0);
+ bt_grid->addWidget(bt_start_date_, 1, 1);
+ bt_grid->addWidget(new QLabel(tr("End"), this), 2, 0);
+ bt_grid->addWidget(bt_end_date_, 2, 1);
+ layout->addLayout(bt_grid);
+
+ status_label_ = new QLabel(this);
+ status_label_->setObjectName(QStringLiteral("builderStatus"));
+ layout->addWidget(status_label_);
+
+ // KPI grid (hidden until backtest runs)
+ kpi_grid_widget_ = new QWidget(this);
+ kpi_grid_widget_->setObjectName(QStringLiteral("builderKpiGrid"));
kpi_grid_widget_->setVisible(false);
- auto* kpi_gl = new QGridLayout(kpi_grid_widget_);
- kpi_gl->setContentsMargins(0, 0, 0, 0);
- kpi_gl->setSpacing(8);
+ auto* kpi_grid = new QGridLayout(kpi_grid_widget_);
+ kpi_grid->setSpacing(8);
- // Helper to build one KPI card and wire up its labels
- struct KpiDef {
- QString label;
- QLabel** val_out;
- QLabel** sub_out;
+ auto make_kpi = [&](int row, int col, const QString& title) -> std::pair<QLabel*, QLabel*> {
+ auto* card = new QWidget(kpi_grid_widget_);
+ card->setObjectName(QStringLiteral("kpiCard"));
+ auto* card_layout = new QVBoxLayout(card);
+ card_layout->setContentsMargins(8, 6, 8, 6);
+ card_layout->setSpacing(2);
+
+ auto* title_lbl = new QLabel(title, card);
+ title_lbl->setObjectName(QStringLiteral("kpiTitle"));
+ auto* val_lbl = new QLabel(QStringLiteral("--"), card);
+ val_lbl->setObjectName(QStringLiteral("kpiValue"));
+ auto* sub_lbl = new QLabel(card);
+ sub_lbl->setObjectName(QStringLiteral("kpiSub"));
+
+ card_layout->addWidget(title_lbl);
+ card_layout->addWidget(val_lbl);
+ card_layout->addWidget(sub_lbl);
+ kpi_grid->addWidget(card, row, col);
+ return {val_lbl, sub_lbl};
};
- QList<KpiDef> kpi_defs = {
- {"TOTAL RETURN", &kpi_total_return_val_, &kpi_total_return_sub_},
- {"SHARPE RATIO", &kpi_sharpe_val_, &kpi_sharpe_sub_},
- {"MAX DRAWDOWN", &kpi_max_dd_val_, &kpi_max_dd_sub_},
- {"WIN RATE", &kpi_win_rate_val_, &kpi_win_rate_sub_},
- {"TOTAL TRADES", &kpi_trades_val_, &kpi_trades_sub_},
- {"PROFIT FACTOR", &kpi_profit_factor_val_, &kpi_profit_factor_sub_},
- };
+ auto [tr_v, tr_s] = make_kpi(0, 0, tr("TOTAL RETURN"));
+ kpi_total_return_val_ = tr_v; kpi_total_return_sub_ = tr_s;
+ auto [sh_v, sh_s] = make_kpi(0, 1, tr("SHARPE RATIO"));
+ kpi_sharpe_val_ = sh_v; kpi_sharpe_sub_ = sh_s;
+ auto [dd_v, dd_s] = make_kpi(0, 2, tr("MAX DRAWDOWN"));
+ kpi_max_dd_val_ = dd_v; kpi_max_dd_sub_ = dd_s;
+ auto [wr_v, wr_s] = make_kpi(1, 0, tr("WIN RATE"));
+ kpi_win_rate_val_ = wr_v; kpi_win_rate_sub_ = wr_s;
+ auto [tt_v, tt_s] = make_kpi(1, 1, tr("TOTAL TRADES"));
+ kpi_trades_val_ = tt_v; kpi_trades_sub_ = tt_s;
+ auto [pf_v, pf_s] = make_kpi(1, 2, tr("PROFIT FACTOR"));
+ kpi_profit_factor_val_ = pf_v; kpi_profit_factor_sub_ = pf_s;
+
+ layout->addWidget(kpi_grid_widget_);
+ layout->addStretch();
+
+ return right;
+}
- for (int i = 0; i < kpi_defs.size(); ++i) {
- const auto& def = kpi_defs[i];
+void StrategyBuilderPanel::connect_service() {
+ auto& svc = services::algo::AlgoTradingService::instance();
+ connect(&svc, &services::algo::AlgoTradingService::backtest_result,
+ this, &StrategyBuilderPanel::on_backtest_result);
+ connect(&svc, &services::algo::AlgoTradingService::error_occurred,
+ this, &StrategyBuilderPanel::on_error);
+ connect(&svc, &services::algo::AlgoTradingService::strategy_saved,
+ this, [this](const QString& id) {
+ status_label_->setText(tr("Strategy saved: %1").arg(id));
+ });
+}
- auto* card = new QWidget(kpi_grid_widget_);
- card->setObjectName("btKpiCard");
- card->setStyleSheet(
- QString("#btKpiCard { background:%1; border:1px solid %2; border-radius:4px; }")
- .arg(fincept::ui::colors::BG_SURFACE(), fincept::ui::colors::BORDER_DIM()));
-
- auto* cl = new QVBoxLayout(card);
- cl->setContentsMargins(12, 10, 12, 10);
- cl->setSpacing(2);
-
- auto* lbl = new QLabel(def.label, card);
- lbl->setStyleSheet(
- QString("color:%1; font-size:%2px; font-family:%3; font-weight:600; letter-spacing:1px;"
- " background:transparent; border:none;")
- .arg(fincept::ui::colors::TEXT_TERTIARY())
- .arg(fincept::ui::fonts::TINY)
- .arg(fincept::ui::fonts::DATA_FAMILY));
- cl->addWidget(lbl);
-
- auto* val = new QLabel("—", card);
- val->setStyleSheet(
- QString("color:%1; font-size:%2px; font-family:%3; font-weight:800;"
- " background:transparent; border:none;")
- .arg(fincept::ui::colors::TEXT_PRIMARY())
- .arg(fincept::ui::fonts::HEADER + 2)
- .arg(fincept::ui::fonts::DATA_FAMILY));
- cl->addWidget(val);
- *def.val_out = val;
-
- auto* sub = new QLabel("", card);
- sub->setStyleSheet(
- QString("color:%1; font-size:%2px; font-family:%3;"
- " background:transparent; border:none;")
- .arg(fincept::ui::colors::TEXT_TERTIARY())
- .arg(fincept::ui::fonts::TINY)
- .arg(fincept::ui::fonts::DATA_FAMILY));
- cl->addWidget(sub);
- *def.sub_out = sub;
-
- kpi_gl->addWidget(card, i / 3, i % 3);
+void StrategyBuilderPanel::on_save() {
+ if (name_edit_->text().trimmed().isEmpty()) {
+ status_label_->setText(tr("Please enter a strategy name."));
+ return;
}
- results_layout_->addWidget(kpi_grid_widget_);
- vl->addWidget(results_container);
- vl->addStretch();
-
- scroll->setWidget(content);
- root_layout->addWidget(scroll);
- return pane;
+ services::algo::AlgoStrategy strat;
+ strat.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ strat.name = name_edit_->text().trimmed();
+ strat.description = desc_edit_->text().trimmed();
+ strat.timeframe = timeframe_combo_->currentText();
+ strat.entry_conditions = entry_section_->conditions();
+ strat.exit_conditions = exit_section_->conditions();
+ strat.entry_logic = entry_section_->combined_logic();
+ strat.exit_logic = exit_section_->combined_logic();
+ strat.stop_loss = risk_panel_->stop_loss();
+ strat.take_profit = risk_panel_->take_profit();
+ strat.trailing_stop = risk_panel_->trailing_stop();
+
+ services::algo::AlgoTradingService::instance().save_strategy(strat);
+ status_label_->setText(tr("Saving strategy..."));
}
-// ── build_ui: QSplitter shell ────────────────────────────────────────────────
+void StrategyBuilderPanel::on_backtest() {
+ if (name_edit_->text().trimmed().isEmpty()) {
+ status_label_->setText(tr("Save strategy first."));
+ return;
+ }
-void StrategyBuilderPanel::build_ui() {
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
+ // Save first, then backtest
+ on_save();
+ QString symbol = symbol_combo_->currentText().trimmed();
+ if (symbol.isEmpty()) symbol = QStringLiteral("RELIANCE");
- auto* splitter = new QSplitter(Qt::Horizontal, this);
- splitter->setHandleWidth(4);
- splitter->setStyleSheet(
- QString("QSplitter::handle { background: %1; }")
- .arg(fincept::ui::colors::BORDER_DIM()));
- splitter->addWidget(build_left_pane());
- splitter->addWidget(build_right_pane());
- splitter->setStretchFactor(0, 2); // left ~40%
- splitter->setStretchFactor(1, 3); // right ~60%
-
- root->addWidget(splitter, 1);
+ services::algo::AlgoTradingService::instance().run_backtest(
+ QString(), symbol, bt_start_date_->text(), bt_end_date_->text(),
+ bt_capital_->value());
+ status_label_->setText(tr("Running backtest..."));
}
-// ── clear_results ────────────────────────────────────────────────────────────
+void StrategyBuilderPanel::on_deploy() {
+ if (name_edit_->text().trimmed().isEmpty()) {
+ status_label_->setText(tr("Save strategy first."));
+ return;
+ }
-void StrategyBuilderPanel::clear_results() {
- bt_empty_label_->setVisible(true);
- kpi_grid_widget_->setVisible(false);
+ // Build strategy from current UI state
+ services::algo::AlgoStrategy strat;
+ strat.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ strat.name = name_edit_->text().trimmed();
+ strat.description = desc_edit_->text().trimmed();
+ strat.timeframe = timeframe_combo_->currentText();
+ strat.entry_conditions = entry_section_->conditions();
+ strat.exit_conditions = exit_section_->conditions();
+ strat.entry_logic = entry_section_->combined_logic();
+ strat.exit_logic = exit_section_->combined_logic();
+ strat.stop_loss = risk_panel_->stop_loss();
+ strat.take_profit = risk_panel_->take_profit();
+ strat.trailing_stop = risk_panel_->trailing_stop();
+
+ auto* dialog = new AlgoDeployDialog(strat, this);
+ if (dialog->exec() == QDialog::Accepted) {
+ auto deployment = dialog->deployment();
+ deployment.quantity = risk_panel_->quantity();
+ deployment.max_order_value = risk_panel_->max_order_value();
+
+ // Save strategy first
+ services::algo::AlgoTradingService::instance().save_strategy(strat);
+
+ // Deploy via C++ engine
+ algo_ns::AlgoEngine::instance().start_deployment(deployment, strat);
+ status_label_->setText(tr("Deploying strategy..."));
+
+ // Switch to deployments tab handled by AlgoTradingScreen
+ }
+ dialog->deleteLater();
}
-// ── display_backtest_result — Quant Lab KPI card style ───────────────────────
+void StrategyBuilderPanel::on_backtest_result(const QJsonObject& payload) {
+ status_label_->setText(tr("Backtest complete."));
+ display_backtest_result(payload);
+ LOG_INFO("AlgoTrading", "Backtest result displayed");
+}
+
+void StrategyBuilderPanel::on_error(const QString& context, const QString& msg) {
+ status_label_->setText(QStringLiteral("[%1] %2").arg(context, msg));
+}
void StrategyBuilderPanel::display_backtest_result(const QJsonObject& payload) {
- bt_empty_label_->setVisible(false);
kpi_grid_widget_->setVisible(true);
- double total_return = payload.value("total_return").toDouble();
- double sharpe = payload.value("sharpe_ratio").toDouble();
- double max_dd = payload.value("max_drawdown").toDouble();
- int total_trades = payload.value("total_trades").toInt();
- double win_rate = payload.value("win_rate").toDouble();
+ double total_return = payload.value("total_return").toDouble();
+ double sharpe = payload.value("sharpe_ratio").toDouble();
+ double max_dd = payload.value("max_drawdown").toDouble();
+ int total_trades = payload.value("total_trades").toInt();
+ double win_rate = payload.value("win_rate").toDouble();
double profit_factor = payload.value("profit_factor").toDouble();
- double final_val = payload.value("final_value").toDouble();
-
- auto set_kpi = [](QLabel* lbl, const QString& text, const QString& color) {
- lbl->setText(text);
- lbl->setStyleSheet(
- QString("color:%1; font-size:%2px; font-family:%3; font-weight:800;"
- " background:transparent; border:none;")
- .arg(color)
- .arg(fincept::ui::fonts::HEADER + 2)
- .arg(fincept::ui::fonts::DATA_FAMILY));
- };
+ double final_val = payload.value("final_value").toDouble();
- // TOTAL RETURN
- set_kpi(kpi_total_return_val_,
- QString("%1%2%").arg(total_return >= 0 ? "+" : "").arg(total_return, 0, 'f', 2),
- total_return >= 0 ? fincept::ui::colors::POSITIVE : fincept::ui::colors::NEGATIVE);
- kpi_total_return_sub_->setText(
- QString("Final: $%1").arg(final_val, 0, 'f', 0));
+ kpi_total_return_val_->setText(
+ QString("%1%2%").arg(total_return >= 0 ? "+" : "").arg(total_return, 0, 'f', 2));
+ kpi_total_return_sub_->setText(QString("Final: $%1").arg(final_val, 0, 'f', 0));
- // SHARPE
- set_kpi(kpi_sharpe_val_, QString::number(sharpe, 'f', 3),
- sharpe >= 0.5 ? fincept::ui::colors::POSITIVE : fincept::ui::colors::NEGATIVE);
+ kpi_sharpe_val_->setText(QString::number(sharpe, 'f', 3));
kpi_sharpe_sub_->setText(sharpe >= 1.0 ? "Excellent" : sharpe >= 0.5 ? "Good" : "Weak");
- // MAX DRAWDOWN (always red)
- set_kpi(kpi_max_dd_val_,
- QString("-%1%").arg(qAbs(max_dd), 0, 'f', 2),
- fincept::ui::colors::NEGATIVE);
+ kpi_max_dd_val_->setText(QString("-%1%").arg(qAbs(max_dd), 0, 'f', 2));
kpi_max_dd_sub_->setText("Max Drawdown");
- // WIN RATE
- set_kpi(kpi_win_rate_val_,
- QString("%1%").arg(win_rate, 0, 'f', 1),
- win_rate >= 50.0 ? fincept::ui::colors::POSITIVE : fincept::ui::colors::NEGATIVE);
+ kpi_win_rate_val_->setText(QString("%1%").arg(win_rate, 0, 'f', 1));
kpi_win_rate_sub_->setText(win_rate >= 50.0 ? "Above average" : "Below average");
- // TOTAL TRADES
- set_kpi(kpi_trades_val_, QString::number(total_trades), fincept::ui::colors::TEXT_PRIMARY);
+ kpi_trades_val_->setText(QString::number(total_trades));
kpi_trades_sub_->setText("Total trades");
- // PROFIT FACTOR
- set_kpi(kpi_profit_factor_val_, QString::number(profit_factor, 'f', 2),
- profit_factor >= 1.0 ? fincept::ui::colors::POSITIVE : fincept::ui::colors::NEGATIVE);
- kpi_profit_factor_sub_->setText(profit_factor >= 1.5 ? "Strong" : profit_factor >= 1.0 ? "Profitable" : "Losing");
-}
-
-// ── on_backtest_result ───────────────────────────────────────────────────────
-
-void StrategyBuilderPanel::on_backtest_result(const QJsonObject& payload) {
- status_label_->setText("Backtest complete.");
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::POSITIVE())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- display_backtest_result(payload);
- LOG_INFO("AlgoTrading", "Backtest result displayed");
+ kpi_profit_factor_val_->setText(QString::number(profit_factor, 'f', 2));
+ kpi_profit_factor_sub_->setText(
+ profit_factor >= 1.5 ? "Strong" : profit_factor >= 1.0 ? "Profitable" : "Losing");
}
-// ── on_save ──────────────────────────────────────────────────────────────────
-
-void StrategyBuilderPanel::on_save() {
- if (name_edit_->text().trimmed().isEmpty()) {
- status_label_->setText("Strategy name is required.");
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::NEGATIVE())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- return;
- }
-
- AlgoStrategy strategy;
- strategy.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
- strategy.name = name_edit_->text().trimmed();
- strategy.description = desc_edit_->text().trimmed();
- strategy.timeframe = timeframe_combo_->currentText();
- strategy.entry_conditions = gather_from_layout(entry_conditions_layout_);
- strategy.exit_conditions = gather_from_layout(exit_conditions_layout_);
- strategy.entry_logic = entry_logic_combo_->currentText();
- strategy.exit_logic = exit_logic_combo_->currentText();
- strategy.stop_loss = stop_loss_spin_->value();
- strategy.take_profit = take_profit_spin_->value();
- strategy.trailing_stop = trailing_stop_spin_->value();
-
- status_label_->setText("Saving...");
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::TEXT_SECONDARY())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
-
- AlgoTradingService::instance().save_strategy(strategy);
- LOG_INFO("AlgoTrading", QString("Saving strategy: %1").arg(strategy.name));
-
- {
- QJsonObject json;
- json["id"] = strategy.id;
- json["name"] = strategy.name;
- json["description"] = strategy.description;
- json["timeframe"] = strategy.timeframe;
- json["entry_logic"] = strategy.entry_logic;
- json["exit_logic"] = strategy.exit_logic;
- json["stop_loss"] = strategy.stop_loss;
- json["take_profit"] = strategy.take_profit;
- json["trailing_stop"] = strategy.trailing_stop;
-
- QJsonArray entry_arr;
- for (const auto& c : strategy.entry_conditions) entry_arr.append(c);
- json["entry_conditions"] = entry_arr;
-
- QJsonArray exit_arr;
- for (const auto& c : strategy.exit_conditions) exit_arr.append(c);
- json["exit_conditions"] = exit_arr;
-
- QString safe_name = strategy.name;
- safe_name.replace(QRegularExpression("[^a-zA-Z0-9_\\-]"), "_");
- QString dest = services::FileManagerService::instance().storage_dir() + "/" +
- safe_name + "_" + strategy.id.left(8) + ".json";
-
- QFile f(dest);
- if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
- f.write(QJsonDocument(json).toJson(QJsonDocument::Indented));
- f.close();
- services::FileManagerService::instance().register_file(
- safe_name + "_" + strategy.id.left(8) + ".json",
- strategy.name + ".json", QFileInfo(dest).size(),
- "application/json", "algo_trading");
- }
- }
-}
-
-// ── on_backtest ──────────────────────────────────────────────────────────────
-
-void StrategyBuilderPanel::on_backtest() {
- QString symbol = bt_symbol_->text().trimmed();
- if (symbol.isEmpty()) {
- status_label_->setText("Enter a symbol for backtesting.");
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::NEGATIVE())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- return;
- }
-
- status_label_->setText("Running backtest...");
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::CYAN())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
-
- QString start_date = bt_start_date_->text().trimmed();
- QString end_date = bt_end_date_->text().trimmed();
- if (start_date.isEmpty()) start_date = "2024-01-01";
- if (end_date.isEmpty()) end_date = "2025-01-01";
-
- QString strat_id = name_edit_->text().trimmed();
- double capital = bt_capital_->value();
-
- AlgoTradingService::instance().run_backtest(strat_id, symbol, start_date, end_date, capital);
- LOG_INFO("AlgoTrading", QString("Backtest requested: %1 on %2").arg(strat_id, symbol));
-}
-
-// ── on_error ─────────────────────────────────────────────────────────────────
-
-void StrategyBuilderPanel::on_error(const QString& context, const QString& msg) {
- if (status_label_) {
- status_label_->setText(QString("Error [%1]: %2").arg(context, msg));
- status_label_->setStyleSheet(
- QString("color: %1; font-size: %2px; %3 background: transparent; border: none;")
- .arg(fincept::ui::colors::NEGATIVE())
- .arg(fincept::ui::fonts::SMALL)
- .arg(kMonoFont()));
- }
+void StrategyBuilderPanel::clear_results() {
+ kpi_grid_widget_->setVisible(false);
}
-// ── Draft persistence ────────────────────────────────────────────────────────
-
QVariantMap StrategyBuilderPanel::save_draft() const {
- QVariantMap d;
- if (name_edit_) d["name"] = name_edit_->text();
- if (desc_edit_) d["desc"] = desc_edit_->text();
- if (bt_symbol_) d["bt_symbol"] = bt_symbol_->text();
- if (bt_start_date_) d["bt_start"] = bt_start_date_->text();
- if (bt_end_date_) d["bt_end"] = bt_end_date_->text();
- if (kpi_total_return_val_ && !kpi_total_return_val_->text().isEmpty()) {
- d["kpi_return"] = kpi_total_return_val_->text();
- d["kpi_sharpe"] = kpi_sharpe_val_ ? kpi_sharpe_val_->text() : QString();
- d["kpi_dd"] = kpi_max_dd_val_ ? kpi_max_dd_val_->text() : QString();
- d["kpi_win"] = kpi_win_rate_val_ ? kpi_win_rate_val_->text() : QString();
- d["kpi_trades"] = kpi_trades_val_ ? kpi_trades_val_->text() : QString();
- d["kpi_pf"] = kpi_profit_factor_val_ ? kpi_profit_factor_val_->text() : QString();
- }
- return d;
+ QVariantMap draft;
+ draft["name"] = name_edit_->text();
+ draft["description"] = desc_edit_->text();
+ draft["symbol"] = symbol_combo_->currentText();
+ draft["timeframe"] = timeframe_combo_->currentText();
+ draft["entry_conditions"] = QJsonDocument(entry_section_->conditions()).toJson(QJsonDocument::Compact);
+ draft["exit_conditions"] = QJsonDocument(exit_section_->conditions()).toJson(QJsonDocument::Compact);
+ draft["entry_logic"] = entry_section_->combined_logic();
+ draft["exit_logic"] = exit_section_->combined_logic();
+ draft["stop_loss"] = risk_panel_->stop_loss();
+ draft["take_profit"] = risk_panel_->take_profit();
+ draft["trailing_stop"] = risk_panel_->trailing_stop();
+ draft["quantity"] = risk_panel_->quantity();
+ draft["max_order_value"] = risk_panel_->max_order_value();
+ return draft;
}
-void StrategyBuilderPanel::restore_draft(const QVariantMap& d) {
- if (d.isEmpty()) return;
- if (name_edit_ && d.contains("name")) name_edit_->setText(d["name"].toString());
- if (desc_edit_ && d.contains("desc")) desc_edit_->setText(d["desc"].toString());
- if (bt_symbol_ && d.contains("bt_symbol")) bt_symbol_->setText(d["bt_symbol"].toString());
- if (bt_start_date_ && d.contains("bt_start")) bt_start_date_->setText(d["bt_start"].toString());
- if (bt_end_date_ && d.contains("bt_end")) bt_end_date_->setText(d["bt_end"].toString());
- if (kpi_total_return_val_ && d.contains("kpi_return")) {
- kpi_total_return_val_->setText(d["kpi_return"].toString());
- if (kpi_sharpe_val_) kpi_sharpe_val_->setText(d["kpi_sharpe"].toString());
- if (kpi_max_dd_val_) kpi_max_dd_val_->setText(d["kpi_dd"].toString());
- if (kpi_win_rate_val_) kpi_win_rate_val_->setText(d["kpi_win"].toString());
- if (kpi_trades_val_) kpi_trades_val_->setText(d["kpi_trades"].toString());
- if (kpi_profit_factor_val_) kpi_profit_factor_val_->setText(d["kpi_pf"].toString());
- }
+void StrategyBuilderPanel::restore_draft(const QVariantMap& draft) {
+ name_edit_->setText(draft.value("name").toString());
+ desc_edit_->setText(draft.value("description").toString());
+ symbol_combo_->setCurrentText(draft.value("symbol").toString());
+ timeframe_combo_->setCurrentText(draft.value("timeframe", "5m").toString());
+
+ auto entry_json = QJsonDocument::fromJson(draft.value("entry_conditions").toByteArray()).array();
+ auto exit_json = QJsonDocument::fromJson(draft.value("exit_conditions").toByteArray()).array();
+ entry_section_->set_conditions(entry_json, draft.value("entry_logic", "AND").toString());
+ exit_section_->set_conditions(exit_json, draft.value("exit_logic", "AND").toString());
+
+ risk_panel_->set_values(
+ draft.value("stop_loss", 2.0).toDouble(),
+ draft.value("take_profit", 5.0).toDouble(),
+ draft.value("trailing_stop", 0.0).toDouble(),
+ draft.value("quantity", 1.0).toDouble(),
+ draft.value("max_order_value", 0.0).toDouble());
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
index d6a2f10e1..fb6f9a079 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
@@ -1,81 +1,79 @@
// src/screens/algo_trading/StrategyBuilderPanel.h
#pragma once
#include "services/algo_trading/AlgoTradingTypes.h"
+#include "ui/widgets/algo/ConditionSection.h"
+#include "ui/widgets/algo/RiskManagementPanel.h"
+#include "ui/widgets/algo/SymbolSearchCombo.h"
#include <QComboBox>
#include <QDoubleSpinBox>
-#include <QGridLayout>
#include <QJsonArray>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSplitter>
-#include <QVBoxLayout>
#include <QWidget>
namespace fincept::screens {
-/// Strategy builder — QSplitter workstation layout.
-/// Left: strategy editor (definition + conditions + risk).
-/// Right: backtest params + Quant Lab-style KPI result cards.
class StrategyBuilderPanel : public QWidget {
Q_OBJECT
- public:
+public:
explicit StrategyBuilderPanel(QWidget* parent = nullptr);
QVariantMap save_draft() const;
void restore_draft(const QVariantMap& draft);
- private slots:
+private slots:
void on_save();
void on_backtest();
+ void on_deploy();
void on_backtest_result(const QJsonObject& data);
void on_error(const QString& context, const QString& msg);
- private:
+private:
void build_ui();
void connect_service();
- QWidget* build_left_pane();
- QWidget* build_right_pane();
- QWidget* build_condition_row(QWidget* parent);
+ QWidget* build_top_toolbar();
+ QWidget* build_left_panel();
+ QWidget* build_right_panel();
void display_backtest_result(const QJsonObject& data);
void clear_results();
- // Left pane — strategy editor
- QLineEdit* name_edit_ = nullptr;
- QLineEdit* desc_edit_ = nullptr;
- QComboBox* timeframe_combo_ = nullptr;
- QComboBox* entry_logic_combo_ = nullptr;
- QComboBox* exit_logic_combo_ = nullptr;
- QDoubleSpinBox* stop_loss_spin_ = nullptr;
- QDoubleSpinBox* take_profit_spin_ = nullptr;
- QDoubleSpinBox* trailing_stop_spin_ = nullptr;
- QVBoxLayout* entry_conditions_layout_ = nullptr;
- QVBoxLayout* exit_conditions_layout_ = nullptr;
+ // Top toolbar
+ QLineEdit* name_edit_ = nullptr;
+ QLineEdit* desc_edit_ = nullptr;
+ ui::algo::SymbolSearchCombo* symbol_combo_ = nullptr;
+ QComboBox* timeframe_combo_ = nullptr;
+ QPushButton* save_btn_ = nullptr;
+ QPushButton* backtest_btn_ = nullptr;
+ QPushButton* deploy_btn_ = nullptr;
- // Right pane — backtest
- QLineEdit* bt_symbol_ = nullptr;
- QDoubleSpinBox* bt_capital_ = nullptr;
- QLineEdit* bt_start_date_ = nullptr;
- QLineEdit* bt_end_date_ = nullptr;
- QLabel* status_label_ = nullptr;
- QVBoxLayout* results_layout_ = nullptr;
- QLabel* bt_empty_label_ = nullptr;
+ // Left panel — condition builder
+ ui::algo::ConditionSection* entry_section_ = nullptr;
+ ui::algo::ConditionSection* exit_section_ = nullptr;
+ ui::algo::RiskManagementPanel* risk_panel_ = nullptr;
- // KPI card value labels — updated in display_backtest_result()
- QLabel* kpi_total_return_val_ = nullptr;
- QLabel* kpi_total_return_sub_ = nullptr;
- QLabel* kpi_sharpe_val_ = nullptr;
- QLabel* kpi_sharpe_sub_ = nullptr;
- QLabel* kpi_max_dd_val_ = nullptr;
- QLabel* kpi_max_dd_sub_ = nullptr;
- QLabel* kpi_win_rate_val_ = nullptr;
- QLabel* kpi_win_rate_sub_ = nullptr;
- QLabel* kpi_trades_val_ = nullptr;
- QLabel* kpi_trades_sub_ = nullptr;
+ // Right panel — backtest
+ QDoubleSpinBox* bt_capital_ = nullptr;
+ QLineEdit* bt_start_date_ = nullptr;
+ QLineEdit* bt_end_date_ = nullptr;
+ QLabel* status_label_ = nullptr;
+
+ // KPI card labels
+ QLabel* kpi_total_return_val_ = nullptr;
+ QLabel* kpi_total_return_sub_ = nullptr;
+ QLabel* kpi_sharpe_val_ = nullptr;
+ QLabel* kpi_sharpe_sub_ = nullptr;
+ QLabel* kpi_max_dd_val_ = nullptr;
+ QLabel* kpi_max_dd_sub_ = nullptr;
+ QLabel* kpi_win_rate_val_ = nullptr;
+ QLabel* kpi_win_rate_sub_ = nullptr;
+ QLabel* kpi_trades_val_ = nullptr;
+ QLabel* kpi_trades_sub_ = nullptr;
QLabel* kpi_profit_factor_val_ = nullptr;
QLabel* kpi_profit_factor_sub_ = nullptr;
- QWidget* kpi_grid_widget_ = nullptr; // hidden until first result
+ QWidget* kpi_grid_widget_ = nullptr;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
index 79a19d5e1..07a5c88db 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
@@ -1,6 +1,8 @@
// src/screens/algo_trading/StrategyListPanel.cpp
#include "screens/algo_trading/StrategyListPanel.h"
+#include "screens/algo_trading/AlgoDeployDialog.h"
+#include "algo_engine/AlgoEngine.h"
#include "core/logging/Logger.h"
#include "services/algo_trading/AlgoTradingService.h"
#include "ui/theme/Theme.h"
@@ -9,6 +11,7 @@
#include <QHeaderView>
#include <QHBoxLayout>
+#include <QMessageBox>
#include <QPushButton>
#include <QScrollArea>
#include <QTableWidgetItem>
@@ -31,6 +34,7 @@ StrategyListPanel::StrategyListPanel(QWidget* parent) : QWidget(parent) {
void StrategyListPanel::connect_service() {
auto& svc = AlgoTradingService::instance();
connect(&svc, &AlgoTradingService::strategies_loaded, this, &StrategyListPanel::on_strategies_loaded);
+ connect(&svc, &AlgoTradingService::strategy_deleted, this, [&svc](const QString&) { svc.list_strategies(); });
connect(&svc, &AlgoTradingService::error_occurred, this, &StrategyListPanel::on_error);
}
@@ -109,24 +113,28 @@ void StrategyListPanel::build_ui() {
// ── Table ────────────────────────────────────────────────────────────────
table_ = new QTableWidget(this);
- table_->setColumnCount(4); // #, NAME, CATEGORY, ID
- table_->setHorizontalHeaderLabels({"#", "STRATEGY NAME", "CATEGORY", "ID"});
+ table_->setColumnCount(6); // #, NAME, CATEGORY, ID, DEPLOY, DELETE
+ table_->setHorizontalHeaderLabels({"#", "STRATEGY NAME", "CATEGORY", "ID", "", ""});
table_->verticalHeader()->setVisible(false);
table_->setSelectionBehavior(QAbstractItemView::SelectRows);
table_->setSelectionMode(QAbstractItemView::SingleSelection);
table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
table_->setAlternatingRowColors(true);
- table_->setSortingEnabled(false); // we sort ourselves
+ table_->setSortingEnabled(false);
table_->setShowGrid(false);
table_->setFocusPolicy(Qt::NoFocus);
table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Fixed);
+ table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Fixed);
+ table_->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Fixed);
table_->setColumnWidth(0, 40);
table_->setColumnWidth(2, 180);
table_->setColumnWidth(3, 120);
- table_->verticalHeader()->setDefaultSectionSize(26);
+ table_->setColumnWidth(4, 80);
+ table_->setColumnWidth(5, 70);
+ table_->verticalHeader()->setDefaultSectionSize(30);
table_->setStyleSheet(
QString("QTableWidget { background:%1; alternate-background-color:%2;"
" color:%3; border:none; font-size:%4px; font-family:%5; gridline-color:%6; }"
@@ -233,6 +241,37 @@ void StrategyListPanel::render_page() {
auto* id_item = new QTableWidgetItem(s.id);
id_item->setForeground(QColor(colors::TEXT_TERTIARY()));
table_->setItem(row, 3, id_item);
+
+ // Col 4: DEPLOY button
+ auto* deploy_btn = new QPushButton("DEPLOY", table_);
+ deploy_btn->setCursor(Qt::PointingHandCursor);
+ deploy_btn->setFixedHeight(22);
+ deploy_btn->setStyleSheet(
+ QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
+ " font-size: %2px; font-weight: 700; font-family: %3; padding: 1px 8px; }"
+ "QPushButton:hover { background: rgba(217,119,6,0.1); }")
+ .arg(colors::AMBER())
+ .arg(fonts::TINY)
+ .arg(fonts::DATA_FAMILY()));
+ connect(deploy_btn, &QPushButton::clicked, this, [this, row]() { on_deploy_clicked(row); });
+ table_->setCellWidget(row, 4, deploy_btn);
+
+ // Col 5: DELETE button (only for DSL strategies — QC strategies come from file registry)
+ const bool is_dsl = !s.id.startsWith("FCT-");
+ if (is_dsl) {
+ auto* delete_btn = new QPushButton("DELETE", table_);
+ delete_btn->setCursor(Qt::PointingHandCursor);
+ delete_btn->setFixedHeight(22);
+ delete_btn->setStyleSheet(
+ QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
+ " font-size: %2px; font-weight: 700; font-family: %3; padding: 1px 8px; }"
+ "QPushButton:hover { background: rgba(220,38,38,0.1); }")
+ .arg(colors::NEGATIVE())
+ .arg(fonts::TINY)
+ .arg(fonts::DATA_FAMILY()));
+ connect(delete_btn, &QPushButton::clicked, this, [this, row]() { on_delete_clicked(row); });
+ table_->setCellWidget(row, 5, delete_btn);
+ }
}
update_pagination_controls();
@@ -334,4 +373,33 @@ void StrategyListPanel::on_error(const QString& context, const QString& msg) {
LOG_ERROR("AlgoTrading", QString("StrategyList error [%1]: %2").arg(context, msg));
}
+void StrategyListPanel::on_deploy_clicked(int row) {
+ const int abs_index = current_page_ * kPageSize + row;
+ if (abs_index < 0 || abs_index >= filtered_.size())
+ return;
+
+ const auto& strategy = filtered_[abs_index];
+ AlgoDeployDialog dialog(strategy.id, strategy.name, this);
+ if (dialog.exec() == QDialog::Accepted) {
+ auto deployment = dialog.result();
+ fincept::algo::AlgoEngine::instance().start_deployment(deployment, strategy);
+ LOG_INFO("AlgoTrading", QString("Deploy requested: %1 on %2").arg(strategy.name, deployment.symbol));
+ }
+}
+
+void StrategyListPanel::on_delete_clicked(int row) {
+ const int abs_index = current_page_ * kPageSize + row;
+ if (abs_index < 0 || abs_index >= filtered_.size())
+ return;
+
+ const auto& strategy = filtered_[abs_index];
+ auto answer = QMessageBox::question(this, "Delete Strategy",
+ QString("Delete \"%1\"?").arg(strategy.name),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer == QMessageBox::Yes) {
+ AlgoTradingService::instance().delete_strategy(strategy.id);
+ LOG_INFO("AlgoTrading", QString("Delete requested: %1").arg(strategy.name));
+ }
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/StrategyListPanel.h b/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
index 550ee378a..28f233c7b 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
@@ -23,6 +23,8 @@ class StrategyListPanel : public QWidget {
void on_sort_changed(int index);
void on_error(const QString& context, const QString& msg);
void on_filter_changed(const QString& text);
+ void on_deploy_clicked(int row);
+ void on_delete_clicked(int row);
void go_to_page(int page);
private:
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp b/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp
index f5dc01c33..4eae6c878 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoChart.cpp
@@ -27,6 +27,15 @@
#include "screens/crypto_trading/CryptoChart.h"
+#include "ui/charts/CandleData.h"
+#include "ui/charts/ChartOverlayManager.h"
+#include "ui/charts/IndicatorPicker.h"
+#include "ui/charts/layers/EmaLayer.h"
+#include "ui/charts/layers/VwapLayer.h"
+#include "ui/charts/layers/BollingerLayer.h"
+#include "ui/charts/layers/SupportResistanceLayer.h"
+#include "ui/charts/layers/PivotLayer.h"
+
#include "ui/theme/Theme.h"
#include <QCandlestickSeries>
@@ -295,6 +304,45 @@ CryptoChart::CryptoChart(QWidget* parent) : QWidget(parent) {
ohlc_tooltip_->move(12, 12);
setMinimumHeight(280);
+
+ // --- Overlay engine ---
+ overlay_mgr_ = new fincept::ui::ChartOverlayManager(this);
+ overlay_mgr_->set_chart(chart_view_->scene(), chart_);
+
+ connect(chart_, &QChart::plotAreaChanged, this, [this](const QRectF&) {
+ overlay_mgr_->reposition_all();
+ });
+
+ indicator_picker_ = new fincept::ui::IndicatorPicker(overlay_mgr_, this);
+ layout->insertWidget(layout->indexOf(chart_view_), indicator_picker_);
+
+ connect(indicator_picker_, &fincept::ui::IndicatorPicker::indicator_requested,
+ this, [this](const QString& id) {
+ using namespace fincept::ui;
+ OverlayLayer* layer = nullptr;
+ if (id.startsWith("ema_")) {
+ int period = id.mid(4).toInt();
+ if (period <= 0) period = 21;
+ const QColor colors[] = {QColor("#d97706"), QColor("#16a34a"), QColor("#2563eb"), QColor("#dc2626")};
+ int idx = (period == 9) ? 0 : (period == 21) ? 1 : (period == 50) ? 2 : 3;
+ layer = new EmaLayer(period, colors[idx]);
+ } else if (id == "vwap") {
+ layer = new VwapLayer(true);
+ } else if (id.startsWith("bb_")) {
+ layer = new BollingerLayer();
+ } else if (id == "sr_auto") {
+ layer = new SupportResistanceLayer();
+ } else if (id == "pivot_std") {
+ layer = new PivotLayer();
+ }
+ if (layer)
+ overlay_mgr_->add_layer(layer);
+ });
+
+ connect(indicator_picker_, &fincept::ui::IndicatorPicker::indicator_removed,
+ this, [this](const QString& id) {
+ overlay_mgr_->remove_layer(id);
+ });
}
void CryptoChart::set_active_tf(int idx) {
@@ -317,6 +365,7 @@ QString CryptoChart::current_timeframe() const {
void CryptoChart::set_candles(const QVector<trading::Candle>& candles) {
candles_ = candles;
rebuild_chart();
+ overlay_mgr_->set_candles(fincept::ui::CandleData::from_candles(candles_));
apply_tf_axis_format();
update_last_price_marker();
@@ -391,6 +440,9 @@ void CryptoChart::append_candle(const trading::Candle& candle) {
update_axes(cached_min_price_, cached_max_price_, min_time, max_time);
apply_tf_axis_format();
update_last_price_marker();
+
+ if (!candles_.isEmpty())
+ overlay_mgr_->append_candle(fincept::ui::CandleData::from(candles_.last()));
}
void CryptoChart::recompute_bounds() {
@@ -426,6 +478,12 @@ void CryptoChart::update_axes(double min_price, double max_price, qint64 min_tim
if (min_price >= max_price)
return;
+ double overlay_min = 0, overlay_max = 0;
+ if (overlay_mgr_->overlay_price_range(overlay_min, overlay_max)) {
+ min_price = std::min(min_price, overlay_min);
+ max_price = std::max(max_price, overlay_max);
+ }
+
const double padding = (max_price - min_price) * 0.06;
const double p_min = min_price - padding;
const double p_max = max_price + padding;
@@ -451,6 +509,8 @@ void CryptoChart::update_axes(double min_price, double max_price, qint64 min_tim
last_min_time_ = min_time;
last_max_time_ = effective_max;
}
+
+ overlay_mgr_->reposition_all();
}
void CryptoChart::apply_tf_axis_format() {
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoChart.h b/fincept-qt/src/screens/crypto_trading/CryptoChart.h
index ee8bf0723..27fa2694b 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoChart.h
+++ b/fincept-qt/src/screens/crypto_trading/CryptoChart.h
@@ -3,6 +3,7 @@
// OHLC tooltip, and a last-price tag pinned to the right axis.
#include "trading/TradingTypes.h"
+#include "ui/charts/ChartOverlayManager.h"
#include <QPushButton>
#include <QVector>
@@ -20,6 +21,8 @@ class QGraphicsEllipseItem;
class QGraphicsSimpleTextItem;
class QLabel;
+namespace fincept::ui { class IndicatorPicker; }
+
namespace fincept::screens::crypto {
class HoverChartView; // forward; defined in the .cpp
@@ -34,6 +37,7 @@ class CryptoChart : public QWidget {
void clear();
QString current_timeframe() const;
+ fincept::ui::ChartOverlayManager* overlay_manager() const { return overlay_mgr_; }
signals:
void timeframe_changed(const QString& tf);
@@ -95,6 +99,9 @@ class CryptoChart : public QWidget {
// set_candles() will emit timeframe_changed again if this is set
QString pending_tf_;
+ fincept::ui::ChartOverlayManager* overlay_mgr_ = nullptr;
+ fincept::ui::IndicatorPicker* indicator_picker_ = nullptr;
+
friend class HoverChartView;
};
diff --git a/fincept-qt/src/screens/dashboard/widgets/VideoPlayerWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/VideoPlayerWidget.cpp
index 0aaab70d2..482dbc7aa 100644
--- a/fincept-qt/src/screens/dashboard/widgets/VideoPlayerWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/VideoPlayerWidget.cpp
@@ -300,7 +300,7 @@ void VideoPlayerWidget::resolve_youtube_and_play(const QString& youtube_url, con
// --no-playlist: single video only
// -g: print URL only, don't download
proc->start(ytdlp_program,
- {"-f", "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best", "--no-playlist", "-g", youtube_url});
+ {"-f", "best[ext=mp4]/best", "--no-playlist", "-g", youtube_url});
}
void VideoPlayerWidget::on_ytdlp_finished(int exit_code, QProcess::ExitStatus /*status*/) {
diff --git a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
index db24bdbd0..fbb032f75 100644
--- a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp
@@ -7,6 +7,11 @@
#include <QDateTime>
#include <QEvent>
#include <QFrame>
+#include <QCoreApplication>
+#include <QFile>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QTextStream>
#include <QHBoxLayout>
#include <QPainter>
#include <QScrollArea>
@@ -433,9 +438,21 @@ QWidget* EquityOverviewTab::build_chart_panel() {
vl->addLayout(btn_row);
- // Canvas
+ // Chart widget — prefer KLineChart when WebEngine is available
+#ifdef HAS_QT_WEBENGINE
+ kline_chart_ = new fincept::ui::KLineChartWidget;
+ if (kline_chart_->is_available()) {
+ vl->addWidget(kline_chart_, 1);
+ } else {
+ delete kline_chart_;
+ kline_chart_ = nullptr;
+ candle_canvas_ = new ResearchCandleCanvas;
+ vl->addWidget(candle_canvas_, 1);
+ }
+#else
candle_canvas_ = new ResearchCandleCanvas;
vl->addWidget(candle_canvas_, 1);
+#endif
return p;
}
@@ -621,7 +638,7 @@ void EquityOverviewTab::render_info(const services::equity::StockInfo& info) {
low_val_->setText(fmt_price(cached_quote_.low));
prev_close_val_->setText(fmt_price(cached_quote_.prev_close));
}
- if (historical_loaded_ && !cached_candles_.isEmpty()) {
+ if (historical_loaded_ && !cached_candles_.isEmpty() && candle_canvas_) {
candle_canvas_->set_candles(cached_candles_,
currency_symbol(current_currency_.isEmpty() ? "USD" : current_currency_));
}
@@ -713,6 +730,38 @@ void EquityOverviewTab::on_historical_loaded(QString symbol, QVector<services::e
}
void EquityOverviewTab::rebuild_chart(const QVector<services::equity::Candle>& candles) {
+#ifdef HAS_QT_WEBENGINE
+ if (kline_chart_) {
+ QJsonArray arr;
+ for (const auto& c : candles) {
+ QJsonObject obj;
+ obj[QStringLiteral("timestamp")] = static_cast<double>(c.timestamp);
+ obj[QStringLiteral("open")] = c.open;
+ obj[QStringLiteral("high")] = c.high;
+ obj[QStringLiteral("low")] = c.low;
+ obj[QStringLiteral("close")] = c.close;
+ obj[QStringLiteral("volume")] = static_cast<double>(c.volume);
+ arr.append(obj);
+ }
+ {
+ QFile dbg(QCoreApplication::applicationDirPath() + "/kline_debug.txt");
+ if (dbg.open(QIODevice::Append | QIODevice::Text)) {
+ QTextStream ts(&dbg);
+ ts << QDateTime::currentDateTime().toString("HH:mm:ss")
+ << " rebuild_chart: candles=" << candles.size()
+ << " json_arr=" << arr.size() << "\n";
+ if (!candles.isEmpty()) {
+ const auto& f = candles.first();
+ ts << " first: ts=" << f.timestamp << " o=" << f.open
+ << " h=" << f.high << " l=" << f.low
+ << " c=" << f.close << " v=" << f.volume << "\n";
+ }
+ }
+ }
+ kline_chart_->set_candles(arr);
+ return;
+ }
+#endif
const QString cs = currency_symbol(current_currency_.isEmpty() ? "USD" : current_currency_);
candle_canvas_->set_candles(candles, cs);
}
diff --git a/fincept-qt/src/screens/equity_research/EquityOverviewTab.h b/fincept-qt/src/screens/equity_research/EquityOverviewTab.h
index 1fd3c4580..233933ac5 100644
--- a/fincept-qt/src/screens/equity_research/EquityOverviewTab.h
+++ b/fincept-qt/src/screens/equity_research/EquityOverviewTab.h
@@ -3,6 +3,10 @@
#include "services/equity/EquityResearchModels.h"
#include "ui/widgets/LoadingOverlay.h"
+#ifdef HAS_QT_WEBENGINE
+#include "ui/charts/KLineChartWidget.h"
+#endif
+
#include <QHash>
#include <QLabel>
#include <QPixmap>
@@ -127,6 +131,9 @@ class EquityOverviewTab : public QWidget {
QLabel* short_pct_val_ = nullptr;
// Chart
+#ifdef HAS_QT_WEBENGINE
+ fincept::ui::KLineChartWidget* kline_chart_ = nullptr;
+#endif
ResearchCandleCanvas* candle_canvas_ = nullptr;
QPushButton* btn_1m_ = nullptr;
QPushButton* btn_3m_ = nullptr;
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 14905e027..4b860640d 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -5,6 +5,10 @@
#include "core/session/ScreenStateManager.h"
#include "core/symbol/SymbolContext.h"
#include "core/symbol/SymbolDragSource.h"
+#include "datahub/DataHub.h"
+#include "datahub/DataHubMetaTypes.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerTopic.h"
#include "screens/equity_research/EquityAnalysisTab.h"
#include "screens/equity_research/EquityFinancialsTab.h"
#include "screens/equity_research/EquityNewsTab.h"
@@ -64,10 +68,12 @@ EquityResearchScreen::EquityResearchScreen(QWidget* parent) : QWidget(parent) {
void EquityResearchScreen::showEvent(QShowEvent* e) {
QWidget::showEvent(e);
refresh_timer_->start();
+ hub_subscribe_broker_quote();
}
void EquityResearchScreen::hideEvent(QHideEvent* e) {
QWidget::hideEvent(e);
+ hub_unsubscribe_broker_quote();
refresh_timer_->stop();
}
@@ -286,6 +292,10 @@ void EquityResearchScreen::load_symbol(const QString& symbol) {
// Trigger quote + info + historical
services::equity::EquityResearchService::instance().load_symbol(symbol);
+ // Subscribe to broker live quote if this is an Indian stock with Fyers connected
+ if (isVisible())
+ hub_subscribe_broker_quote();
+
// Publish to linked group so Watchlist/EquityTrading/News/etc. follow.
if (link_group_ != SymbolGroup::None) {
SymbolContext::instance().set_group_symbol(
@@ -384,8 +394,8 @@ QVariantMap EquityResearchScreen::save_state() const {
void EquityResearchScreen::restore_state(const QVariantMap& state) {
const QString sym = state.value("symbol").toString();
if (!sym.isEmpty()) {
- current_symbol_ = sym;
- services::equity::EquityResearchService::instance().load_symbol(sym);
+ current_symbol_.clear();
+ load_symbol(sym);
}
if (tab_widget_) {
const int idx = state.value("tab_index", 0).toInt();
@@ -396,4 +406,62 @@ void EquityResearchScreen::restore_state(const QVariantMap& state) {
peers_tab_->set_peers_text(state.value("peers").toString());
}
+// ── Broker live quote subscription ──────────────────────────────────────────
+
+void EquityResearchScreen::hub_subscribe_broker_quote() {
+ hub_unsubscribe_broker_quote();
+
+ if (current_symbol_.isEmpty())
+ return;
+ // Only Indian stocks are streamable via Fyers
+ if (!current_symbol_.endsWith(QStringLiteral(".NS")) && !current_symbol_.endsWith(QStringLiteral(".BO")))
+ return;
+
+ // Find a connected Fyers account
+ const auto accounts = trading::AccountManager::instance().active_accounts();
+ QString fyers_account_id;
+ for (const auto& a : accounts) {
+ if (a.broker_id == QStringLiteral("fyers") && a.state == trading::ConnectionState::Connected) {
+ fyers_account_id = a.account_id;
+ break;
+ }
+ }
+ if (fyers_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,
+ QStringLiteral("quote"), broker_sym);
+ const QString sym = current_symbol_;
+
+ datahub::DataHub::instance().subscribe(this, topic, [this, sym](const QVariant& v) {
+ if (!v.canConvert<trading::BrokerQuote>())
+ return;
+ const auto bq = v.value<trading::BrokerQuote>();
+ services::equity::QuoteData qd;
+ qd.symbol = sym;
+ qd.price = bq.ltp;
+ qd.change = bq.change;
+ qd.change_pct = bq.change_pct;
+ qd.high = bq.high;
+ qd.low = bq.low;
+ qd.volume = bq.volume;
+ qd.timestamp = bq.timestamp;
+ update_quote_bar(qd);
+ });
+
+ refresh_timer_->stop(); // broker stream is faster than 30s polling
+ hub_broker_active_ = true;
+}
+
+void EquityResearchScreen::hub_unsubscribe_broker_quote() {
+ if (!hub_broker_active_)
+ return;
+ datahub::DataHub::instance().unsubscribe(this);
+ hub_broker_active_ = false;
+ if (isVisible())
+ refresh_timer_->start();
+}
+
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
index a7a61de6a..4e15a04ce 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
@@ -57,6 +57,8 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
void update_quote_bar(const services::equity::QuoteData& q);
void load_symbol(const QString& symbol);
void retranslateUi();
+ void hub_subscribe_broker_quote();
+ void hub_unsubscribe_broker_quote();
// Title bar
QLabel* title_label_ = nullptr;
@@ -86,6 +88,7 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
QTimer* refresh_timer_ = nullptr;
QString current_symbol_;
QString current_currency_;
+ bool hub_broker_active_ = false;
// Symbol group link — SymbolGroup::None when unlinked.
SymbolGroup link_group_ = SymbolGroup::None;
diff --git a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
index 2d9808eac..1bc625f31 100644
--- a/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
+++ b/fincept-qt/src/screens/equity_trading/AccountManagementDialog.cpp
@@ -12,6 +12,7 @@
#include "ui/theme/Theme.h"
#include <QCoreApplication>
+#include <QDateTime>
#include <QDesktopServices>
#include <QFrame>
#include <QHBoxLayout>
@@ -1250,6 +1251,10 @@ void AccountManagementDialog::fyers_exchange_and_store_token_async(const QString
creds.refresh_token = result.refresh_token;
if (!result.user_id.isEmpty())
creds.user_id = result.user_id;
+ // Fyers tokens expire in 24h from issuance
+ QJsonObject extra = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();
+ extra[QStringLiteral("token_expires_at")] = QDateTime::currentSecsSinceEpoch() + 86400;
+ creds.additional_data = QString::fromUtf8(QJsonDocument(extra).toJson(QJsonDocument::Compact));
am.save_credentials(acct, creds);
am.set_connection_state(acct, ConnectionState::Connected, {});
self->f_status_->setText(QString("Connected as %1").arg(
diff --git a/fincept-qt/src/screens/equity_trading/EquityChart.cpp b/fincept-qt/src/screens/equity_trading/EquityChart.cpp
index 8e550a9bf..48e04015e 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChart.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityChart.cpp
@@ -1,194 +1,156 @@
-// EquityChart.cpp — Custom-painted candlestick chart
-// QPainter-based: no QCandlestickSeries, no QDateTimeAxis gaps.
-#include "screens/equity_trading/EquityChart.h"
+// EquityChart.cpp — Qt Charts candlestick chart with overlays.
+//
+// Ported from QPainter-based rendering to Qt Charts, matching the CryptoChart
+// implementation pattern. This gives EquityChart the same overlay
+// infrastructure (indicators, crosshair, hover tooltips).
+//
+// What this widget does on top of stock Qt Charts:
+// * Crosshair on hover (vertical + horizontal lines through the cursor)
+// * OHLC tooltip in the top-left, updated to the candle under the cursor
+// * Right-edge price tag at the cursor's price (snaps to grid)
+// * Bottom-edge time tag at the cursor's time
+// * Always-visible "last price" tag pinned to the right axis at the
+// most recent close -- colour-coded green/red by the latest direction
+// * Time-axis label format auto-scales with the timeframe
+// (HH:mm / MMM dd HH:mm / MMM dd / MMM yy)
+// * Generous bottom margin so the time-axis labels stop being clipped
+// * Mouse wheel = zoom price axis; drag = pan
-#include "screens/equity_trading/EquityTypes.h"
-#include "ui/theme/ThemeManager.h"
+#include "screens/equity_trading/EquityChart.h"
+#include "ui/charts/CandleData.h"
+#include "ui/charts/ChartOverlayManager.h"
+#include "ui/charts/IndicatorPicker.h"
+#include "ui/charts/layers/EmaLayer.h"
+#include "ui/charts/layers/VwapLayer.h"
+#include "ui/charts/layers/BollingerLayer.h"
+#include "ui/charts/layers/SupportResistanceLayer.h"
+#include "ui/charts/layers/PivotLayer.h"
+
+#include "ui/theme/Theme.h"
+
+#include <QCandlestickSeries>
+#include <QCandlestickSet>
+#include <QChart>
+#include <QChartView>
+#include <QDateTime>
+#include <QDateTimeAxis>
+#include <QEnterEvent>
+#include <QFont>
+#include <QGraphicsLayout>
+#include <QGraphicsEllipseItem>
+#include <QGraphicsLineItem>
+#include <QGraphicsRectItem>
+#include <QGraphicsScene>
+#include <QGraphicsSimpleTextItem>
#include <QHBoxLayout>
+#include <QLabel>
+#include <QLineSeries>
+#include <QMouseEvent>
#include <QPainter>
-#include <QPainterPath>
+#include <QPen>
#include <QStyle>
+#include <QToolTip>
+#include <QValueAxis>
#include <QVBoxLayout>
+#include <QWheelEvent>
#include <algorithm>
#include <cmath>
-namespace fincept::screens::equity {
-
-// ── CandleCanvas ─────────────────────────────────────────────────────────────
+using namespace fincept::ui;
-CandleCanvas::CandleCanvas(QWidget* parent) : QWidget(parent) {
- setObjectName("eqCandleCanvas");
- setMinimumHeight(120);
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+namespace fincept::screens::equity {
- connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this](const ui::ThemeTokens&) {
- dirty_ = true;
- cache_ = QPixmap(); // invalidate cache
- update();
- });
+constexpr const char* EquityChart::TF_LABELS[];
+
+namespace {
+
+// Maps a timeframe label to its slot duration in milliseconds. Used to
+// extend the time axis by one slot when there is only one candle (otherwise
+// QCandlestickSeries renders bars as hairlines) and to pick the time-axis
+// label format.
+qint64 tf_slot_ms(const QString& tf) {
+ if (tf == QLatin1String("1m")) return 60'000;
+ if (tf == QLatin1String("5m")) return 5 * 60'000;
+ if (tf == QLatin1String("15m")) return 15 * 60'000;
+ if (tf == QLatin1String("1h")) return 60 * 60'000;
+ if (tf == QLatin1String("1d")) return 24 * 60 * 60'000;
+ if (tf == QLatin1String("1w")) return 7 * 24 * 60 * 60'000;
+ return 60'000;
}
-void CandleCanvas::set_candles(const QVector<trading::BrokerCandle>& candles) {
- candles_ = candles;
- dirty_ = true;
- update();
+// Choose a time-axis label format that fits the chart's time span without
+// overlapping ticks. Driven by total span, not just the timeframe, so a
+// 120-bar 1d chart shows months/years rather than redundant day labels.
+QString time_format_for(qint64 span_ms) {
+ constexpr qint64 kHour = 60LL * 60 * 1000;
+ constexpr qint64 kDay = 24 * kHour;
+ if (span_ms <= 6 * kHour) return QStringLiteral("HH:mm");
+ if (span_ms <= 3 * kDay) return QStringLiteral("MMM dd HH:mm");
+ if (span_ms <= 90 * kDay) return QStringLiteral("MMM dd");
+ return QStringLiteral("MMM yy");
}
-void CandleCanvas::clear() {
- candles_.clear();
- dirty_ = true;
- update();
+QFont scene_font() {
+ QFont f;
+ f.setFamily(QStringLiteral("Consolas"));
+ f.setPointSize(9);
+ f.setWeight(QFont::DemiBold);
+ return f;
}
-void CandleCanvas::resizeEvent(QResizeEvent* e) {
- QWidget::resizeEvent(e);
- dirty_ = true;
-}
-
-void CandleCanvas::paintEvent(QPaintEvent*) {
- if (dirty_) {
- rebuild_cache();
- dirty_ = false;
+} // namespace
+
+// -- HoverEquityChartView ----------------------------------------------------
+// Custom QChartView that forwards mouse-move events to the parent EquityChart
+// so the crosshair / OHLC tooltip can update without subclassing the chart
+// itself. Also enables wheel-zoom on the price axis and drag-pan.
+class HoverEquityChartView : public QChartView {
+ public:
+ HoverEquityChartView(QChart* chart, EquityChart* host)
+ : QChartView(chart), host_(host) {
+ setMouseTracking(true);
+ setRenderHint(QPainter::Antialiasing, true);
+ setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ setRubberBand(QChartView::NoRubberBand);
+ setDragMode(QGraphicsView::NoDrag);
}
- QPainter p(this);
- p.drawPixmap(0, 0, cache_);
-}
-
-void CandleCanvas::rebuild_cache() {
- const int W = width();
- const int H = height();
- if (W <= 0 || H <= 0)
- return;
-
- cache_ = QPixmap(W, H);
- cache_.fill(BG_SURFACE());
-
- QPainter p(&cache_);
- p.setRenderHint(QPainter::Antialiasing, false);
- // ── Subset ───────────────────────────────────────────────────────────────
- const int total = candles_.size();
- if (total == 0) {
- // Empty state
- p.setPen(TEXT_TERTIARY());
- p.setFont(QFont("monospace", 10));
- p.drawText(cache_.rect(), Qt::AlignCenter, "No data");
- return;
+ protected:
+ void mouseMoveEvent(QMouseEvent* e) override {
+ if (host_ && chart()) {
+ const QPointF chart_pos = chart()->mapToValue(e->pos());
+ host_->on_hover_position(chart_pos, e->pos());
+ }
+ QChartView::mouseMoveEvent(e);
}
-
- const int start = qMax(0, total - MAX_VISIBLE);
- const int count = total - start;
-
- // ── Price range ──────────────────────────────────────────────────────────
- double lo = 1e18, hi = 0.0;
- for (int i = start; i < total; ++i) {
- lo = std::min(lo, candles_[i].low);
- hi = std::max(hi, candles_[i].high);
+ void leaveEvent(QEvent* e) override {
+ if (host_) host_->on_hover_leave();
+ QChartView::leaveEvent(e);
}
- if (lo >= hi)
- return;
-
- const double margin = (hi - lo) * 0.05;
- lo -= margin;
- hi += margin;
-
- // ── Layout ───────────────────────────────────────────────────────────────
- const int plot_w = W - PRICE_AXIS_W;
- const int plot_h = H - TIME_AXIS_H;
- if (plot_w <= 0 || plot_h <= 0)
- return;
-
- // Lambda: price → y pixel
- auto py = [&](double price) -> int { return static_cast<int>(plot_h - (price - lo) / (hi - lo) * plot_h); };
-
- // ── Grid lines ───────────────────────────────────────────────────────────
- p.setPen(QPen(BORDER_DIM(), 1));
- for (int g = 1; g < 5; ++g) {
- int gy = plot_h * g / 5;
- p.drawLine(0, gy, plot_w, gy);
- }
-
- // ── Candle geometry ──────────────────────────────────────────────────────
- const double slot_w = static_cast<double>(plot_w) / count;
- const int body_w = qMax(1, static_cast<int>(slot_w * 0.6));
- const int half = body_w / 2;
-
- for (int i = 0; i < count; ++i) {
- const auto& c = candles_[start + i];
- const int cx = static_cast<int>((i + 0.5) * slot_w); // centre x
- const bool bull = c.close >= c.open;
-
- const QColor col = bull ? COLOR_BUY() : COLOR_SELL();
-
- const int open_y = py(c.open);
- const int close_y = py(c.close);
- const int high_y = py(c.high);
- const int low_y = py(c.low);
-
- const int body_top = std::min(open_y, close_y);
- const int body_bot = std::max(open_y, close_y);
- const int body_h = qMax(1, body_bot - body_top);
-
- // Wick
- p.setPen(QPen(col, 1));
- p.drawLine(cx, high_y, cx, low_y);
-
- // Body
- p.fillRect(cx - half, body_top, body_w, body_h, col);
- }
-
- // ── Price axis (right) ────────────────────────────────────────────────────
- p.setPen(BORDER_MED());
- p.drawLine(plot_w, 0, plot_w, plot_h);
-
- p.setPen(TEXT_SECONDARY());
- QFont lbl_font("monospace", 8);
- p.setFont(lbl_font);
- QFontMetrics fm(lbl_font);
-
- for (int g = 0; g <= 5; ++g) {
- double price = lo + (hi - lo) * g / 5.0;
- int gy = py(price);
- QString txt = QString::number(price, 'f', 2);
- p.drawText(plot_w + 4, gy + fm.ascent() / 2, txt);
- }
-
- // ── Time axis (bottom) ────────────────────────────────────────────────────
- p.setPen(BORDER_MED());
- p.drawLine(0, plot_h, plot_w, plot_h);
-
- p.setPen(TEXT_SECONDARY());
- for (int i = 0; i < count; i += LABEL_STEP) {
- const auto& c = candles_[start + i];
- QDateTime dt = QDateTime::fromMSecsSinceEpoch(c.timestamp);
- // Show date if daily/weekly, time otherwise
- QString label;
- if (slot_w * LABEL_STEP > 60) {
- // enough space — pick format based on timeframe span
- qint64 span_ms = candles_.last().timestamp - candles_.first().timestamp;
- label = span_ms > 7LL * 24 * 3600 * 1000 ? dt.toString("dd MMM") : dt.toString("HH:mm");
- } else {
- label = dt.toString("HH:mm");
+ void wheelEvent(QWheelEvent* e) override {
+ if (!chart()) {
+ QChartView::wheelEvent(e);
+ return;
}
- int lx = static_cast<int>((i + 0.5) * slot_w);
- int tw = fm.horizontalAdvance(label);
- p.drawText(lx - tw / 2, plot_h + TIME_AXIS_H - 3, label);
- }
- // Always draw the last label
- {
- const auto& c = candles_.last();
- QDateTime dt = QDateTime::fromMSecsSinceEpoch(c.timestamp);
- qint64 span_ms = candles_.last().timestamp - candles_.first().timestamp;
- QString label = span_ms > 7LL * 24 * 3600 * 1000 ? dt.toString("dd MMM") : dt.toString("HH:mm");
- int lx = static_cast<int>((count - 0.5) * slot_w);
- int tw = fm.horizontalAdvance(label);
- p.drawText(lx - tw / 2, plot_h + TIME_AXIS_H - 3, label);
+ // Zoom price axis only. Wheel-panning the time axis collides with the
+ // candle stream -- users expect Time fixed and Price scaled.
+ const double factor = (e->angleDelta().y() > 0) ? 0.9 : 1.1;
+ if (auto* y = qobject_cast<QValueAxis*>(host_ ? host_->price_axis_ : nullptr)) {
+ const double mid = (y->min() + y->max()) / 2.0;
+ const double span = (y->max() - y->min()) * factor;
+ y->setRange(mid - span / 2.0, mid + span / 2.0);
+ }
+ e->accept();
}
-}
-// ── EquityChart ───────────────────────────────────────────────────────────────
+ private:
+ EquityChart* host_ = nullptr;
+};
+
+// -- EquityChart -------------------------------------------------------------
EquityChart::EquityChart(QWidget* parent) : QWidget(parent) {
setObjectName("eqChart");
@@ -197,57 +159,536 @@ EquityChart::EquityChart(QWidget* parent) : QWidget(parent) {
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
- // Header with timeframe buttons
+ // -- Header with TF toggles ----------------------------------------------
auto* header = new QWidget(this);
header->setObjectName("eqChartHeader");
- header->setFixedHeight(28);
auto* h_layout = new QHBoxLayout(header);
- h_layout->setContentsMargins(8, 0, 8, 0);
+ h_layout->setContentsMargins(10, 4, 10, 4);
h_layout->setSpacing(2);
- auto* title = new QLabel("CHART");
+ auto* title = new QLabel(QStringLiteral("CHART"));
title->setObjectName("eqChartTitle");
h_layout->addWidget(title);
- h_layout->addStretch();
+ h_layout->addSpacing(8);
for (int i = 0; i < 6; ++i) {
tf_buttons_[i] = new QPushButton(TF_LABELS[i]);
tf_buttons_[i]->setObjectName("eqTfBtn");
- tf_buttons_[i]->setFixedHeight(20);
tf_buttons_[i]->setCursor(Qt::PointingHandCursor);
- if (i == active_tf_)
- tf_buttons_[i]->setProperty("active", true);
+ tf_buttons_[i]->setFocusPolicy(Qt::NoFocus);
+ if (i == active_tf_) tf_buttons_[i]->setProperty("active", true);
connect(tf_buttons_[i], &QPushButton::clicked, this, [this, i]() { set_active_tf(i); });
h_layout->addWidget(tf_buttons_[i]);
}
+ h_layout->addStretch();
layout->addWidget(header);
- canvas_ = new CandleCanvas(this);
- layout->addWidget(canvas_, 1);
+ // -- Chart proper --------------------------------------------------------
+ chart_ = new QChart;
+ chart_->setBackgroundBrush(QBrush(QColor(colors::BG_SURFACE())));
+ chart_->setBackgroundPen(QPen(Qt::NoPen));
+ chart_->setPlotAreaBackgroundBrush(QBrush(QColor(colors::BG_BASE())));
+ chart_->setPlotAreaBackgroundVisible(true);
+ chart_->legend()->hide();
+ // Generous bottom + right margins so axis labels are NEVER clipped.
+ // Right margin = 72 px gives the price-axis labels and the right-edge
+ // hover/last-price tags room for "99999.99" without bleeding into the
+ // plot. Bottom = 36 px fits "MMM dd HH:mm" comfortably.
+ chart_->setMargins(QMargins(6, 6, 72, 36));
+ if (auto* l = chart_->layout())
+ l->setContentsMargins(0, 0, 0, 0);
+
+ series_ = new QCandlestickSeries;
+ series_->setIncreasingColor(QColor(colors::POSITIVE()));
+ series_->setDecreasingColor(QColor(colors::NEGATIVE()));
+ series_->setBodyWidth(0.78);
+ series_->setPen(QPen(Qt::NoPen)); // no outline on body
+ series_->setCapsVisible(false);
+ chart_->addSeries(series_);
+
+ time_axis_ = new QDateTimeAxis;
+ time_axis_->setFormat(QStringLiteral("HH:mm"));
+ time_axis_->setLabelsColor(QColor(colors::TEXT_SECONDARY()));
+ time_axis_->setLabelsFont(scene_font());
+ time_axis_->setGridLineColor(QColor(colors::BORDER_DIM()));
+ time_axis_->setMinorGridLineColor(QColor(colors::BG_RAISED()));
+ time_axis_->setLinePenColor(QColor(colors::BORDER_DIM()));
+ time_axis_->setTickCount(6);
+ chart_->addAxis(time_axis_, Qt::AlignBottom);
+ series_->attachAxis(time_axis_);
+
+ price_axis_ = new QValueAxis;
+ price_axis_->setLabelsColor(QColor(colors::TEXT_SECONDARY()));
+ price_axis_->setLabelsFont(scene_font());
+ price_axis_->setGridLineColor(QColor(colors::BORDER_DIM()));
+ price_axis_->setMinorGridLineColor(QColor(colors::BG_RAISED()));
+ price_axis_->setLinePenColor(QColor(colors::BORDER_DIM()));
+ price_axis_->setLabelFormat(QStringLiteral("%.2f"));
+ price_axis_->setTickCount(6);
+ chart_->addAxis(price_axis_, Qt::AlignRight);
+ series_->attachAxis(price_axis_);
+
+ // -- Last-price line (horizontal) ----------------------------------------
+ last_price_line_ = new QLineSeries;
+ last_price_line_->setUseOpenGL(false);
+ QPen last_pen;
+ last_pen.setColor(QColor(colors::AMBER()));
+ last_pen.setStyle(Qt::DashLine);
+ last_pen.setWidthF(1.0);
+ last_price_line_->setPen(last_pen);
+ chart_->addSeries(last_price_line_);
+ last_price_line_->attachAxis(time_axis_);
+ last_price_line_->attachAxis(price_axis_);
+
+ // -- Chart view ----------------------------------------------------------
+ chart_view_ = new HoverEquityChartView(chart_, this);
+ layout->addWidget(chart_view_, 1);
+
+ // -- Scene overlays (crosshair, price/time tags, last-price tag) ---------
+ auto* scene = chart_view_->scene();
+ QPen pen_grid;
+ pen_grid.setColor(QColor(colors::BORDER_BRIGHT()));
+ pen_grid.setStyle(Qt::DashLine);
+ pen_grid.setWidthF(0.8);
+
+ xhair_v_ = scene->addLine(QLineF(), pen_grid);
+ xhair_h_ = scene->addLine(QLineF(), pen_grid);
+ xhair_v_->setZValue(20);
+ xhair_h_->setZValue(20);
+ xhair_v_->setVisible(false);
+ xhair_h_->setVisible(false);
+
+ // Small dot at the crosshair intersection -- gives the user a clear
+ // anchor point and disambiguates which exact price/time the tags refer
+ // to when the cursor is moving fast.
+ QPen dot_pen;
+ dot_pen.setColor(QColor(colors::AMBER()));
+ dot_pen.setWidthF(1.0);
+ xhair_dot_ = scene->addEllipse(QRectF(-3, -3, 6, 6), dot_pen,
+ QBrush(QColor(colors::BG_BASE())));
+ xhair_dot_->setZValue(23);
+ xhair_dot_->setVisible(false);
+
+ auto build_tag = [&](QGraphicsRectItem*& bg, QGraphicsSimpleTextItem*& txt,
+ const QColor& fill, const QColor& text_color) {
+ bg = scene->addRect(QRectF(), QPen(Qt::NoPen), QBrush(fill));
+ bg->setZValue(21);
+ bg->setVisible(false);
+ txt = scene->addSimpleText(QStringLiteral(""));
+ txt->setBrush(QBrush(text_color));
+ txt->setFont(scene_font());
+ txt->setZValue(22);
+ txt->setVisible(false);
+ };
+ build_tag(price_tag_bg_, price_tag_txt_, QColor(colors::BG_RAISED()), QColor(colors::TEXT_PRIMARY()));
+ build_tag(time_tag_bg_, time_tag_txt_, QColor(colors::BG_RAISED()), QColor(colors::TEXT_PRIMARY()));
+ build_tag(last_tag_bg_, last_tag_txt_, QColor(colors::AMBER()), QColor(colors::BG_BASE()));
+
+ // -- OHLC tooltip pinned to top-left of the chart widget -----------------
+ ohlc_tooltip_ = new QLabel(chart_view_);
+ ohlc_tooltip_->setObjectName("eqChartOhlc");
+ ohlc_tooltip_->setVisible(false);
+ ohlc_tooltip_->setAttribute(Qt::WA_TransparentForMouseEvents);
+ ohlc_tooltip_->move(12, 12);
+
+ setMinimumHeight(280);
+
+ // --- Overlay engine ---
+ overlay_mgr_ = new fincept::ui::ChartOverlayManager(this);
+ overlay_mgr_->set_chart(chart_view_->scene(), chart_);
+
+ connect(chart_, &QChart::plotAreaChanged, this, [this](const QRectF&) {
+ overlay_mgr_->reposition_all();
+ });
+
+ indicator_picker_ = new fincept::ui::IndicatorPicker(overlay_mgr_, this);
+ layout->insertWidget(layout->indexOf(chart_view_), indicator_picker_);
+
+ connect(indicator_picker_, &fincept::ui::IndicatorPicker::indicator_requested,
+ this, [this](const QString& id) {
+ using namespace fincept::ui;
+ OverlayLayer* layer = nullptr;
+ if (id.startsWith("ema_")) {
+ int period = id.mid(4).toInt();
+ if (period <= 0) period = 21;
+ const QColor colors[] = {QColor("#d97706"), QColor("#16a34a"), QColor("#2563eb"), QColor("#dc2626")};
+ int idx = (period == 9) ? 0 : (period == 21) ? 1 : (period == 50) ? 2 : 3;
+ layer = new EmaLayer(period, colors[idx]);
+ } else if (id == "vwap") {
+ layer = new VwapLayer(true);
+ } else if (id.startsWith("bb_")) {
+ layer = new BollingerLayer();
+ } else if (id == "sr_auto") {
+ layer = new SupportResistanceLayer();
+ } else if (id == "pivot_std") {
+ layer = new PivotLayer();
+ }
+ if (layer)
+ overlay_mgr_->add_layer(layer);
+ });
+
+ connect(indicator_picker_, &fincept::ui::IndicatorPicker::indicator_removed,
+ this, [this](const QString& id) {
+ overlay_mgr_->remove_layer(id);
+ });
+}
+
+void EquityChart::set_active_tf(int idx) {
+ for (int i = 0; i < 6; ++i) {
+ tf_buttons_[i]->setProperty("active", i == idx);
+ if (auto* st = tf_buttons_[i]->style()) {
+ st->unpolish(tf_buttons_[i]);
+ st->polish(tf_buttons_[i]);
+ }
+ }
+ active_tf_ = idx;
+ emit timeframe_changed(TF_LABELS[idx]);
+}
+
+QString EquityChart::current_timeframe() const {
+ return TF_LABELS[active_tf_];
}
void EquityChart::set_candles(const QVector<trading::BrokerCandle>& candles) {
- canvas_->set_candles(candles);
+ candles_ = candles;
+ rebuild_chart();
+
+ // Overlay layers must use synthetic timestamps so their QLineSeries
+ // align with the chart's gap-free X axis.
+ QVector<fincept::ui::CandleData> synth_candles;
+ synth_candles.reserve(display_count_);
+ for (int i = display_start_; i < display_start_ + display_count_ && i < candles_.size(); ++i) {
+ const auto& c = candles_[i];
+ synth_candles.append({synth_ts_for(i), c.open, c.high, c.low, c.close, c.volume});
+ }
+ overlay_mgr_->set_candles(std::move(synth_candles));
+
+ apply_tf_axis_format();
+ update_last_price_marker();
+}
+
+void EquityChart::recompute_bounds() {
+ const auto& sets = series_->sets();
+ if (sets.isEmpty()) {
+ cached_min_price_ = -1;
+ cached_max_price_ = -1;
+ bounds_dirty_ = false;
+ return;
+ }
+ double mn = 1e18, mx = 0;
+ for (const auto* s : sets) {
+ mn = std::min(mn, s->low());
+ mx = std::max(mx, s->high());
+ }
+ cached_min_price_ = mn;
+ cached_max_price_ = mx;
+ bounds_dirty_ = false;
}
void EquityChart::clear() {
- canvas_->clear();
+ candles_.clear();
+ series_->clear();
+ if (last_price_line_) last_price_line_->clear();
+ cached_min_price_ = cached_max_price_ = -1;
+ bounds_dirty_ = true;
+ if (last_tag_bg_) last_tag_bg_->setVisible(false);
+ if (last_tag_txt_) last_tag_txt_->setVisible(false);
+ on_hover_leave();
}
-QString EquityChart::current_timeframe() const {
- return TF_LABELS[active_tf_];
+void EquityChart::update_axes(double min_price, double max_price, qint64 min_time, qint64 max_time) {
+ if (min_price >= max_price)
+ return;
+
+ // Expand price range to include overlay levels (pivots, S/R)
+ double overlay_min = 0, overlay_max = 0;
+ if (overlay_mgr_->overlay_price_range(overlay_min, overlay_max)) {
+ min_price = std::min(min_price, overlay_min);
+ max_price = std::max(max_price, overlay_max);
+ }
+
+ const double padding = (max_price - min_price) * 0.06;
+ const double p_min = min_price - padding;
+ const double p_max = max_price + padding;
+
+ if (p_min != last_min_price_ || p_max != last_max_price_) {
+ price_axis_->setRange(p_min, p_max);
+ last_min_price_ = p_min;
+ last_max_price_ = p_max;
+ }
+
+ qint64 effective_max = max_time;
+ if (min_time >= max_time) {
+ effective_max = min_time + tf_slot_ms(TF_LABELS[active_tf_]);
+ } else {
+ // Add half-a-slot of right padding so the latest candle isn't pinned
+ // to the right edge of the plot -- looks more like a real terminal.
+ effective_max = max_time + tf_slot_ms(TF_LABELS[active_tf_]) / 2;
+ }
+
+ if (min_time != last_min_time_ || effective_max != last_max_time_) {
+ time_axis_->setRange(QDateTime::fromMSecsSinceEpoch(min_time),
+ QDateTime::fromMSecsSinceEpoch(effective_max));
+ last_min_time_ = min_time;
+ last_max_time_ = effective_max;
+ }
+
+ overlay_mgr_->reposition_all();
}
-void EquityChart::set_active_tf(int idx) {
- if (idx == active_tf_)
+void EquityChart::apply_tf_axis_format() {
+ if (!time_axis_ || candles_.isEmpty()) return;
+ // Use real time span (not synthetic) to pick the right label format.
+ const int64_t real_first = candles_[display_start_].timestamp;
+ const int64_t real_last = candles_.last().timestamp;
+ const qint64 real_span = std::max<qint64>(0, real_last - real_first);
+ time_axis_->setFormat(time_format_for(real_span));
+}
+
+int64_t EquityChart::synth_ts_for(int candle_index) const {
+ return synth_base_ts_ + static_cast<int64_t>(candle_index - display_start_) * synth_slot_ms_;
+}
+
+int EquityChart::candle_index_from_synth(int64_t synth_ts) const {
+ if (synth_slot_ms_ <= 0) return display_start_;
+ int idx = display_start_ + static_cast<int>((synth_ts - synth_base_ts_) / synth_slot_ms_);
+ return std::clamp(idx, display_start_, display_start_ + display_count_ - 1);
+}
+
+const trading::BrokerCandle* EquityChart::candle_near_synth(int64_t synth_ts) const {
+ const int idx = candle_index_from_synth(synth_ts);
+ if (idx >= 0 && idx < candles_.size())
+ return &candles_[idx];
+ return nullptr;
+}
+
+void EquityChart::rebuild_chart() {
+ series_->clear();
+ last_min_price_ = last_max_price_ = -1;
+ last_min_time_ = last_max_time_ = -1;
+ cached_min_price_ = cached_max_price_ = -1;
+ bounds_dirty_ = true;
+
+ if (candles_.isEmpty())
return;
- for (int i = 0; i < 6; ++i) {
- tf_buttons_[i]->setProperty("active", i == idx);
- tf_buttons_[i]->style()->unpolish(tf_buttons_[i]);
- tf_buttons_[i]->style()->polish(tf_buttons_[i]);
+
+ const int start = std::max(0, static_cast<int>(candles_.size()) - MAX_VISIBLE);
+ display_start_ = start;
+ display_count_ = 0;
+
+ synth_slot_ms_ = tf_slot_ms(TF_LABELS[active_tf_]);
+ synth_base_ts_ = candles_[start].timestamp;
+
+ double min_price = 1e18, max_price = 0;
+ qint64 min_synth = INT64_MAX, max_synth = 0;
+
+ for (int i = start; i < candles_.size(); ++i) {
+ const auto& c = candles_[i];
+ if (c.open <= 0.0 || c.high <= 0.0 || c.low <= 0.0 || c.close <= 0.0 || c.timestamp <= 0)
+ continue;
+ if (c.low > c.high || c.open > c.high || c.close > c.high)
+ continue;
+
+ const int64_t synth = synth_ts_for(i);
+ series_->append(new QCandlestickSet(c.open, c.high, c.low, c.close, synth));
+ ++display_count_;
+
+ min_price = std::min(min_price, c.low);
+ max_price = std::max(max_price, c.high);
+ if (synth < min_synth) min_synth = synth;
+ if (synth > max_synth) max_synth = synth;
}
- active_tf_ = idx;
- emit timeframe_changed(TF_LABELS[idx]);
+
+ if (min_price < max_price) {
+ cached_min_price_ = min_price;
+ cached_max_price_ = max_price;
+ bounds_dirty_ = false;
+ }
+
+ update_axes(min_price, max_price, min_synth, max_synth);
+}
+
+void EquityChart::update_last_price_marker() {
+ if (!last_price_line_ || candles_.isEmpty()) {
+ if (last_tag_bg_) last_tag_bg_->setVisible(false);
+ if (last_tag_txt_) last_tag_txt_->setVisible(false);
+ return;
+ }
+ const auto& last = candles_.last();
+ const double price = last.close;
+ const bool up = last.close >= last.open;
+ last_price_line_->clear();
+ last_price_line_->append(static_cast<qreal>(last_min_time_), price);
+ last_price_line_->append(static_cast<qreal>(last_max_time_), price);
+
+ QPen pen = last_price_line_->pen();
+ pen.setColor(QColor(up ? colors::POSITIVE() : colors::NEGATIVE()));
+ last_price_line_->setPen(pen);
+
+ // Update the always-visible "last price" tag on the right axis.
+ if (last_tag_bg_ && last_tag_txt_ && chart_) {
+ const QPointF anchor = chart_->mapToPosition(QPointF(last_max_time_, price), series_);
+ const QString text = QString::number(price, 'f', 2);
+ last_tag_txt_->setText(text);
+ const QRectF tb = last_tag_txt_->boundingRect();
+ const qreal pad_x = 6, pad_y = 2;
+ const qreal x = chart_->plotArea().right() + 2;
+ const qreal y = anchor.y() - tb.height() / 2 - pad_y;
+ last_tag_bg_->setRect(QRectF(x, y, tb.width() + 2 * pad_x, tb.height() + 2 * pad_y));
+ last_tag_bg_->setBrush(QBrush(QColor(up ? colors::POSITIVE() : colors::NEGATIVE())));
+ last_tag_txt_->setPos(x + pad_x, y + pad_y);
+ last_tag_bg_->setVisible(true);
+ last_tag_txt_->setVisible(true);
+ }
+}
+
+void EquityChart::on_hover_position(const QPointF& chart_value_pos, const QPoint& view_pos) {
+ if (!chart_ || candles_.isEmpty()) return;
+
+ const QRectF plot = chart_->plotArea();
+ if (!plot.contains(view_pos)) {
+ on_hover_leave();
+ return;
+ }
+
+ // Crosshair lines: stop a half-pixel before the plot edge so they don't
+ // bleed into the axis labels at the bottom-right corner.
+ const qreal cx = view_pos.x();
+ const qreal cy = view_pos.y();
+ xhair_v_->setLine(cx, plot.top(), cx, plot.bottom());
+ xhair_h_->setLine(plot.left(), cy, plot.right(), cy);
+ xhair_v_->setVisible(true);
+ xhair_h_->setVisible(true);
+
+ // Intersection dot, centred on the cursor.
+ if (xhair_dot_) {
+ xhair_dot_->setRect(cx - 3, cy - 3, 6, 6);
+ xhair_dot_->setVisible(true);
+ }
+
+ // While the cursor is over the chart, hide the always-visible "last
+ // price" tag -- otherwise it overlaps the live cursor price tag whenever
+ // the cursor sits at the same y-level as the last close.
+ if (last_tag_bg_) last_tag_bg_->setVisible(false);
+ if (last_tag_txt_) last_tag_txt_->setVisible(false);
+
+ constexpr qreal kPadX = 6;
+ constexpr qreal kPadY = 3;
+
+ // -- Price tag (right of plot) -------------------------------------------
+ // Clamp Y so the tag never extends past the plot edges into the time tag.
+ {
+ const double price = chart_value_pos.y();
+ price_tag_txt_->setText(QString::number(price, 'f', 2));
+ const QRectF tb = price_tag_txt_->boundingRect();
+ const qreal w = tb.width() + 2 * kPadX;
+ const qreal h = tb.height() + 2 * kPadY;
+ const qreal x = plot.right() + 4;
+ qreal y = cy - h / 2.0;
+ y = std::max(plot.top(), std::min(y, plot.bottom() - h));
+ price_tag_bg_->setRect(QRectF(x, y, w, h));
+ price_tag_txt_->setPos(x + kPadX, y + kPadY);
+ price_tag_bg_->setVisible(true);
+ price_tag_txt_->setVisible(true);
+ }
+
+ // -- Time tag (below plot) -----------------------------------------------
+ // Map synthetic timestamp back to real timestamp for display.
+ {
+ const qint64 synth_ms = static_cast<qint64>(chart_value_pos.x());
+ const auto* nearest = candle_near_synth(synth_ms);
+ const qint64 real_ms = nearest ? nearest->timestamp : synth_ms;
+ const int64_t real_first = (display_start_ < candles_.size()) ? candles_[display_start_].timestamp : 0;
+ const int64_t real_last = candles_.isEmpty() ? 0 : candles_.last().timestamp;
+ const QString fmt = time_format_for(std::max<qint64>(0, real_last - real_first));
+ time_tag_txt_->setText(QDateTime::fromMSecsSinceEpoch(real_ms).toString(fmt));
+ const QRectF tb = time_tag_txt_->boundingRect();
+ const qreal w = tb.width() + 2 * kPadX;
+ const qreal h = tb.height() + 2 * kPadY;
+ qreal x = cx - w / 2.0;
+ x = std::max(plot.left(), std::min(x, plot.right() - w));
+ const qreal y = plot.bottom() + 4;
+ time_tag_bg_->setRect(QRectF(x, y, w, h));
+ time_tag_txt_->setPos(x + kPadX, y + kPadY);
+ time_tag_bg_->setVisible(true);
+ time_tag_txt_->setVisible(true);
+ }
+
+ // -- OHLC tooltip --------------------------------------------------------
+ // Map synthetic timestamp to candle index for direct lookup.
+ const qint64 synth_cursor = static_cast<qint64>(chart_value_pos.x());
+ const trading::BrokerCandle* hit = candle_near_synth(synth_cursor);
+ if (hit) {
+ const bool up = hit->close >= hit->open;
+ const double pct = (hit->close - hit->open) / std::max(1e-12, hit->open) * 100.0;
+ const QString chg = QString("%1%2%")
+ .arg(pct >= 0 ? QStringLiteral("+") : QString())
+ .arg(QString::number(pct, 'f', 2));
+ const QString time_str =
+ QDateTime::fromMSecsSinceEpoch(hit->timestamp).toString(QStringLiteral("MMM dd HH:mm"));
+ const QString dir_color = up ? QString::fromLatin1(colors::POSITIVE())
+ : QString::fromLatin1(colors::NEGATIVE());
+ const QString dim = QString::fromLatin1(colors::TEXT_TERTIARY());
+ const QString fg = QString::fromLatin1(colors::TEXT_PRIMARY());
+ const QString green = QString::fromLatin1(colors::POSITIVE());
+ const QString red = QString::fromLatin1(colors::NEGATIVE());
+
+ // Vertical layout: header row + four label/value rows + change row.
+ // Numeric values use a fixed-width <td> so different price magnitudes
+ // (e.g. 79655.40 vs 9.50) don't push the values into different
+ // columns from row to row. font-family:Consolas keeps digits aligned.
+ const QString tpl = QStringLiteral(
+ "<div style='font-family:Consolas,Courier New,monospace;'>"
+ "<div style='color:%1;font-size:10px;font-weight:700;letter-spacing:0.8px;"
+ " margin-bottom:6px;'>%2</div>"
+ "<table cellspacing='0' cellpadding='0' style='border-spacing:0;font-size:12px;'>"
+ "<tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;'>O</td>"
+ " <td style='color:%3;text-align:right;'>%4</td>"
+ "</tr><tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;padding-top:1px;'>H</td>"
+ " <td style='color:%5;text-align:right;padding-top:1px;'>%6</td>"
+ "</tr><tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;padding-top:1px;'>L</td>"
+ " <td style='color:%7;text-align:right;padding-top:1px;'>%8</td>"
+ "</tr><tr>"
+ " <td style='color:%1;font-weight:700;padding-right:10px;padding-top:1px;'>C</td>"
+ " <td style='color:%9;text-align:right;font-weight:700;padding-top:1px;'>%10</td>"
+ "</tr><tr>"
+ " <td colspan='2' style='padding-top:6px;color:%9;font-weight:700;text-align:right;"
+ " border-top:1px solid #1a1a1a;'>%11</td>"
+ "</tr>"
+ "</table>"
+ "</div>");
+ ohlc_tooltip_->setText(tpl
+ .arg(dim) // %1 dim/label colour
+ .arg(time_str) // %2 timestamp
+ .arg(fg) // %3 open colour
+ .arg(QString::number(hit->open, 'f', 2)) // %4
+ .arg(green) // %5 high colour
+ .arg(QString::number(hit->high, 'f', 2)) // %6
+ .arg(red) // %7 low colour
+ .arg(QString::number(hit->low, 'f', 2)) // %8
+ .arg(dir_color) // %9 close + delta%
+ .arg(QString::number(hit->close, 'f', 2)) // %10
+ .arg(chg)); // %11
+ ohlc_tooltip_->adjustSize();
+ ohlc_tooltip_->setVisible(true);
+ }
+}
+
+void EquityChart::on_hover_leave() {
+ if (xhair_v_) xhair_v_->setVisible(false);
+ if (xhair_h_) xhair_h_->setVisible(false);
+ if (xhair_dot_) xhair_dot_->setVisible(false);
+ if (price_tag_bg_) price_tag_bg_->setVisible(false);
+ if (price_tag_txt_)price_tag_txt_->setVisible(false);
+ if (time_tag_bg_) time_tag_bg_->setVisible(false);
+ if (time_tag_txt_) time_tag_txt_->setVisible(false);
+ if (ohlc_tooltip_) ohlc_tooltip_->setVisible(false);
+ // Bring the always-visible last-price tag back now that the cursor's
+ // gone -- recompute in case anything moved while we were hovering.
+ update_last_price_marker();
}
} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/EquityChart.h b/fincept-qt/src/screens/equity_trading/EquityChart.h
index cb8fdfa4f..62e393c59 100644
--- a/fincept-qt/src/screens/equity_trading/EquityChart.h
+++ b/fincept-qt/src/screens/equity_trading/EquityChart.h
@@ -1,64 +1,105 @@
#pragma once
-// Equity Chart — Custom-painted candlestick chart with timeframe toggle buttons
-// Uses QPainter directly — no QCandlestickSeries (which has QDateTimeAxis gaps).
+// Equity Chart — Qt Charts candlestick chart with overlays.
+// Upgraded from QPainter to share overlay infrastructure with CryptoChart.
#include "trading/TradingTypes.h"
+#include "ui/charts/ChartOverlayManager.h"
-#include <QLabel>
#include <QPushButton>
#include <QVector>
#include <QWidget>
-namespace fincept::screens::equity {
-
-// ── Canvas: draws candles via QPainter ───────────────────────────────────────
-class CandleCanvas : public QWidget {
- Q_OBJECT
- public:
- explicit CandleCanvas(QWidget* parent = nullptr);
-
- void set_candles(const QVector<trading::BrokerCandle>& candles);
- void clear();
+class QChartView;
+class QChart;
+class QCandlestickSeries;
+class QLineSeries;
+class QDateTimeAxis;
+class QValueAxis;
+class QGraphicsLineItem;
+class QGraphicsRectItem;
+class QGraphicsEllipseItem;
+class QGraphicsSimpleTextItem;
+class QLabel;
- protected:
- void paintEvent(QPaintEvent*) override;
- void resizeEvent(QResizeEvent*) override;
+namespace fincept::ui { class IndicatorPicker; }
- private:
- void rebuild_cache();
-
- QVector<trading::BrokerCandle> candles_;
- QPixmap cache_;
- bool dirty_ = true;
+namespace fincept::screens::equity {
- static constexpr int MAX_VISIBLE = 120;
- static constexpr int PRICE_AXIS_W = 70; // pixels reserved for price labels on right
- static constexpr int TIME_AXIS_H = 20; // pixels reserved for time labels at bottom
- static constexpr int LABEL_STEP = 20; // draw a time label every N candles
-};
+class HoverEquityChartView;
-// ── EquityChart: header + canvas ─────────────────────────────────────────────
class EquityChart : public QWidget {
Q_OBJECT
- public:
+public:
explicit EquityChart(QWidget* parent = nullptr);
void set_candles(const QVector<trading::BrokerCandle>& candles);
void clear();
QString current_timeframe() const;
+ fincept::ui::ChartOverlayManager* overlay_manager() const { return overlay_mgr_; }
- signals:
+signals:
void timeframe_changed(const QString& tf);
- private:
+private:
+ void rebuild_chart();
+ void update_axes(double min_price, double max_price, qint64 min_time, qint64 max_time);
void set_active_tf(int idx);
+ void apply_tf_axis_format();
+ void update_last_price_marker();
+ void on_hover_position(const QPointF& chart_value_pos, const QPoint& view_pos);
+ void on_hover_leave();
+
+ HoverEquityChartView* chart_view_ = nullptr;
+ QChart* chart_ = nullptr;
+ QCandlestickSeries* series_ = nullptr;
+ QDateTimeAxis* time_axis_ = nullptr;
+ QValueAxis* price_axis_ = nullptr;
+ QLineSeries* last_price_line_ = nullptr;
+
+ QGraphicsLineItem* xhair_v_ = nullptr;
+ QGraphicsLineItem* xhair_h_ = nullptr;
+ QGraphicsEllipseItem* xhair_dot_ = nullptr;
+ QGraphicsRectItem* price_tag_bg_ = nullptr;
+ QGraphicsSimpleTextItem* price_tag_txt_ = nullptr;
+ QGraphicsRectItem* time_tag_bg_ = nullptr;
+ QGraphicsSimpleTextItem* time_tag_txt_ = nullptr;
+ QGraphicsRectItem* last_tag_bg_ = nullptr;
+ QGraphicsSimpleTextItem* last_tag_txt_ = nullptr;
+
+ QLabel* ohlc_tooltip_ = nullptr;
- CandleCanvas* canvas_ = nullptr;
QPushButton* tf_buttons_[6] = {};
int active_tf_ = 2; // default "15m"
-
static constexpr const char* TF_LABELS[] = {"1m", "5m", "15m", "1h", "1d", "1w"};
+
+ QVector<trading::BrokerCandle> candles_;
+ static constexpr int MAX_VISIBLE = 120;
+
+ double last_min_price_ = -1;
+ double last_max_price_ = -1;
+ qint64 last_min_time_ = -1;
+ qint64 last_max_time_ = -1;
+ double cached_min_price_ = -1;
+ double cached_max_price_ = -1;
+ bool bounds_dirty_ = true;
+ void recompute_bounds();
+
+ // Synthetic sequential timestamps — eliminates QDateTimeAxis gaps for
+ // non-trading hours. Each visible candle gets evenly-spaced synthetic
+ // timestamps; real timestamps are looked up from candles_ by index.
+ int64_t synth_base_ts_ = 0; // synthetic timestamp of first visible candle
+ int64_t synth_slot_ms_ = 0; // slot width in ms
+ int display_start_ = 0; // index into candles_ of first visible candle
+ int display_count_ = 0; // number of visible candles
+ int64_t synth_ts_for(int candle_index) const;
+ int candle_index_from_synth(int64_t synth_ts) const;
+ const trading::BrokerCandle* candle_near_synth(int64_t synth_ts) const;
+
+ fincept::ui::ChartOverlayManager* overlay_mgr_ = nullptr;
+ fincept::ui::IndicatorPicker* indicator_picker_ = nullptr;
+
+ friend class HoverEquityChartView;
};
} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderBook.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderBook.cpp
index 3b2d7e5ac..9d97f384d 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderBook.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderBook.cpp
@@ -35,6 +35,7 @@ namespace fincept::screens::equity {
EquityOrderBook::EquityOrderBook(QWidget* parent) : QWidget(parent) {
setObjectName("eqOrderBook");
+ setMinimumHeight(HEADER_H + ROW_H * 11 + SPREAD_H); // header + 5 asks + header row + 5 bids + spread
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this]() { update(); });
auto* layout = new QVBoxLayout(this);
@@ -65,7 +66,7 @@ EquityOrderBook::EquityOrderBook(QWidget* parent) : QWidget(parent) {
canvas_ = new QWidget(this);
canvas_->setObjectName("eqObCanvas");
canvas_->setAttribute(Qt::WA_TransparentForMouseEvents);
- canvas_->setMinimumHeight(100);
+ canvas_->setMinimumHeight(ROW_H * 10 + ROW_H); // 5 asks + 5 bids + header row
layout->addWidget(canvas_, 1);
layout->addWidget(spread_label_);
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 58c28c0e6..dc2fe6741 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -116,6 +116,9 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
DataStreamManager::instance().start_all_active();
DataStreamManager::instance().resume_all();
+ // Hub subscriptions for streaming data (D4)
+ hub_subscribe_streaming();
+
// UI-local timers
if (clock_timer_)
clock_timer_->start();
@@ -132,6 +135,7 @@ void EquityTradingScreen::showEvent(QShowEvent* event) {
void EquityTradingScreen::hideEvent(QHideEvent* event) {
QWidget::hideEvent(event);
+ hub_unsubscribe_all();
DataStreamManager::instance().pause_all();
if (clock_timer_)
clock_timer_->stop();
@@ -143,7 +147,7 @@ void EquityTradingScreen::hideEvent(QHideEvent* event) {
{"selected_symbol", selected_symbol_},
{"selected_exchange", selected_exchange_},
});
- LOG_INFO(TAG, "Screen hidden — data streams paused");
+ LOG_INFO(TAG, "Screen hidden — data streams paused, hub unsubscribed");
}
// ============================================================================
@@ -360,18 +364,9 @@ void EquityTradingScreen::update_clock() {
void EquityTradingScreen::connect_data_stream_signals() {
auto& dsm = DataStreamManager::instance();
- connect(&dsm, &DataStreamManager::quote_updated,
- this, &EquityTradingScreen::on_stream_quote_updated);
- connect(&dsm, &DataStreamManager::watchlist_updated,
- this, &EquityTradingScreen::on_stream_watchlist_updated);
- connect(&dsm, &DataStreamManager::positions_updated,
- this, &EquityTradingScreen::on_stream_positions_updated);
- connect(&dsm, &DataStreamManager::holdings_updated,
- this, &EquityTradingScreen::on_stream_holdings_updated);
- connect(&dsm, &DataStreamManager::orders_updated,
- this, &EquityTradingScreen::on_stream_orders_updated);
- connect(&dsm, &DataStreamManager::funds_updated,
- this, &EquityTradingScreen::on_stream_funds_updated);
+ // Streaming data (quotes, positions, holdings, orders, funds) now comes
+ // via DataHub subscriptions — see hub_subscribe_streaming().
+ // Only on-demand / one-shot signals remain wired here.
connect(&dsm, &DataStreamManager::candles_fetched,
this, &EquityTradingScreen::on_stream_candles_fetched);
connect(&dsm, &DataStreamManager::orderbook_fetched,
@@ -384,6 +379,10 @@ void EquityTradingScreen::connect_data_stream_signals() {
this, &EquityTradingScreen::on_stream_calendar_fetched);
connect(&dsm, &DataStreamManager::clock_fetched,
this, &EquityTradingScreen::on_stream_clock_fetched);
+ connect(&dsm, &DataStreamManager::connection_state_changed,
+ this, [this](const QString& /*account_id*/, ConnectionState /*state*/) {
+ update_connection_status();
+ });
connect(&dsm, &DataStreamManager::token_expired,
this, &EquityTradingScreen::handle_token_expired);
}
@@ -507,13 +506,19 @@ void EquityTradingScreen::update_account_menu() {
void EquityTradingScreen::update_connection_status() {
const auto accounts = AccountManager::instance().active_accounts();
int connected = 0;
+ int expired = 0;
for (const auto& a : accounts) {
if (a.state == ConnectionState::Connected)
++connected;
+ else if (a.state == ConnectionState::TokenExpired)
+ ++expired;
}
if (accounts.isEmpty()) {
conn_label_->setText("○ NO ACCOUNTS");
conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::TEXT_TERTIARY()));
+ } else if (expired > 0 && connected == 0) {
+ conn_label_->setText(QString::fromUtf8("\xe2\x9a\xa0 TOKEN EXPIRED \xe2\x80\x94 click ACCOUNTS"));
+ conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::NEGATIVE()));
} else if (connected == accounts.size()) {
conn_label_->setText(QString("● %1/%2 CONNECTED").arg(connected).arg(accounts.size()));
conn_label_->setStyleSheet(QString("color: %1; font-size: 10px; font-weight: 700;").arg(ui::colors::POSITIVE()));
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index 98d72ade5..f43e0abde 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -9,6 +9,7 @@
#include "trading/BrokerAccount.h"
#include "trading/TradingTypes.h"
+#include <QHash>
#include <QHideEvent>
#include <QLabel>
#include <QLineEdit>
@@ -68,13 +69,7 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void refresh_candles();
void update_clock();
- // DataStreamManager signal handlers
- void on_stream_quote_updated(const QString& account_id, const QString& symbol, const trading::BrokerQuote& quote);
- void on_stream_watchlist_updated(const QString& account_id, const QVector<trading::BrokerQuote>& quotes);
- void on_stream_positions_updated(const QString& account_id, const QVector<trading::BrokerPosition>& positions);
- void on_stream_holdings_updated(const QString& account_id, const QVector<trading::BrokerHolding>& holdings);
- void on_stream_orders_updated(const QString& account_id, const QVector<trading::BrokerOrderInfo>& orders);
- void on_stream_funds_updated(const QString& account_id, const trading::BrokerFunds& funds);
+ // DataStreamManager signal handlers (on-demand / one-shot — kept as legacy signals)
void on_stream_candles_fetched(const QString& account_id, const QVector<trading::BrokerCandle>& candles);
void on_stream_orderbook_fetched(const QString& account_id,
const QVector<QPair<double, double>>& bids,
@@ -97,6 +92,12 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void update_connection_status();
void async_modify_order(const QString& order_id, double qty, double price);
+ // DataHub subscription helpers (D4 migration)
+ void hub_subscribe_streaming();
+ void hub_unsubscribe_all();
+ void hub_subscribe_quotes();
+ QString broker_id_for_focused() const;
+
// ── Command bar widgets ──
QPushButton* account_btn_ = nullptr; // shows focused account name
QMenu* account_menu_ = nullptr; // lists all active accounts
@@ -134,6 +135,8 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
double current_price_ = 0.0; // last known LTP for selected symbol
bool initialized_ = false;
+ bool hub_active_ = false;
+ QHash<QString, trading::BrokerQuote> watchlist_quote_cache_;
// Symbol group link — SymbolGroup::None when unlinked.
SymbolGroup link_group_ = SymbolGroup::None;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index abb68d36c..30fa9f7dd 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -113,6 +113,10 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
order_entry_->set_symbol(selected_symbol_);
order_entry_->set_exchange(selected_exchange_);
+ // Resubscribe hub topics for new focused account
+ if (isVisible())
+ hub_subscribe_streaming();
+
// Ensure stream is running and configure it. Skip data fetches when the
// account has no credentials yet — every fetch_* spawns a QtConcurrent
// thread that bails on an empty api_key check inside the lambda. Firing
@@ -177,6 +181,10 @@ void EquityTradingScreen::switch_symbol(const QString& symbol) {
order_entry_->set_symbol(symbol);
watchlist_->set_active_symbol(symbol);
+ // Resubscribe quote topics so the new symbol gets a hub subscription
+ if (isVisible() && hub_active_)
+ hub_subscribe_streaming();
+
// Publish to the linked group so other panels (Watchlist, EquityResearch,
// News, Derivatives, SurfaceAnalytics) follow. `this` as source suppresses
// the echo back into this screen.
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
index a2b972bf6..0ec7e9970 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Streams.cpp
@@ -1,142 +1,168 @@
// src/screens/equity_trading/EquityTradingScreen_Streams.cpp
//
-// DataStream broker→UI slots: per-stream callbacks that propagate quote,
-// watchlist, positions, holdings, orders, funds, candles, orderbook,
-// time/sales, latest trade, calendar, and market clock updates into the
-// screen widgets.
+// DataHub subscription wiring (D4 migration) + on-demand legacy signal slots.
+//
+// Streaming data (quotes, positions, holdings, orders, funds) is consumed
+// via DataHub::subscribe() instead of direct DataStreamManager signals.
+// On-demand / one-shot data (candles, orderbook, time/sales, calendar, clock)
+// remains wired as legacy signals — no hub topic exists for those.
//
// Part of the partial-class split of EquityTradingScreen.cpp.
#include "screens/equity_trading/EquityTradingScreen.h"
#include "core/logging/Logger.h"
-#include "core/session/ScreenStateManager.h"
-#include "core/symbol/SymbolContext.h"
-#include "core/symbol/SymbolDragSource.h"
-#include "screens/equity_trading/AccountManagementDialog.h"
-#include "screens/equity_trading/BroadcastOrderDialog.h"
+#include "datahub/DataHub.h"
+#include "datahub/DataHubMetaTypes.h"
#include "screens/equity_trading/EquityBottomPanel.h"
#include "screens/equity_trading/EquityChart.h"
#include "screens/equity_trading/EquityOrderBook.h"
#include "screens/equity_trading/EquityOrderEntry.h"
#include "screens/equity_trading/EquityTickerBar.h"
#include "screens/equity_trading/EquityWatchlist.h"
-#include "services/portfolio/PortfolioService.h"
-#include "storage/repositories/SettingsRepository.h"
#include "trading/AccountManager.h"
-#include "trading/BrokerRegistry.h"
+#include "trading/BrokerTopic.h"
#include "trading/DataStreamManager.h"
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
-#include "ui/theme/StyleSheets.h"
-#include "ui/theme/Theme.h"
-
-#include <QApplication>
-#include <QCheckBox>
-#include <QComboBox>
-#include <QCompleter>
-#include <QDate>
-#include <QDateTime>
-#include <QDialog>
-#include <QDialogButtonBox>
-#include <QFormLayout>
-#include <QHBoxLayout>
-#include <QHash>
-#include <QHeaderView>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QLineEdit>
-#include <QMessageBox>
-#include <QMouseEvent>
-#include <QPointer>
-#include <QPushButton>
-#include <QRadioButton>
-#include <QScrollBar>
-#include <QSplitter>
-#include <QStringListModel>
-#include <QTableWidget>
-#include <QVBoxLayout>
-
-#include <memory>
-
-#include <QtConcurrent/QtConcurrent>
namespace fincept::screens {
using namespace fincept::trading;
using namespace fincept::screens::equity;
-void EquityTradingScreen::on_stream_quote_updated(const QString& account_id, const QString& symbol,
- const BrokerQuote& quote) {
- // Update UI only for focused account's selected symbol
- if (account_id == focused_account_id_ && symbol == selected_symbol_) {
- current_price_ = quote.ltp;
- ticker_bar_->update_quote(quote.ltp, quote.change, quote.change_pct, quote.high, quote.low,
- quote.volume, quote.bid, quote.ask);
- order_entry_->set_current_price(quote.ltp);
- }
+static const QString TAG = "EquityTrading";
- // Feed ALL account quotes into paper trading engine for order matching
- auto account = AccountManager::instance().get_account(account_id);
- if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty() && quote.ltp > 0) {
- pt_update_position_price(account.paper_portfolio_id, symbol, quote.ltp);
- PriceData pd;
- pd.last = quote.ltp;
- pd.bid = quote.bid;
- pd.ask = quote.ask;
- pd.timestamp = quote.timestamp;
- OrderMatcher::instance().check_orders(symbol, pd, account.paper_portfolio_id);
- OrderMatcher::instance().check_sl_tp_triggers(account.paper_portfolio_id, symbol, quote.ltp);
- }
-}
+// ============================================================================
+// DataHub subscription helpers (D4)
+// ============================================================================
-void EquityTradingScreen::on_stream_watchlist_updated(const QString& account_id,
- const QVector<BrokerQuote>& quotes) {
- if (account_id == focused_account_id_)
- watchlist_->update_quotes(quotes);
-
- // Feed into paper trading for all accounts
- auto account = AccountManager::instance().get_account(account_id);
- if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty()) {
- for (const auto& q : quotes) {
- if (q.ltp <= 0)
- continue;
- pt_update_position_price(account.paper_portfolio_id, q.symbol, q.ltp);
- PriceData pd;
- pd.last = q.ltp;
- pd.bid = q.bid;
- pd.ask = q.ask;
- pd.timestamp = q.timestamp;
- OrderMatcher::instance().check_orders(q.symbol, pd, account.paper_portfolio_id);
- }
- }
+QString EquityTradingScreen::broker_id_for_focused() const {
+ if (focused_account_id_.isEmpty())
+ return {};
+ return AccountManager::instance().get_account(focused_account_id_).broker_id;
}
-void EquityTradingScreen::on_stream_positions_updated(const QString& account_id,
- const QVector<BrokerPosition>& positions) {
- if (account_id == focused_account_id_)
- bottom_panel_->set_positions(positions);
+void EquityTradingScreen::hub_subscribe_streaming() {
+ auto& hub = datahub::DataHub::instance();
+ hub.unsubscribe(this);
+ hub_active_ = false;
+ watchlist_quote_cache_.clear();
+
+ const QString bid = broker_id_for_focused();
+ if (bid.isEmpty() || focused_account_id_.isEmpty())
+ return;
+
+ const QString aid = focused_account_id_;
+
+ // ── Positions ──
+ hub.subscribe(this, broker_topic(bid, aid, QStringLiteral("positions")),
+ [this](const QVariant& v) {
+ if (!v.canConvert<QVector<BrokerPosition>>())
+ return;
+ bottom_panel_->set_positions(v.value<QVector<BrokerPosition>>());
+ });
+
+ // ── Holdings ──
+ hub.subscribe(this, broker_topic(bid, aid, QStringLiteral("holdings")),
+ [this](const QVariant& v) {
+ if (!v.canConvert<QVector<BrokerHolding>>())
+ return;
+ bottom_panel_->set_holdings(v.value<QVector<BrokerHolding>>());
+ });
+
+ // ── Orders ──
+ hub.subscribe(this, broker_topic(bid, aid, QStringLiteral("orders")),
+ [this](const QVariant& v) {
+ if (!v.canConvert<QVector<BrokerOrderInfo>>())
+ return;
+ bottom_panel_->set_orders(v.value<QVector<BrokerOrderInfo>>());
+ });
+
+ // ── Balance / Funds ──
+ hub.subscribe(this, broker_topic(bid, aid, QStringLiteral("balance")),
+ [this](const QVariant& v) {
+ if (!v.canConvert<BrokerFunds>())
+ return;
+ const auto funds = v.value<BrokerFunds>();
+ bottom_panel_->set_funds(funds);
+ order_entry_->set_balance(funds.available_balance);
+ });
+
+ // ── Quotes (per-symbol subscriptions for ticker + watchlist + paper trading) ──
+ hub_subscribe_quotes();
+
+ hub_active_ = true;
+ LOG_INFO(TAG, QString("Hub subscribed: %1 / %2").arg(bid, aid));
}
-void EquityTradingScreen::on_stream_holdings_updated(const QString& account_id,
- const QVector<BrokerHolding>& holdings) {
- if (account_id == focused_account_id_)
- bottom_panel_->set_holdings(holdings);
+void EquityTradingScreen::hub_subscribe_quotes() {
+ auto& hub = datahub::DataHub::instance();
+ const QString bid = broker_id_for_focused();
+ if (bid.isEmpty() || focused_account_id_.isEmpty())
+ return;
+
+ const QString aid = focused_account_id_;
+
+ // Build deduplicated symbol set: selected symbol + watchlist
+ QSet<QString> symbols;
+ symbols.insert(selected_symbol_);
+ for (const auto& s : watchlist_symbols_)
+ symbols.insert(s);
+
+ for (const auto& sym : symbols) {
+ const QString topic = broker_topic(bid, aid, QStringLiteral("quote"), sym);
+ hub.subscribe(this, topic, [this, sym](const QVariant& v) {
+ if (!v.canConvert<BrokerQuote>())
+ return;
+ const auto quote = v.value<BrokerQuote>();
+
+ // Cache for watchlist rebuild
+ watchlist_quote_cache_[sym] = quote;
+
+ // Ticker bar + order entry for selected symbol
+ if (sym == selected_symbol_) {
+ current_price_ = quote.ltp;
+ ticker_bar_->update_quote(quote.ltp, quote.change, quote.change_pct,
+ quote.high, quote.low, quote.volume,
+ quote.bid, quote.ask);
+ order_entry_->set_current_price(quote.ltp);
+ }
+
+ // Rebuild watchlist from cache
+ QVector<BrokerQuote> wl_quotes;
+ wl_quotes.reserve(watchlist_quote_cache_.size());
+ for (auto it = watchlist_quote_cache_.cbegin(); it != watchlist_quote_cache_.cend(); ++it)
+ wl_quotes.append(it.value());
+ watchlist_->update_quotes(wl_quotes);
+
+ // Feed paper trading engine
+ auto account = AccountManager::instance().get_account(focused_account_id_);
+ if (account.trading_mode == "paper" && !account.paper_portfolio_id.isEmpty() && quote.ltp > 0) {
+ pt_update_position_price(account.paper_portfolio_id, sym, quote.ltp);
+ PriceData pd;
+ pd.last = quote.ltp;
+ pd.bid = quote.bid;
+ pd.ask = quote.ask;
+ pd.timestamp = quote.timestamp;
+ OrderMatcher::instance().check_orders(sym, pd, account.paper_portfolio_id);
+ OrderMatcher::instance().check_sl_tp_triggers(account.paper_portfolio_id, sym, quote.ltp);
+ }
+ });
+ }
}
-void EquityTradingScreen::on_stream_orders_updated(const QString& account_id,
- const QVector<BrokerOrderInfo>& orders) {
- if (account_id == focused_account_id_)
- bottom_panel_->set_orders(orders);
+void EquityTradingScreen::hub_unsubscribe_all() {
+ if (!hub_active_)
+ return;
+ datahub::DataHub::instance().unsubscribe(this);
+ hub_active_ = false;
+ LOG_INFO(TAG, "Hub unsubscribed");
}
-void EquityTradingScreen::on_stream_funds_updated(const QString& account_id, const BrokerFunds& funds) {
- if (account_id == focused_account_id_) {
- bottom_panel_->set_funds(funds);
- order_entry_->set_balance(funds.available_balance);
- }
-}
+// ============================================================================
+// On-demand legacy signal slots (no hub topic — D4 exception)
+// ============================================================================
void EquityTradingScreen::on_stream_candles_fetched(const QString& account_id,
const QVector<BrokerCandle>& candles) {
@@ -177,8 +203,4 @@ void EquityTradingScreen::on_stream_clock_fetched(const QString& account_id, con
bottom_panel_->set_clock(clock);
}
-// ============================================================================
-// Slot Handlers
-// ============================================================================
-
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
index 2ac79ec39..bf5bbc1e7 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
@@ -4,10 +4,12 @@
#include "screens/portfolio/PortfolioSparkline.h"
#include "services/markets/MarketDataService.h"
#include "storage/repositories/SettingsRepository.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerTopic.h"
#include "ui/theme/Theme.h"
-# include "datahub/DataHub.h"
-# include "datahub/DataHubMetaTypes.h"
+#include "datahub/DataHub.h"
+#include "datahub/DataHubMetaTypes.h"
#include <QAction>
#include <QEvent>
@@ -327,6 +329,67 @@ void PortfolioBlotter::hub_unsubscribe_all() {
hub_active_ = false;
}
+void PortfolioBlotter::hub_resubscribe_broker_quotes(const QString& broker_account_id) {
+ if (broker_account_id.isEmpty() || holdings_.isEmpty())
+ return;
+ auto account = trading::AccountManager::instance().get_account(broker_account_id);
+ if (account.broker_id.isEmpty() || account.state != trading::ConnectionState::Connected)
+ return;
+
+ auto& hub = datahub::DataHub::instance();
+ const QString bid = account.broker_id;
+ const QString aid = broker_account_id;
+
+ for (const auto& h : holdings_) {
+ // Indian stocks in yfinance format end with .NS or .BO
+ QString broker_sym;
+ if (h.symbol.endsWith(QStringLiteral(".NS")) || h.symbol.endsWith(QStringLiteral(".BO")))
+ broker_sym = h.symbol.left(h.symbol.length() - 3);
+ else
+ continue; // not an Indian stock — skip broker subscription
+
+ const QString topic = trading::broker_topic(bid, aid, QStringLiteral("quote"), broker_sym);
+ const QString yf_sym = h.symbol;
+ hub.subscribe(this, topic, [this, yf_sym](const QVariant& v) {
+ if (!v.canConvert<trading::BrokerQuote>())
+ return;
+ const auto quote = v.value<trading::BrokerQuote>();
+ update_row_price(yf_sym, quote.ltp, quote.change_pct);
+ });
+ }
+}
+
+void PortfolioBlotter::update_row_price(const QString& symbol, double ltp, double change_pct) {
+ for (int r = 0; r < table_->rowCount(); ++r) {
+ auto* item = table_->item(r, 0);
+ if (!item || item->data(Qt::UserRole).toString() != symbol)
+ continue;
+ // Column layout: SYMBOL(0), QTY(1), AVG(2), LAST(3), MKT VAL(4), COST(5), P&L(6), P&L%(7), CHG%(8), SPARKLINE(9), WT%(10)
+ if (auto* last_item = table_->item(r, 3))
+ last_item->setText(format_value(ltp));
+ // Recalculate market value & P&L from holdings data
+ const int idx = r + (current_page_ - 1) * page_size_;
+ auto view = visible_view();
+ if (idx >= 0 && idx < view.size()) {
+ auto& h = view[idx];
+ double mkt_val = ltp * h.quantity;
+ double pnl = mkt_val - h.cost_basis;
+ double pnl_pct = h.cost_basis > 0 ? (pnl / h.cost_basis) * 100.0 : 0.0;
+ if (auto* mv = table_->item(r, 4))
+ mv->setText(format_value(mkt_val));
+ if (auto* pnl_item = table_->item(r, 6))
+ pnl_item->setText(format_value(pnl));
+ if (auto* pnl_pct_item = table_->item(r, 7))
+ pnl_pct_item->setText(QString("%1%").arg(pnl_pct, 0, 'f', 2));
+ }
+ if (auto* chg = table_->item(r, 8)) {
+ chg->setText(QString("%1%").arg(change_pct, 0, 'f', 2));
+ chg->setForeground(QColor(change_pct >= 0 ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ }
+ break;
+ }
+}
+
void PortfolioBlotter::set_selected_symbol(const QString& symbol) {
selected_symbol_ = symbol;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
index e35c74c58..aad86d3e9 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
@@ -1,6 +1,7 @@
// src/screens/portfolio/PortfolioBlotter.h
#pragma once
#include "screens/portfolio/PortfolioTypes.h"
+#include "trading/TradingTypes.h"
#include <QComboBox>
#include <QHash>
@@ -26,6 +27,7 @@ class PortfolioBlotter : public QWidget {
/// Show only rows whose symbol is in @p symbols. Empty list = show all.
void set_sector_filter(const QStringList& symbols);
void refresh_theme();
+ void hub_resubscribe_broker_quotes(const QString& broker_account_id);
protected:
void changeEvent(QEvent* event) override;
@@ -78,6 +80,7 @@ class PortfolioBlotter : public QWidget {
void hub_resubscribe_sparklines();
void hub_unsubscribe_all();
void repaint_sparkline_cells();
+ void update_row_price(const QString& symbol, double ltp, double change_pct);
bool hub_active_ = false;
QVector<portfolio::HoldingWithQuote> holdings_;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
index c92befa84..20caffd43 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioScreen.cpp
@@ -137,6 +137,8 @@ void PortfolioScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
refresh_timer_->start();
status_bar_->start_clock();
+ if (blotter_ && !current_summary_.portfolio.broker_account_id.isEmpty())
+ blotter_->hub_resubscribe_broker_quotes(current_summary_.portfolio.broker_account_id);
}
void PortfolioScreen::hideEvent(QHideEvent* event) {
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp b/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
index aa5e13ee8..c9318f6f3 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
@@ -5,6 +5,8 @@
#include "core/logging/Logger.h"
#include "python/PythonRunner.h"
#include "storage/cache/CacheManager.h"
+#include "storage/sqlite/Database.h"
+#include "trading/UnifiedTrading.h"
#include <QFile>
#include <QJsonDocument>
@@ -43,7 +45,20 @@ void AlgoTradingService::run_python(const QString& script, const QStringList& ar
// ── Strategy CRUD ─────────────────────────────────────────────────────────────
void AlgoTradingService::save_strategy(const AlgoStrategy& strategy) {
QJsonObject obj;
- obj["id"] = strategy.id.isEmpty() ? QUuid::createUuid().toString(QUuid::WithoutBraces) : strategy.id;
+
+ // Upsert by name: if a strategy with the same name exists, reuse its ID
+ QString resolved_id = strategy.id;
+ if (resolved_id.isEmpty() && !strategy.name.isEmpty()) {
+ auto q = fincept::Database::instance().execute(
+ "SELECT id FROM algo_strategies WHERE name = ? AND is_active = 1 LIMIT 1",
+ {strategy.name});
+ if (q.is_ok() && q.value().next())
+ resolved_id = q.value().value(0).toString();
+ }
+ if (resolved_id.isEmpty())
+ resolved_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+
+ obj["id"] = resolved_id;
obj["name"] = strategy.name;
obj["description"] = strategy.description;
obj["timeframe"] = strategy.timeframe;
@@ -92,33 +107,59 @@ static QVector<AlgoStrategy> parse_strategies(const QJsonArray& arr) {
return strategies;
}
+static QVector<AlgoStrategy> load_dsl_strategies_from_db() {
+ QVector<AlgoStrategy> result;
+ auto q = fincept::Database::instance().execute(
+ "SELECT id, name, description, timeframe, entry_conditions, exit_conditions, "
+ "entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, "
+ "created_at, updated_at "
+ "FROM algo_strategies WHERE is_active = 1 ORDER BY created_at DESC", {});
+ if (q.is_err())
+ return result;
+ auto& query = q.value();
+ while (query.next()) {
+ AlgoStrategy s;
+ s.id = query.value(0).toString();
+ s.name = query.value(1).toString();
+ s.description = query.value(2).toString();
+ s.timeframe = query.value(3).toString();
+ s.entry_conditions = QJsonDocument::fromJson(query.value(4).toString().toUtf8()).array();
+ s.exit_conditions = QJsonDocument::fromJson(query.value(5).toString().toUtf8()).array();
+ s.entry_logic = query.value(6).isNull() ? QStringLiteral("AND") : query.value(6).toString();
+ s.exit_logic = query.value(7).isNull() ? QStringLiteral("AND") : query.value(7).toString();
+ s.stop_loss = query.value(8).toDouble();
+ s.take_profit = query.value(9).toDouble();
+ s.trailing_stop = query.value(10).toDouble();
+ s.created_at = query.value(11).toString();
+ s.updated_at = query.value(12).toString();
+ result.append(s);
+ }
+ return result;
+}
+
void AlgoTradingService::list_strategies() {
- // Fast path: read pre-generated registry_index.json directly — no Python spawn needed
+ QVector<AlgoStrategy> all;
+
+ // 1. Load QC strategies from pre-generated registry_index.json
const QString json_path =
python::PythonRunner::instance().scripts_dir() + "/strategies/registry_index.json";
QFile f(json_path);
if (f.open(QIODevice::ReadOnly)) {
auto doc = QJsonDocument::fromJson(f.readAll());
f.close();
- if (!doc.isNull()) {
- LOG_INFO("AlgoTrading", QString("Loaded registry from %1").arg(json_path));
- emit strategies_loaded(parse_strategies(doc.object()["strategies"].toArray()));
- return;
- }
+ if (!doc.isNull())
+ all = parse_strategies(doc.object()["strategies"].toArray());
}
- // Fallback: run Python to regenerate the index
- LOG_WARN("AlgoTrading", "registry_index.json missing — falling back to Python");
- run_python("algo_trading/backtest_engine.py", {"list_registry"}, "list_strategies",
- [this](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("list_strategies", out);
- return;
- }
- auto doc = QJsonDocument::fromJson(python::extract_json(out).toUtf8());
- auto obj = doc.object();
- emit strategies_loaded(parse_strategies(obj["strategies"].toArray()));
- });
+ // 2. Load user-saved DSL strategies from the database
+ auto dsl = load_dsl_strategies_from_db();
+ if (!dsl.isEmpty()) {
+ all.append(dsl);
+ LOG_INFO("AlgoTrading", QString("Loaded %1 DSL strategies from DB").arg(dsl.size()));
+ }
+
+ LOG_INFO("AlgoTrading", QString("Total strategies: %1 (QC + DSL)").arg(all.size()));
+ emit strategies_loaded(all);
}
void AlgoTradingService::delete_strategy(const QString& id) {
@@ -133,110 +174,10 @@ void AlgoTradingService::delete_strategy(const QString& id) {
});
}
-// ── Deployment lifecycle ──────────────────────────────────────────────────────
-void AlgoTradingService::deploy_strategy(const QString& strategy_id, const QString& symbol, const QString& mode,
- const QString& timeframe, double quantity) {
- auto deploy_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
- // algo_live_runner is a long-running process — start and don't wait for completion
- run_python("algo_trading/algo_live_runner.py",
- {"--deploy-id", deploy_id, "--strategy-id", strategy_id, "--symbol", symbol, "--mode", mode,
- "--timeframe", timeframe, "--quantity", QString::number(quantity), "--db", algo_db_path()},
- "deploy", [this, deploy_id](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("deploy", out);
- return;
- }
- emit deployment_started(deploy_id);
- });
-}
-
-void AlgoTradingService::stop_deployment(const QString& deployment_id) {
- run_python("algo_trading/algo_manager.py", {"stop", deployment_id, "--db", algo_db_path()}, "stop_deployment",
- [this, deployment_id](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("stop_deployment", out);
- return;
- }
- emit deployment_stopped(deployment_id);
- });
-}
-
-void AlgoTradingService::stop_all_deployments() {
- run_python("algo_trading/algo_manager.py", {"stop_all", "--db", algo_db_path()}, "stop_all",
- [this](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("stop_all", out);
- return;
- }
- LOG_INFO("AlgoTrading", "All deployments stopped");
- });
-}
-
-static QVector<AlgoDeployment> parse_deployments(const QJsonArray& arr) {
- QVector<AlgoDeployment> deployments;
- deployments.reserve(arr.size());
- for (const auto& v : arr) {
- auto o = v.toObject();
- AlgoDeployment d;
- d.id = o["id"].toString();
- d.strategy_id = o["strategy_id"].toString();
- d.strategy_name = o["strategy_name"].toString();
- d.strategy_kind = o["strategy_kind"].toString("dsl");
- d.symbol = o["symbol"].toString();
- d.exchange = o["exchange"].toString();
- d.product_type = o["product_type"].toString();
- d.mode = o["mode"].toString();
- d.backend = o["backend"].toString("paper");
- d.broker_id = o["broker_id"].toString();
- d.broker_account_id = o["broker_account_id"].toString();
- d.paper_portfolio_id = o["paper_portfolio_id"].toString();
- d.status = o["status"].toString();
- d.timeframe = o["timeframe"].toString();
- d.quantity = o["quantity"].toDouble();
- d.max_order_value = o["max_order_value"].toDouble();
- d.max_daily_loss = o["max_daily_loss"].toDouble();
- d.error_message = o["error_message"].toString();
- d.pid = static_cast<qint64>(o["pid"].toDouble());
- d.total_pnl = o["total_pnl"].toDouble();
- d.unrealized_pnl = o["unrealized_pnl"].toDouble();
- d.total_trades = o["total_trades"].toInt();
- d.win_rate = o["win_rate"].toDouble();
- d.max_drawdown = o["max_drawdown"].toDouble();
- d.position_qty = o["current_position_qty"].toDouble();
- d.position_side = o["current_position_side"].toString();
- d.position_entry = o["current_position_entry"].toDouble();
- d.created_at = o["created_at"].toString();
- d.updated_at = o["updated_at"].toString();
- deployments.append(d);
- }
- return deployments;
-}
-
-void AlgoTradingService::list_deployments() {
- const QVariant cached = fincept::CacheManager::instance().get(kDeploymentsCacheKey);
- if (!cached.isNull()) {
- auto doc = QJsonDocument::fromJson(cached.toString().toUtf8());
- if (!doc.isNull()) {
- emit deployments_loaded(parse_deployments(doc.object()["deployments"].toArray()));
- return;
- }
- }
-
- run_python("algo_trading/algo_manager.py", {"list_deployments", "--db", algo_db_path()}, "list_deployments",
- [this](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("list_deployments", out);
- return;
- }
- auto doc = QJsonDocument::fromJson(python::extract_json(out).toUtf8());
- auto obj = doc.object();
- fincept::CacheManager::instance().put(
- kDeploymentsCacheKey,
- QVariant(QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact))),
- kDeploymentsTtlSec, "algo_trading");
- emit deployments_loaded(parse_deployments(obj["deployments"].toArray()));
- });
-}
+// ── Deployment lifecycle — now handled by AlgoEngine (src/algo_engine/) ──────
+// deploy_strategy, stop_deployment, stop_all_deployments, remove_deployment,
+// list_deployments, check_bridge_needed have been removed.
+// Use fincept::algo::AlgoEngine::instance() for all deployment operations.
// ── Backtesting ───────────────────────────────────────────────────────────────
void AlgoTradingService::run_backtest(const QString& strategy_id, const QString& symbol, const QString& start_date,
@@ -260,26 +201,6 @@ void AlgoTradingService::run_backtest(const QString& strategy_id, const QString&
});
}
-// ── Scanner ───────────────────────────────────────────────────────────────────
-void AlgoTradingService::run_scan(const QJsonArray& conditions, const QStringList& symbols, const QString& timeframe,
- int lookback_days, const QString& logic) {
- QJsonObject params;
- params["conditions"] = conditions;
- params["symbols"] = QJsonArray::fromStringList(symbols);
- params["timeframe"] = timeframe;
- params["lookback_days"] = lookback_days;
- params["logic"] = logic;
- auto json = QJsonDocument(params).toJson(QJsonDocument::Compact);
-
- run_python("algo_trading/scanner_engine.py", {"scan", json, "--db", algo_db_path()}, "scan",
- [this](bool ok, const QString& out) {
- if (!ok) {
- emit error_occurred("scan", out);
- return;
- }
- auto doc = QJsonDocument::fromJson(python::extract_json(out).toUtf8());
- emit scan_result(doc.object());
- });
-}
+// Scanner is now in AlgoScanner (src/algo_engine/AlgoScanner.h/.cpp).
} // namespace fincept::services::algo
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingService.h b/fincept-qt/src/services/algo_trading/AlgoTradingService.h
index 071b36ded..cb413915b 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingService.h
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingService.h
@@ -17,30 +17,21 @@ class AlgoTradingService : public QObject {
void list_strategies();
void delete_strategy(const QString& id);
- // ── Deployment lifecycle ────────────────────────────────────────────────
- void deploy_strategy(const QString& strategy_id, const QString& symbol, const QString& mode,
- const QString& timeframe, double quantity);
- void stop_deployment(const QString& deployment_id);
- void stop_all_deployments();
- void list_deployments();
+ // Deployment lifecycle is now in AlgoEngine (src/algo_engine/AlgoEngine.h).
// ── Backtesting ─────────────────────────────────────────────────────────
void run_backtest(const QString& strategy_id, const QString& symbol, const QString& start_date,
const QString& end_date, double capital);
- // ── Scanner ─────────────────────────────────────────────────────────────
- void run_scan(const QJsonArray& conditions, const QStringList& symbols, const QString& timeframe, int lookback_days,
- const QString& logic = "AND");
+ // Scanner is now in AlgoScanner (src/algo_engine/AlgoScanner.h).
signals:
void strategy_saved(QString id);
void strategies_loaded(QVector<fincept::services::algo::AlgoStrategy> strategies);
void strategy_deleted(QString id);
void deployment_started(QString deployment_id);
- void deployments_loaded(QVector<fincept::services::algo::AlgoDeployment> deployments);
void deployment_stopped(QString deployment_id);
void backtest_result(QJsonObject data);
- void scan_result(QJsonObject data);
void error_occurred(QString context, QString message);
private:
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
index 89901fd7a..1a866a6e8 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
@@ -87,6 +87,7 @@ struct AlgoDeployment {
QString exchange; // e.g. "NSE", "NASDAQ" — from broker profile
QString product_type; // e.g. "MIS", "CNC" — broker-specific
QString mode; // paper | live
+ QString entry_side = "BUY"; // BUY | SELL — direction of the entry signal
QString backend = "paper"; // paper | equity_broker | crypto_exchange
QString broker_id; // BrokerRegistry id; empty for paper
QString broker_account_id; // AccountManager id; empty for paper or single-account brokers
@@ -110,6 +111,7 @@ struct AlgoDeployment {
double position_qty = 0;
QString position_side;
double position_entry = 0;
+ double current_price = 0;
StrategyKind kind() const { return kind_from_id(strategy_id); }
TradingBackend backend_enum() const { return backend_from_string(backend); }
diff --git a/fincept-qt/src/services/equity/EquityResearchService.cpp b/fincept-qt/src/services/equity/EquityResearchService.cpp
index b7253d261..1559c1c84 100644
--- a/fincept-qt/src/services/equity/EquityResearchService.cpp
+++ b/fincept-qt/src/services/equity/EquityResearchService.cpp
@@ -128,22 +128,28 @@ void EquityResearchService::load_info_only(const QString& symbol) {
void EquityResearchService::load_historical_only(const QString& symbol, const QString& period) {
if (symbol.isEmpty())
return;
- const QVariant hcv = fincept::CacheManager::instance().get("equity:candles:" + symbol);
+ const QString cache_key = "equity:candles:" + symbol + ":" + period;
+ const QVariant hcv = fincept::CacheManager::instance().get(cache_key);
if (!hcv.isNull()) {
- emit historical_loaded(symbol, parse_candles(QJsonDocument::fromJson(hcv.toString().toUtf8()).array()));
- return;
+ auto arr = QJsonDocument::fromJson(hcv.toString().toUtf8()).array();
+ if (!arr.isEmpty()) {
+ emit historical_loaded(symbol, parse_candles(arr));
+ return;
+ }
}
run_python("yfinance_data.py", {"historical_period", symbol, period, "1d"},
- [this, symbol](bool ok, const QString& out) {
+ [this, symbol, cache_key](bool ok, const QString& out) {
if (!ok) {
emit error_occurred("Historical", "Failed to fetch historical for " + symbol);
return;
}
auto arr = QJsonDocument::fromJson(python::extract_json(out).toUtf8()).array();
- fincept::CacheManager::instance().put(
- "equity:candles:" + symbol,
- QVariant(QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact))),
- kHistoricalTtlSec, "equity");
+ if (!arr.isEmpty()) {
+ fincept::CacheManager::instance().put(
+ cache_key,
+ QVariant(QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact))),
+ kHistoricalTtlSec, "equity");
+ }
emit historical_loaded(symbol, parse_candles(arr));
});
}
diff --git a/fincept-qt/src/services/llm/LlmFinceptAsync.cpp b/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
index 9e2b3dcd0..859b5e492 100644
--- a/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
+++ b/fincept-qt/src/services/llm/LlmFinceptAsync.cpp
@@ -35,7 +35,7 @@ namespace { constexpr const char* kLlmFinceptTag = "LlmService"; }
//
// Two modes:
// • Tool RAG ON + default filter: emit only the Tier-0 tools + explicit
-// instructions to use tool.list for everything else. Same disclosure
+// instructions to use tool_list for everything else. Same disclosure
// model as structured providers — keeps the catalog small and forces
// deliberate discovery.
// • Tool RAG OFF or explicit filter: legacy behaviour — list up to 60
@@ -63,7 +63,7 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {
// Mirror McpService::tier_0_tool_names() (kept in sync manually — small
// list, low churn).
static const QSet<QString> kTier0 = {
- "tool.list", "tool.describe", "navigate_to_tab", "list_tabs",
+ "tool_list", "tool_describe", "navigate_to_tab", "list_tabs",
"get_current_tab", "get_auth_status",
};
catalog += "Always-available tools:\n";
@@ -73,8 +73,8 @@ static QString build_tool_catalog_for_prompt(const mcp::ToolFilter& filter) {
QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
catalog += "- " + fn_name + ": " + tool.description + "\n";
}
- const QString wire_list = mcp::McpProvider::encode_tool_name_for_wire("tool.list");
- const QString wire_describe = mcp::McpProvider::encode_tool_name_for_wire("tool.describe");
+ const QString wire_list = QStringLiteral("tool_list");
+ const QString wire_describe = QStringLiteral("tool_describe");
catalog += QStringLiteral(
"\nFor any other capability, call fincept-terminal__%1 with a natural-language "
"query (e.g. {\"query\": \"draft a research report\"}). It returns the top 5 most "
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index 8f85cc42e..13b2687dc 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -194,7 +194,7 @@ void LlmService::ensure_config() const {
"Be concise, accurate, and finance-focused.";
}
- // Tool RAG discovery hint: lists categories dynamically so the model can form good tool.list() queries.
+ // Tool RAG discovery hint: lists categories dynamically so the model can form good tool_list() queries.
// The `[Tool discovery]` sentinel makes append idempotent across reloads. Cached static for prompt-cache stability.
if (tools_enabled_ && !system_prompt_.contains("[Tool discovery]")) {
// Tool registry is immutable after McpInit; runtime additions won't appear until restart (acceptable here).
@@ -211,11 +211,11 @@ void LlmService::ensure_config() const {
QString hint =
"\n\n[Tool discovery] You see only a small subset of tools each turn. "
"To find a tool for any action you don't already have, call "
- "tool.list(query=\"<natural-language description>\"). "
+ "tool_list(query=\"<natural-language description>\"). "
"It returns the top 5 most relevant tools (BM25-ranked). "
- "Then call tool.describe(name) for the full input schema, then invoke it. "
+ "Then call tool_describe(name) for the full input schema, then invoke it. "
"For requests with multiple intents (\"get news AND add to watchlist\"), "
- "call tool.list MULTIPLE TIMES — once per intent. "
+ "call tool_list MULTIPLE TIMES — once per intent. "
"Never decline an action you can fulfil via a discoverable tool.";
if (!sorted_cats.isEmpty()) {
hint += "\nAvailable tool categories: " + sorted_cats.join(", ") + ".";
diff --git a/fincept-qt/src/services/llm/LlmToolLoop.cpp b/fincept-qt/src/services/llm/LlmToolLoop.cpp
index 12ace97e6..4f676e5d1 100644
--- a/fincept-qt/src/services/llm/LlmToolLoop.cpp
+++ b/fincept-qt/src/services/llm/LlmToolLoop.cpp
@@ -12,6 +12,7 @@
#include "services/llm/LlmContentExtractors.h"
#include "services/llm/LlmRequestPolicy.h"
#include "core/logging/Logger.h"
+#include "mcp/McpProvider.h"
#include "mcp/McpService.h"
#include <QJsonArray>
@@ -29,7 +30,7 @@ namespace { constexpr const char* kLlmToolLoopTag = "LlmService"; }
LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& url,
const QMap<QString, QString>& headers) {
LlmResponse resp;
- // MiniMax-style models spend 3 rounds per action (tool.list → tool.describe
+ // MiniMax-style models spend 3 rounds per action (tool_list → tool_describe
// → actual call), so the default 40 gives ~13 real actions — enough for a
// full report template fill. Below ~12 silently cripples report-builder flows.
const int MAX_ROUNDS = active_max_tool_rounds();
@@ -80,7 +81,7 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP r%1: executing %2 args=%3").arg(round).arg(fname,
QString::fromUtf8(QJsonDocument(fa).toJson(QJsonDocument::Compact)).left(200)));
- // Strip "<server>__" prefix for user-visible label; restore "tool.list" from wire form.
+ // Strip "<server>__" prefix for user-visible label; decode any wire encoding.
QString display = fname;
int sep = display.indexOf(QStringLiteral("__"));
if (sep > 0)
@@ -335,7 +336,7 @@ std::optional<LlmResponse> LlmService::try_extract_and_execute_text_tool_calls(c
for (auto pit = props.constBegin(); pit != props.constEnd(); ++pit) {
QString key = pit.key().toLower();
if (key == "query" || key == "sql" || key == "statement") {
- QString fn_name = tool.server_id + "__" + tool.name;
+ QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
QJsonObject args;
args[pit.key()] = body;
calls.push_back({fn_name, args});
diff --git a/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp b/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp
index acdb6c0a2..dbad09faa 100644
--- a/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp
+++ b/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp
@@ -125,6 +125,7 @@ Result<void> apply_v023(QSqlDatabase& db) {
{"algo_deployments", "paper_portfolio_id", "TEXT DEFAULT ''"},
{"algo_deployments", "max_order_value", "REAL DEFAULT 0"},
{"algo_deployments", "max_daily_loss", "REAL DEFAULT 0"},
+ {"algo_deployments", "entry_side", "TEXT DEFAULT 'BUY'"},
{"algo_deployments", "pid", "INTEGER DEFAULT 0"},
};
for (const auto& c : deployment_cols) {
@@ -208,6 +209,18 @@ Result<void> apply_v023(QSqlDatabase& db) {
return r;
}
+ // Add current_price and entry_side to algo_metrics for live dashboard display.
+ {
+ auto r = v023_add_column_if_missing(db, "algo_metrics", "current_price", "REAL DEFAULT 0");
+ if (r.is_err())
+ return r;
+ }
+ {
+ auto r = v023_add_column_if_missing(db, "algo_metrics", "entry_side", "TEXT DEFAULT 'BUY'");
+ if (r.is_err())
+ return r;
+ }
+
// ── Trade audit log (paper + live) ──────────────────────────────────────
{
auto r = v023_sql(db, R"sql(
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index f845c6743..f8595d448 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -5,6 +5,7 @@
#include "trading/BrokerRegistry.h"
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
+#include "trading/brokers/alpaca/AlpacaWebSocket.h"
#include "trading/websocket/FyersWebSocket.h"
#include <QDate>
@@ -138,13 +139,30 @@ BrokerQuote AccountDataStream::cached_quote(const QString& symbol) const {
// ── Timer callbacks ─────────────────────────────────────────────────────────
+// ── Token expiry check ─────────────────────────────────────────────────────
+
+bool AccountDataStream::is_token_expired() const {
+ auto creds = AccountManager::instance().load_credentials(account_id_);
+ if (creds.additional_data.isEmpty())
+ return false;
+ auto doc = QJsonDocument::fromJson(creds.additional_data.toUtf8());
+ qint64 expires_at = static_cast<qint64>(doc.object().value("token_expires_at").toDouble(0));
+ return expires_at > 0 && expires_at <= QDateTime::currentSecsSinceEpoch();
+}
+
void AccountDataStream::on_quote_timer() {
- // Always poll — WS supplements with faster ticks but polling ensures
- // data is available for newly-selected symbols and after market close.
+ if (is_token_expired()) {
+ emit token_expired(account_id_);
+ return;
+ }
async_fetch_quote();
}
void AccountDataStream::on_portfolio_timer() {
+ if (is_token_expired()) {
+ emit token_expired(account_id_);
+ return;
+ }
if (portfolio_fetching_.exchange(true))
return;
async_fetch_positions();
@@ -155,8 +173,10 @@ void AccountDataStream::on_portfolio_timer() {
}
void AccountDataStream::on_watchlist_timer() {
- // Always run watchlist polling — the watchlist UI needs the batch
- // watchlist_updated signal which WS tick_received doesn't provide.
+ if (is_token_expired()) {
+ emit token_expired(account_id_);
+ return;
+ }
async_fetch_watchlist_quotes();
}
@@ -609,6 +629,7 @@ void AccountDataStream::ws_init() {
connect(fws, &FyersWebSocket::connected, this, [this]() {
LOG_INFO(ADS_TAG, QString("Fyers HSM connected for %1").arg(account_id_));
+ emit connection_state_changed(account_id_, ConnectionState::Connected);
auto to_fyers = [](const QString& sym) {
return sym.contains(':') ? sym : QStringLiteral("NSE:") + sym + QStringLiteral("-EQ");
};
@@ -624,6 +645,7 @@ void AccountDataStream::ws_init() {
connect(fws, &FyersWebSocket::disconnected, this, [this]() {
LOG_WARN(ADS_TAG, QString("Fyers HSM disconnected for %1").arg(account_id_));
+ emit connection_state_changed(account_id_, ConnectionState::Disconnected);
});
connect(fws, &FyersWebSocket::error_occurred, this, [this](const QString& err) {
@@ -634,6 +656,76 @@ void AccountDataStream::ws_init() {
return;
}
+ if (broker_id_ == "alpaca") {
+ auto creds = AccountManager::instance().load_credentials(account_id_);
+ if (creds.api_key.isEmpty() || creds.api_secret.isEmpty())
+ return;
+
+ auto* aws = new AlpacaWebSocket(creds.api_key, creds.api_secret, this);
+ ws_ = aws;
+
+ connect(aws, &AlpacaWebSocket::tick_received, this, [this](const BrokerQuote& q) {
+ ++ws_tick_count_;
+ quote_cache_[q.symbol] = q;
+ emit quote_updated(account_id_, q.symbol, q);
+ });
+
+ connect(aws, &AlpacaWebSocket::trade_received, this, [this](const BrokerTrade& trade) {
+ auto it = quote_cache_.find(trade.symbol);
+ if (it != quote_cache_.end()) {
+ it->ltp = trade.price;
+ const auto dt = QDateTime::fromString(trade.timestamp, Qt::ISODateWithMs);
+ it->timestamp = dt.isValid() ? dt.toMSecsSinceEpoch() : 0;
+ emit quote_updated(account_id_, trade.symbol, it.value());
+ }
+ });
+
+ connect(aws, &AlpacaWebSocket::bar_received, this,
+ [this](const QString& symbol, const BrokerCandle& bar) {
+ auto it = quote_cache_.find(symbol);
+ if (it != quote_cache_.end()) {
+ it->open = bar.open;
+ it->high = bar.high;
+ it->low = bar.low;
+ it->close = bar.close;
+ it->volume = bar.volume;
+ it->change = bar.close - bar.open;
+ it->change_pct = bar.open > 0 ? ((bar.close - bar.open) / bar.open) * 100.0 : 0;
+ emit quote_updated(account_id_, symbol, it.value());
+ }
+ });
+
+ connect(aws, &AlpacaWebSocket::connected, this, [this]() {
+ LOG_INFO(ADS_TAG, QString("Alpaca WS connected for %1").arg(account_id_));
+ emit connection_state_changed(account_id_, ConnectionState::Connected);
+ QStringList symbols;
+ if (!selected_symbol_.isEmpty())
+ symbols.append(selected_symbol_);
+ for (const auto& s : watchlist_symbols_) {
+ if (!symbols.contains(s))
+ symbols.append(s);
+ }
+ if (auto* a = qobject_cast<AlpacaWebSocket*>(ws_))
+ a->subscribe(symbols);
+ });
+
+ connect(aws, &AlpacaWebSocket::disconnected, this, [this]() {
+ LOG_WARN(ADS_TAG, QString("Alpaca WS disconnected for %1").arg(account_id_));
+ emit connection_state_changed(account_id_, ConnectionState::Disconnected);
+ });
+
+ connect(aws, &AlpacaWebSocket::error_occurred, this, [this](const QString& err) {
+ LOG_ERROR(ADS_TAG, QString("Alpaca WS error: %1").arg(err));
+ });
+
+ connect(aws, &AlpacaWebSocket::market_closed, this, [this]() {
+ LOG_INFO(ADS_TAG, QString("Alpaca market closed for %1 — falling back to polling").arg(account_id_));
+ });
+
+ aws->open();
+ return;
+ }
+
if (broker_id_ != "angelone")
return;
@@ -667,6 +759,8 @@ bool AccountDataStream::ws_active() const {
return false;
if (auto* fws = qobject_cast<FyersWebSocket*>(ws_))
return fws->is_connected() && ws_tick_count_ > 0;
+ if (auto* aws = qobject_cast<AlpacaWebSocket*>(ws_))
+ return aws->is_connected() && ws_tick_count_ > 0;
return false;
}
@@ -683,6 +777,17 @@ void AccountDataStream::ws_resubscribe() {
fyers_symbols.removeDuplicates();
fws->set_subscriptions(fyers_symbols);
}
+
+ if (auto* aws = qobject_cast<AlpacaWebSocket*>(ws_)) {
+ QStringList symbols;
+ if (!selected_symbol_.isEmpty())
+ symbols.append(selected_symbol_);
+ for (const auto& s : watchlist_symbols_) {
+ if (!symbols.contains(s))
+ symbols.append(s);
+ }
+ aws->set_subscriptions(symbols);
+ }
}
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/AccountDataStream.h b/fincept-qt/src/trading/AccountDataStream.h
index 54d917bb6..6ed04e31d 100644
--- a/fincept-qt/src/trading/AccountDataStream.h
+++ b/fincept-qt/src/trading/AccountDataStream.h
@@ -79,6 +79,9 @@ class AccountDataStream : public QObject {
void token_expired(const QString& account_id);
private:
+ // --- Token expiry check ---
+ bool is_token_expired() const;
+
// --- Async fetch methods (all follow P8: QPointer + QtConcurrent + QueuedConnection) ---
void async_fetch_quote();
void async_fetch_positions();
diff --git a/fincept-qt/src/trading/AccountManager.cpp b/fincept-qt/src/trading/AccountManager.cpp
index 9b103ba93..ea51acf5a 100644
--- a/fincept-qt/src/trading/AccountManager.cpp
+++ b/fincept-qt/src/trading/AccountManager.cpp
@@ -8,6 +8,8 @@
#include "trading/PaperTrading.h"
#include <QDateTime>
+#include <QJsonDocument>
+#include <QJsonObject>
#include <QMutexLocker>
#include <QUuid>
@@ -46,13 +48,28 @@ void AccountManager::load_from_db() {
LOG_INFO("AccountManager", QString("Loaded %1 broker accounts from DB").arg(accounts_.size()));
// Restore connection state from persisted credentials.
- // If an account has a saved access_token, mark it as Connected (optimistic).
- // The first API call will detect token expiry and update the state.
+ // Check token_expires_at in additional_data — mark TokenExpired if stale.
auto& secure = SecureStorage::instance();
for (auto it = accounts_.begin(); it != accounts_.end(); ++it) {
auto token_r = secure.retrieve(acct_key(it->account_id, "access_token"));
- if (token_r.is_ok() && !token_r.value().isEmpty())
- it->state = ConnectionState::Connected;
+ if (!token_r.is_ok() || token_r.value().isEmpty())
+ continue;
+ auto extra_r = secure.retrieve(acct_key(it->account_id, "additional_data"));
+ qint64 expires_at = 0;
+ if (extra_r.is_ok() && !extra_r.value().isEmpty()) {
+ auto doc = QJsonDocument::fromJson(extra_r.value().toUtf8());
+ expires_at = static_cast<qint64>(doc.object().value("token_expires_at").toDouble(0));
+ }
+ // Fyers tokens expire in 24h — if no expiry stored, assume expired
+ if (expires_at > 0 && expires_at <= QDateTime::currentSecsSinceEpoch()) {
+ it->state = ConnectionState::TokenExpired;
+ continue;
+ }
+ if (expires_at == 0 && it->broker_id == QStringLiteral("fyers")) {
+ it->state = ConnectionState::TokenExpired;
+ continue;
+ }
+ it->state = ConnectionState::Connected;
}
}
diff --git a/fincept-qt/src/trading/DataStreamManager.cpp b/fincept-qt/src/trading/DataStreamManager.cpp
index 4cd500280..fbd73176e 100644
--- a/fincept-qt/src/trading/DataStreamManager.cpp
+++ b/fincept-qt/src/trading/DataStreamManager.cpp
@@ -105,19 +105,7 @@ QStringList DataStreamManager::active_stream_ids() const {
// ── Signal wiring ───────────────────────────────────────────────────────────
void DataStreamManager::wire_stream_signals(AccountDataStream* stream) {
- // Forward all per-stream signals to aggregated manager signals
- connect(stream, &AccountDataStream::quote_updated,
- this, &DataStreamManager::quote_updated);
- connect(stream, &AccountDataStream::watchlist_updated,
- this, &DataStreamManager::watchlist_updated);
- connect(stream, &AccountDataStream::positions_updated,
- this, &DataStreamManager::positions_updated);
- connect(stream, &AccountDataStream::holdings_updated,
- this, &DataStreamManager::holdings_updated);
- connect(stream, &AccountDataStream::orders_updated,
- this, &DataStreamManager::orders_updated);
- connect(stream, &AccountDataStream::funds_updated,
- this, &DataStreamManager::funds_updated);
+ // On-demand / one-shot signals — relayed directly (no hub topic)
connect(stream, &AccountDataStream::candles_fetched,
this, &DataStreamManager::candles_fetched);
connect(stream, &AccountDataStream::orderbook_fetched,
@@ -132,6 +120,10 @@ void DataStreamManager::wire_stream_signals(AccountDataStream* stream) {
this, &DataStreamManager::clock_fetched);
connect(stream, &AccountDataStream::connection_state_changed,
this, &DataStreamManager::connection_state_changed);
+ connect(stream, &AccountDataStream::connection_state_changed,
+ this, [](const QString& account_id, ConnectionState state) {
+ AccountManager::instance().set_connection_state(account_id, state);
+ });
connect(stream, &AccountDataStream::token_expired,
this, &DataStreamManager::token_expired);
diff --git a/fincept-qt/src/trading/DataStreamManager.h b/fincept-qt/src/trading/DataStreamManager.h
index 7355839e5..70c45186d 100644
--- a/fincept-qt/src/trading/DataStreamManager.h
+++ b/fincept-qt/src/trading/DataStreamManager.h
@@ -46,13 +46,7 @@ class DataStreamManager : public QObject
int max_requests_per_sec() const override;
signals:
- // Aggregated signals — the UI connects to these instead of individual streams
- void quote_updated(const QString& account_id, const QString& symbol, const BrokerQuote& quote);
- void watchlist_updated(const QString& account_id, const QVector<BrokerQuote>& quotes);
- void positions_updated(const QString& account_id, const QVector<BrokerPosition>& positions);
- void holdings_updated(const QString& account_id, const QVector<BrokerHolding>& holdings);
- void orders_updated(const QString& account_id, const QVector<BrokerOrderInfo>& orders);
- void funds_updated(const QString& account_id, const BrokerFunds& funds);
+ // On-demand / one-shot signals — no hub topic exists for these
void candles_fetched(const QString& account_id, const QVector<BrokerCandle>& candles);
void orderbook_fetched(const QString& account_id,
const QVector<QPair<double, double>>& bids,
diff --git a/fincept-qt/src/trading/UnifiedTrading.cpp b/fincept-qt/src/trading/UnifiedTrading.cpp
index 212e198e6..7f276013a 100644
--- a/fincept-qt/src/trading/UnifiedTrading.cpp
+++ b/fincept-qt/src/trading/UnifiedTrading.cpp
@@ -6,8 +6,14 @@
#include "trading/AccountManager.h"
#include "trading/PaperTrading.h"
+#include "storage/sqlite/Database.h"
+
#include <QJsonObject>
#include <QMutexLocker>
+#include <QPointer>
+#include <QSqlQuery>
+#include <QTimer>
+#include <QtConcurrent/QtConcurrentRun>
namespace fincept::trading {
@@ -284,22 +290,4 @@ QVector<UnifiedTrading::BroadcastResult> UnifiedTrading::broadcast_order(const Q
return results;
}
-// ============================================================================
-// Order Bridge (simplified — no detached threads in Qt)
-// ============================================================================
-
-void UnifiedTrading::start_order_bridge() {
- bridge_running_.store(true);
- LOG_INFO("UnifiedTrading", "Order signal bridge started");
-}
-
-void UnifiedTrading::stop_order_bridge() {
- bridge_running_.store(false);
- LOG_INFO("UnifiedTrading", "Order signal bridge stopping");
-}
-
-bool UnifiedTrading::is_bridge_running() const {
- return bridge_running_.load();
-}
-
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/UnifiedTrading.h b/fincept-qt/src/trading/UnifiedTrading.h
index e2795ae9f..a3d37c668 100644
--- a/fincept-qt/src/trading/UnifiedTrading.h
+++ b/fincept-qt/src/trading/UnifiedTrading.h
@@ -6,6 +6,7 @@
#include <QMutex>
#include <QThread>
+#include <QTimer>
#include <atomic>
#include <optional>
@@ -42,11 +43,6 @@ class UnifiedTrading : public QObject {
};
QVector<BroadcastResult> broadcast_order(const QStringList& account_ids, const UnifiedOrder& order);
- // Order bridge for algo trading
- void start_order_bridge();
- void stop_order_bridge();
- bool is_bridge_running() const;
-
UnifiedTrading(const UnifiedTrading&) = delete;
UnifiedTrading& operator=(const UnifiedTrading&) = delete;
@@ -62,9 +58,6 @@ class UnifiedTrading : public QObject {
std::optional<TradingSession> session_;
mutable QMutex mutex_;
-
- // Order bridge
- std::atomic<bool> bridge_running_{false};
};
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/alpaca/AlpacaWebSocket.cpp b/fincept-qt/src/trading/brokers/alpaca/AlpacaWebSocket.cpp
new file mode 100644
index 000000000..725a74af7
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/alpaca/AlpacaWebSocket.cpp
@@ -0,0 +1,363 @@
+#include "trading/brokers/alpaca/AlpacaWebSocket.h"
+
+#include "core/logging/Logger.h"
+#include "network/websocket/WebSocketClient.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
+
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QPointer>
+#include <QtConcurrent>
+
+namespace fincept::trading {
+
+namespace {
+QString compact_json(const QJsonObject& obj) {
+ return QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact));
+}
+} // namespace
+
+// ── Construction ────────────────────────────────────────────────────────────
+
+AlpacaWebSocket::AlpacaWebSocket(const QString& api_key, const QString& api_secret,
+ QObject* parent)
+ : QObject(parent), api_key_(api_key), api_secret_(api_secret) {
+ ws_ = new fincept::WebSocketClient(this);
+ connect(ws_, &fincept::WebSocketClient::connected, this, &AlpacaWebSocket::on_ws_connected);
+ connect(ws_, &fincept::WebSocketClient::disconnected, this, &AlpacaWebSocket::on_ws_disconnected);
+ connect(ws_, &fincept::WebSocketClient::message_received, this, &AlpacaWebSocket::on_ws_message);
+ connect(ws_, &fincept::WebSocketClient::error_occurred, this, &AlpacaWebSocket::on_ws_error);
+
+ heartbeat_timer_ = new QTimer(this);
+ heartbeat_timer_->setSingleShot(true);
+ heartbeat_timer_->setInterval(HEARTBEAT_TIMEOUT_MS);
+ connect(heartbeat_timer_, &QTimer::timeout, this, &AlpacaWebSocket::on_heartbeat_timeout);
+
+ clock_timer_ = new QTimer(this);
+ clock_timer_->setInterval(CLOCK_CHECK_INTERVAL_MS);
+ connect(clock_timer_, &QTimer::timeout, this, &AlpacaWebSocket::on_clock_check);
+}
+
+AlpacaWebSocket::~AlpacaWebSocket() {
+ close();
+}
+
+// ── Public API ──────────────────────────────────────────────────────────────
+
+void AlpacaWebSocket::open() {
+ LOG_INFO(kTag, "Checking market clock before connecting...");
+
+ QPointer<AlpacaWebSocket> self = this;
+ const QString api_key = api_key_;
+ const QString api_secret = api_secret_;
+
+ (void)QtConcurrent::run([self, api_key, api_secret]() {
+ auto* broker = BrokerRegistry::instance().get("alpaca");
+ if (!broker) return;
+
+ BrokerCredentials creds;
+ creds.broker_id = "alpaca";
+ creds.api_key = api_key;
+ creds.api_secret = api_secret;
+
+ auto result = broker->get_clock(creds);
+ QMetaObject::invokeMethod(self, [self, result]() {
+ if (!self) return;
+
+ bool should_connect = true;
+ if (result.success && result.data) {
+ const auto& clock = *result.data;
+ if (!clock.is_open) {
+ LOG_INFO(kTag, QString("Market is closed. Next open: %1").arg(clock.next_open));
+ should_connect = false;
+ emit self->market_closed();
+ }
+ }
+
+ if (should_connect) {
+ LOG_INFO(kTag, QString("Connecting to %1").arg(kWsUrl));
+ self->ws_->connect_to(QString::fromLatin1(kWsUrl));
+ }
+
+ self->clock_timer_->start();
+ }, Qt::QueuedConnection);
+ });
+}
+
+void AlpacaWebSocket::close() {
+ if (heartbeat_timer_)
+ heartbeat_timer_->stop();
+ if (clock_timer_)
+ clock_timer_->stop();
+ authenticated_ = false;
+ if (ws_)
+ ws_->disconnect();
+ if (connected_.exchange(false))
+ emit disconnected();
+}
+
+void AlpacaWebSocket::subscribe(const QStringList& symbols) {
+ for (const auto& s : symbols) {
+ if (!subscribed_symbols_.contains(s))
+ subscribed_symbols_.append(s);
+ }
+ if (authenticated_)
+ send_subscribe(symbols);
+}
+
+void AlpacaWebSocket::unsubscribe(const QStringList& symbols) {
+ for (const auto& s : symbols)
+ subscribed_symbols_.removeAll(s);
+ if (authenticated_)
+ send_unsubscribe(symbols);
+}
+
+void AlpacaWebSocket::set_subscriptions(const QStringList& symbols) {
+ if (authenticated_ && !subscribed_symbols_.isEmpty())
+ send_unsubscribe(subscribed_symbols_);
+ subscribed_symbols_ = symbols;
+ if (authenticated_)
+ send_subscribe(symbols);
+}
+
+// ── WebSocketClient callbacks ───────────────────────────────────────────────
+
+void AlpacaWebSocket::on_ws_connected() {
+ LOG_INFO(kTag, "WebSocket connected, sending auth...");
+ heartbeat_timer_->start();
+ send_auth();
+}
+
+void AlpacaWebSocket::on_ws_disconnected() {
+ LOG_WARN(kTag, "WebSocket disconnected");
+ heartbeat_timer_->stop();
+ authenticated_ = false;
+ if (connected_.exchange(false))
+ emit disconnected();
+}
+
+void AlpacaWebSocket::on_ws_error(const QString& error) {
+ LOG_ERROR(kTag, "WebSocket error: " + error);
+ emit error_occurred(error);
+}
+
+void AlpacaWebSocket::on_heartbeat_timeout() {
+ LOG_WARN(kTag, "No messages received in 15s — forcing reconnect");
+ if (ws_)
+ ws_->disconnect();
+}
+
+void AlpacaWebSocket::on_clock_check() {
+ QPointer<AlpacaWebSocket> self = this;
+ const QString api_key = api_key_;
+ const QString api_secret = api_secret_;
+
+ (void)QtConcurrent::run([self, api_key, api_secret]() {
+ auto* broker = BrokerRegistry::instance().get("alpaca");
+ if (!broker) return;
+
+ BrokerCredentials creds;
+ creds.broker_id = "alpaca";
+ creds.api_key = api_key;
+ creds.api_secret = api_secret;
+
+ auto result = broker->get_clock(creds);
+ QMetaObject::invokeMethod(self, [self, result]() {
+ if (!self) return;
+ if (!result.success || !result.data) return;
+
+ const auto& clock = *result.data;
+ if (clock.is_open && !self->connected_.load()) {
+ LOG_INFO(kTag, "Market opened — connecting WebSocket");
+ self->ws_->connect_to(QString::fromLatin1(kWsUrl));
+ } else if (!clock.is_open && self->connected_.load()) {
+ LOG_INFO(kTag, "Market closed — disconnecting WebSocket");
+ self->close();
+ self->clock_timer_->start();
+ emit self->market_closed();
+ }
+ }, Qt::QueuedConnection);
+ });
+}
+
+// ── Protocol messages ───────────────────────────────────────────────────────
+
+void AlpacaWebSocket::send_auth() {
+ QJsonObject msg;
+ msg["action"] = QStringLiteral("auth");
+ msg["key"] = api_key_;
+ msg["secret"] = api_secret_;
+ ws_->send(compact_json(msg));
+}
+
+void AlpacaWebSocket::send_subscribe(const QStringList& symbols) {
+ if (symbols.isEmpty()) return;
+
+ QJsonArray syms;
+ for (const auto& s : symbols)
+ syms.append(s);
+
+ QJsonObject msg;
+ msg["action"] = QStringLiteral("subscribe");
+ msg["trades"] = syms;
+ msg["quotes"] = syms;
+ msg["bars"] = syms;
+
+ LOG_INFO(kTag, QString("Subscribing to %1 symbols").arg(symbols.size()));
+ ws_->send(compact_json(msg));
+}
+
+void AlpacaWebSocket::send_unsubscribe(const QStringList& symbols) {
+ if (symbols.isEmpty()) return;
+
+ QJsonArray syms;
+ for (const auto& s : symbols)
+ syms.append(s);
+
+ QJsonObject msg;
+ msg["action"] = QStringLiteral("unsubscribe");
+ msg["trades"] = syms;
+ msg["quotes"] = syms;
+ msg["bars"] = syms;
+
+ ws_->send(compact_json(msg));
+}
+
+// ── Message parsing ─────────────────────────────────────────────────────────
+
+void AlpacaWebSocket::on_ws_message(const QString& message) {
+ if (heartbeat_timer_)
+ heartbeat_timer_->start();
+
+ QJsonParseError err;
+ const auto doc = QJsonDocument::fromJson(message.toUtf8(), &err);
+ if (err.error != QJsonParseError::NoError)
+ return;
+
+ if (!doc.isArray())
+ return;
+
+ const auto arr = doc.array();
+ for (const auto& val : arr) {
+ if (!val.isObject()) continue;
+ handle_message(val.toObject());
+ }
+}
+
+void AlpacaWebSocket::handle_message(const QJsonObject& msg) {
+ const QString type = msg.value("T").toString();
+
+ if (type == QLatin1String("success")) handle_success(msg);
+ else if (type == QLatin1String("error")) handle_error(msg);
+ else if (type == QLatin1String("subscription")) handle_subscription(msg);
+ else if (type == QLatin1String("t")) handle_trade(msg);
+ else if (type == QLatin1String("q")) handle_quote(msg);
+ else if (type == QLatin1String("b")) handle_bar(msg);
+}
+
+void AlpacaWebSocket::handle_success(const QJsonObject& msg) {
+ const QString m = msg.value("msg").toString();
+ if (m == QLatin1String("connected")) {
+ LOG_INFO(kTag, "Server acknowledged connection");
+ } else if (m == QLatin1String("authenticated")) {
+ LOG_INFO(kTag, "Authentication successful");
+ authenticated_ = true;
+ if (!connected_.exchange(true))
+ emit connected();
+ if (!subscribed_symbols_.isEmpty())
+ send_subscribe(subscribed_symbols_);
+ }
+}
+
+void AlpacaWebSocket::handle_error(const QJsonObject& msg) {
+ const int code = msg.value("code").toInt();
+ const QString err_msg = msg.value("msg").toString();
+ LOG_ERROR(kTag, QString("Error %1: %2").arg(code).arg(err_msg));
+
+ if (code == 402) {
+ LOG_ERROR(kTag, "Authentication failed — invalid credentials");
+ emit error_occurred("Authentication failed: " + err_msg);
+ } else if (code == 406) {
+ LOG_WARN(kTag, "Connection limit exceeded — another session may be active");
+ emit error_occurred("Connection limit exceeded");
+ } else {
+ emit error_occurred(QString("Error %1: %2").arg(code).arg(err_msg));
+ }
+}
+
+void AlpacaWebSocket::handle_subscription(const QJsonObject& msg) {
+ const auto trades = msg.value("trades").toArray();
+ const auto quotes = msg.value("quotes").toArray();
+ const auto bars = msg.value("bars").toArray();
+ LOG_INFO(kTag, QString("Subscribed — trades: %1, quotes: %2, bars: %3")
+ .arg(trades.size()).arg(quotes.size()).arg(bars.size()));
+}
+
+void AlpacaWebSocket::handle_trade(const QJsonObject& msg) {
+ BrokerTrade trade;
+ trade.symbol = msg.value("S").toString();
+ trade.price = msg.value("p").toDouble();
+ trade.size = msg.value("s").toDouble();
+ trade.exchange = msg.value("x").toString();
+ trade.timestamp = msg.value("t").toString();
+ trade.tape = msg.value("z").toString();
+
+ const auto conditions = msg.value("c").toArray();
+ for (const auto& c : conditions)
+ trade.conditions.append(c.toString());
+
+ if (trade.price <= 0.0) return;
+ emit trade_received(trade);
+}
+
+void AlpacaWebSocket::handle_quote(const QJsonObject& msg) {
+ const QString symbol = msg.value("S").toString();
+ const double bid = msg.value("bp").toDouble();
+ const double ask = msg.value("ap").toDouble();
+ const double bid_size = msg.value("bs").toDouble();
+ const double ask_size = msg.value("as").toDouble();
+ const int64_t ts = parse_rfc3339_to_ms(msg.value("t").toString());
+
+ BrokerQuote q;
+ q.symbol = symbol;
+ q.bid = bid;
+ q.ask = ask;
+ q.bid_size = bid_size;
+ q.ask_size = ask_size;
+ q.timestamp = ts;
+
+ if (bid > 0.0 && ask > 0.0)
+ q.ltp = (bid + ask) / 2.0;
+
+ emit tick_received(q);
+}
+
+void AlpacaWebSocket::handle_bar(const QJsonObject& msg) {
+ const QString symbol = msg.value("S").toString();
+
+ BrokerCandle candle;
+ candle.open = msg.value("o").toDouble();
+ candle.high = msg.value("h").toDouble();
+ candle.low = msg.value("l").toDouble();
+ candle.close = msg.value("c").toDouble();
+ candle.volume = msg.value("v").toDouble();
+ candle.timestamp = parse_rfc3339_to_ms(msg.value("t").toString());
+
+ if (candle.open <= 0.0) return;
+ emit bar_received(symbol, candle);
+}
+
+// ── Helpers ─────────────────────────────────────────────────────────────────
+
+int64_t AlpacaWebSocket::parse_rfc3339_to_ms(const QString& ts) {
+ if (ts.isEmpty()) return 0;
+ const auto dt = QDateTime::fromString(ts, Qt::ISODateWithMs);
+ if (dt.isValid()) return dt.toMSecsSinceEpoch();
+ const auto dt2 = QDateTime::fromString(ts, Qt::ISODate);
+ return dt2.isValid() ? dt2.toMSecsSinceEpoch() : 0;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/alpaca/AlpacaWebSocket.h b/fincept-qt/src/trading/brokers/alpaca/AlpacaWebSocket.h
new file mode 100644
index 000000000..b48bde4bc
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/alpaca/AlpacaWebSocket.h
@@ -0,0 +1,93 @@
+#pragma once
+// Alpaca Data API v2 WebSocket client for real-time US equity market data.
+//
+// Protocol: wss://stream.data.alpaca.markets/v2/{feed}
+// - JSON-based auth: {"action":"auth","key":"...","secret":"..."}
+// - Subscribe: {"action":"subscribe","trades":["AAPL"],"quotes":["AAPL"],"bars":["AAPL"]}
+// - Messages arrive as JSON arrays: [{"T":"t",...},{"T":"q",...}]
+// - Must authenticate within 10s of connect
+// - Connection limit: 1 per endpoint per user
+//
+// Market-hours aware: checks AlpacaBroker::get_clock() on init and periodically.
+// Connects only when the market is open (or within 15min of open). Disconnects
+// gracefully after market close.
+
+#include "trading/TradingTypes.h"
+
+#include <QObject>
+#include <QStringList>
+#include <QTimer>
+
+#include <atomic>
+
+namespace fincept {
+class WebSocketClient;
+}
+
+namespace fincept::trading {
+
+class AlpacaWebSocket : public QObject {
+ Q_OBJECT
+ public:
+ explicit AlpacaWebSocket(const QString& api_key, const QString& api_secret,
+ QObject* parent = nullptr);
+ ~AlpacaWebSocket() override;
+
+ void open();
+ void close();
+ bool is_connected() const { return connected_.load(); }
+
+ void subscribe(const QStringList& symbols);
+ void unsubscribe(const QStringList& symbols);
+ void set_subscriptions(const QStringList& symbols);
+
+ signals:
+ void tick_received(const fincept::trading::BrokerQuote& quote);
+ void trade_received(const fincept::trading::BrokerTrade& trade);
+ void bar_received(const QString& symbol, const fincept::trading::BrokerCandle& candle);
+ void connected();
+ void disconnected();
+ void error_occurred(const QString& error);
+ void market_closed();
+
+ private slots:
+ void on_ws_connected();
+ void on_ws_disconnected();
+ void on_ws_message(const QString& message);
+ void on_ws_error(const QString& error);
+ void on_heartbeat_timeout();
+ void on_clock_check();
+
+ private:
+ void send_auth();
+ void send_subscribe(const QStringList& symbols);
+ void send_unsubscribe(const QStringList& symbols);
+
+ void handle_message(const QJsonObject& msg);
+ void handle_trade(const QJsonObject& msg);
+ void handle_quote(const QJsonObject& msg);
+ void handle_bar(const QJsonObject& msg);
+ void handle_success(const QJsonObject& msg);
+ void handle_error(const QJsonObject& msg);
+ void handle_subscription(const QJsonObject& msg);
+
+ static int64_t parse_rfc3339_to_ms(const QString& ts);
+
+ QString api_key_;
+ QString api_secret_;
+
+ fincept::WebSocketClient* ws_ = nullptr;
+ QTimer* heartbeat_timer_ = nullptr;
+ QTimer* clock_timer_ = nullptr;
+
+ QStringList subscribed_symbols_;
+ std::atomic<bool> connected_{false};
+ bool authenticated_ = false;
+
+ static constexpr int HEARTBEAT_TIMEOUT_MS = 15000;
+ static constexpr int CLOCK_CHECK_INTERVAL_MS = 60000;
+ static constexpr const char* kWsUrl = "wss://stream.data.alpaca.markets/v2/iex";
+ static constexpr const char* kTag = "AlpacaWS";
+};
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
index 66c1a5b40..d695d7356 100644
--- a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
+++ b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp
@@ -408,7 +408,7 @@ ApiResponse<QVector<BrokerQuote>> FyersBroker::get_quotes(const BrokerCredential
q.change_pct = v.value("chp").toDouble();
q.bid = v.value("bid").toDouble();
q.ask = v.value("ask").toDouble();
- q.timestamp = v.value("tt").toVariant().toLongLong();
+ q.timestamp = v.value("tt").toVariant().toLongLong() * 1000;
q.oi = v.value("oi").toVariant().toLongLong();
q.oi_change_pct = v.value("oichp").toDouble();
all_quotes.append(q);
@@ -450,7 +450,8 @@ ApiResponse<QVector<BrokerCandle>> FyersBroker::get_history(const BrokerCredenti
if (c.size() < 6)
continue;
BrokerCandle candle;
- candle.timestamp = c[0].toVariant().toLongLong();
+ // Fyers returns epoch in seconds; internal convention is milliseconds.
+ candle.timestamp = c[0].toVariant().toLongLong() * 1000;
candle.open = c[1].toDouble();
candle.high = c[2].toDouble();
candle.low = c[3].toDouble();
diff --git a/fincept-qt/src/ui/charts/CandleData.h b/fincept-qt/src/ui/charts/CandleData.h
new file mode 100644
index 000000000..d3462bc27
--- /dev/null
+++ b/fincept-qt/src/ui/charts/CandleData.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include "trading/TradingTypes.h"
+
+#include <QVector>
+#include <algorithm>
+
+namespace fincept::ui {
+
+struct CandleData {
+ int64_t timestamp = 0;
+ double open = 0.0;
+ double high = 0.0;
+ double low = 0.0;
+ double close = 0.0;
+ double volume = 0.0;
+
+ static CandleData from(const trading::Candle& c) {
+ return {c.timestamp, c.open, c.high, c.low, c.close, c.volume};
+ }
+
+ static CandleData from(const trading::BrokerCandle& c) {
+ return {c.timestamp, c.open, c.high, c.low, c.close, c.volume};
+ }
+
+ static QVector<CandleData> from_candles(const QVector<trading::Candle>& src) {
+ QVector<CandleData> out;
+ out.reserve(src.size());
+ for (const auto& c : src)
+ out.append(from(c));
+ return out;
+ }
+
+ static QVector<CandleData> from_broker_candles(const QVector<trading::BrokerCandle>& src) {
+ QVector<CandleData> out;
+ out.reserve(src.size());
+ for (const auto& c : src)
+ out.append(from(c));
+ return out;
+ }
+
+ static void sort_by_time(QVector<CandleData>& candles) {
+ std::sort(candles.begin(), candles.end(),
+ [](const CandleData& a, const CandleData& b) { return a.timestamp < b.timestamp; });
+ }
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/ChartIndicators.cpp b/fincept-qt/src/ui/charts/ChartIndicators.cpp
new file mode 100644
index 000000000..53b682c72
--- /dev/null
+++ b/fincept-qt/src/ui/charts/ChartIndicators.cpp
@@ -0,0 +1,133 @@
+#include "ui/charts/ChartIndicators.h"
+
+#include <cmath>
+#include <limits>
+
+namespace fincept::ui::indicators {
+
+QVector<double> sma(const QVector<double>& values, int period) {
+ const int n = values.size();
+ QVector<double> out(n, std::numeric_limits<double>::quiet_NaN());
+ if (period < 1 || n < period)
+ return out;
+
+ double sum = 0;
+ for (int i = 0; i < period; ++i)
+ sum += values[i];
+ out[period - 1] = sum / period;
+
+ for (int i = period; i < n; ++i) {
+ sum += values[i] - values[i - period];
+ out[i] = sum / period;
+ }
+ return out;
+}
+
+QVector<double> vwap(const QVector<double>& highs,
+ const QVector<double>& lows,
+ const QVector<double>& closes,
+ const QVector<double>& volumes) {
+ const int n = closes.size();
+ QVector<double> out(n, std::numeric_limits<double>::quiet_NaN());
+ if (n == 0)
+ return out;
+
+ double cum_tp_vol = 0;
+ double cum_vol = 0;
+
+ for (int i = 0; i < n; ++i) {
+ const double tp = (highs[i] + lows[i] + closes[i]) / 3.0;
+ cum_tp_vol += tp * volumes[i];
+ cum_vol += volumes[i];
+ out[i] = (cum_vol > 0) ? cum_tp_vol / cum_vol : std::numeric_limits<double>::quiet_NaN();
+ }
+ return out;
+}
+
+QVector<double> vwap_std_dev(const QVector<double>& highs,
+ const QVector<double>& lows,
+ const QVector<double>& closes,
+ const QVector<double>& volumes,
+ const QVector<double>& vwap_values) {
+ const int n = closes.size();
+ QVector<double> out(n, std::numeric_limits<double>::quiet_NaN());
+ if (n == 0)
+ return out;
+
+ double cum_vol = 0;
+ double cum_sq_diff_vol = 0;
+
+ for (int i = 0; i < n; ++i) {
+ const double tp = (highs[i] + lows[i] + closes[i]) / 3.0;
+ cum_vol += volumes[i];
+ const double diff = tp - vwap_values[i];
+ cum_sq_diff_vol += diff * diff * volumes[i];
+ out[i] = (cum_vol > 0) ? std::sqrt(cum_sq_diff_vol / cum_vol) : 0.0;
+ }
+ return out;
+}
+
+BollingerResult bollinger(const QVector<double>& closes, int period, double num_std) {
+ const int n = closes.size();
+ BollingerResult result;
+ result.upper.resize(n, std::numeric_limits<double>::quiet_NaN());
+ result.middle = sma(closes, period);
+ result.lower.resize(n, std::numeric_limits<double>::quiet_NaN());
+
+ for (int i = period - 1; i < n; ++i) {
+ double sum_sq = 0;
+ for (int j = i - period + 1; j <= i; ++j) {
+ const double diff = closes[j] - result.middle[i];
+ sum_sq += diff * diff;
+ }
+ const double sd = std::sqrt(sum_sq / period);
+ result.upper[i] = result.middle[i] + num_std * sd;
+ result.lower[i] = result.middle[i] - num_std * sd;
+ }
+ return result;
+}
+
+PivotResult pivot_points(double high, double low, double close, PivotType type) {
+ PivotResult r;
+ switch (type) {
+ case PivotType::Standard:
+ r.pp = (high + low + close) / 3.0;
+ r.r1 = 2 * r.pp - low;
+ r.s1 = 2 * r.pp - high;
+ r.r2 = r.pp + (high - low);
+ r.s2 = r.pp - (high - low);
+ r.r3 = high + 2 * (r.pp - low);
+ r.s3 = low - 2 * (high - r.pp);
+ break;
+ case PivotType::Camarilla:
+ r.pp = (high + low + close) / 3.0;
+ r.r1 = close + (high - low) * 1.1 / 12;
+ r.s1 = close - (high - low) * 1.1 / 12;
+ r.r2 = close + (high - low) * 1.1 / 6;
+ r.s2 = close - (high - low) * 1.1 / 6;
+ r.r3 = close + (high - low) * 1.1 / 4;
+ r.s3 = close - (high - low) * 1.1 / 4;
+ break;
+ case PivotType::Woodie:
+ r.pp = (high + low + 2 * close) / 4.0;
+ r.r1 = 2 * r.pp - low;
+ r.s1 = 2 * r.pp - high;
+ r.r2 = r.pp + (high - low);
+ r.s2 = r.pp - (high - low);
+ r.r3 = high + 2 * (r.pp - low);
+ r.s3 = low - 2 * (high - r.pp);
+ break;
+ case PivotType::Fibonacci:
+ r.pp = (high + low + close) / 3.0;
+ r.r1 = r.pp + 0.382 * (high - low);
+ r.s1 = r.pp - 0.382 * (high - low);
+ r.r2 = r.pp + 0.618 * (high - low);
+ r.s2 = r.pp - 0.618 * (high - low);
+ r.r3 = r.pp + 1.000 * (high - low);
+ r.s3 = r.pp - 1.000 * (high - low);
+ break;
+ }
+ return r;
+}
+
+} // namespace fincept::ui::indicators
diff --git a/fincept-qt/src/ui/charts/ChartIndicators.h b/fincept-qt/src/ui/charts/ChartIndicators.h
new file mode 100644
index 000000000..2f3039d2a
--- /dev/null
+++ b/fincept-qt/src/ui/charts/ChartIndicators.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <QVector>
+
+namespace fincept::ui {
+
+struct BollingerResult {
+ QVector<double> upper;
+ QVector<double> middle;
+ QVector<double> lower;
+};
+
+struct PivotResult {
+ double pp = 0;
+ double r1 = 0, r2 = 0, r3 = 0;
+ double s1 = 0, s2 = 0, s3 = 0;
+};
+
+enum class PivotType { Standard, Camarilla, Woodie, Fibonacci };
+
+namespace indicators {
+
+QVector<double> sma(const QVector<double>& values, int period);
+
+QVector<double> vwap(const QVector<double>& highs,
+ const QVector<double>& lows,
+ const QVector<double>& closes,
+ const QVector<double>& volumes);
+
+QVector<double> vwap_std_dev(const QVector<double>& highs,
+ const QVector<double>& lows,
+ const QVector<double>& closes,
+ const QVector<double>& volumes,
+ const QVector<double>& vwap_values);
+
+BollingerResult bollinger(const QVector<double>& closes, int period = 20, double num_std = 2.0);
+
+PivotResult pivot_points(double high, double low, double close, PivotType type = PivotType::Standard);
+
+} // namespace indicators
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/ChartOverlayManager.cpp b/fincept-qt/src/ui/charts/ChartOverlayManager.cpp
new file mode 100644
index 000000000..4bfa7b7f1
--- /dev/null
+++ b/fincept-qt/src/ui/charts/ChartOverlayManager.cpp
@@ -0,0 +1,136 @@
+#include "ui/charts/ChartOverlayManager.h"
+#include "ui/charts/HorizontalLineLayer.h"
+
+#include <QChart>
+#include <QGraphicsScene>
+
+#include <algorithm>
+
+namespace fincept::ui {
+
+ChartOverlayManager::ChartOverlayManager(QObject* parent) : QObject(parent) {}
+
+ChartOverlayManager::~ChartOverlayManager() {
+ if (scene_ && chart_) {
+ for (auto* layer : layers_)
+ layer->detach(scene_, chart_);
+ }
+}
+
+void ChartOverlayManager::set_chart(QGraphicsScene* scene, QChart* chart) {
+ if (scene_ && chart_) {
+ for (auto* layer : layers_)
+ layer->detach(scene_, chart_);
+ }
+ scene_ = scene;
+ chart_ = chart;
+ if (scene_ && chart_) {
+ for (auto* layer : layers_)
+ layer->attach(scene_, chart_);
+ }
+}
+
+void ChartOverlayManager::add_layer(OverlayLayer* layer) {
+ if (has_layer(layer->id()))
+ return;
+
+ layer->setParent(this);
+ layers_.append(layer);
+
+ if (scene_ && chart_)
+ layer->attach(scene_, chart_);
+
+ if (!candles_.isEmpty())
+ layer->compute(candles_);
+
+ if (scene_ && chart_)
+ layer->reposition(chart_);
+
+ emit layer_added(layer->id());
+}
+
+void ChartOverlayManager::remove_layer(const QString& id) {
+ for (int i = 0; i < layers_.size(); ++i) {
+ if (layers_[i]->id() == id) {
+ auto* layer = layers_.takeAt(i);
+ if (scene_ && chart_)
+ layer->detach(scene_, chart_);
+ layer->deleteLater();
+ emit layer_removed(id);
+ return;
+ }
+ }
+}
+
+OverlayLayer* ChartOverlayManager::layer(const QString& id) const {
+ for (auto* l : layers_) {
+ if (l->id() == id)
+ return l;
+ }
+ return nullptr;
+}
+
+bool ChartOverlayManager::has_layer(const QString& id) const {
+ return layer(id) != nullptr;
+}
+
+void ChartOverlayManager::set_candles(QVector<CandleData> candles) {
+ CandleData::sort_by_time(candles);
+ candles_ = std::move(candles);
+ recompute_all();
+}
+
+void ChartOverlayManager::append_candle(const CandleData& candle) {
+ if (!candles_.isEmpty() && candles_.last().timestamp == candle.timestamp) {
+ candles_.last() = candle;
+ } else {
+ candles_.append(candle);
+ }
+ recompute_all();
+}
+
+void ChartOverlayManager::recompute_all() {
+ for (auto* layer : layers_) {
+ layer->compute(candles_);
+ if (chart_)
+ layer->reposition(chart_);
+ }
+}
+
+void ChartOverlayManager::reposition_all() {
+ if (!chart_)
+ return;
+ for (auto* layer : layers_) {
+ if (layer->visible())
+ layer->reposition(chart_);
+ }
+}
+
+QStringList ChartOverlayManager::active_layer_ids() const {
+ QStringList ids;
+ for (auto* l : layers_)
+ ids.append(l->id());
+ return ids;
+}
+
+bool ChartOverlayManager::overlay_price_range(double& out_min, double& out_max) const {
+ bool found = false;
+ out_min = 1e18;
+ out_max = 0;
+ for (const auto* layer : layers_) {
+ if (!layer->visible() || layer->type() != LayerType::HorizontalLine)
+ continue;
+ const auto* hl = qobject_cast<const HorizontalLineLayer*>(layer);
+ if (!hl) continue;
+ for (const auto& level : hl->levels()) {
+ if (level.price > 0) {
+ out_min = std::min(out_min, level.price);
+ out_max = std::max(out_max, level.price);
+ found = true;
+ }
+ }
+ }
+ return found;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/ChartOverlayManager.h b/fincept-qt/src/ui/charts/ChartOverlayManager.h
new file mode 100644
index 000000000..e7178903c
--- /dev/null
+++ b/fincept-qt/src/ui/charts/ChartOverlayManager.h
@@ -0,0 +1,51 @@
+#pragma once
+
+#include "ui/charts/CandleData.h"
+#include "ui/charts/OverlayLayer.h"
+
+#include <QObject>
+#include <QVector>
+
+class QChart;
+class QGraphicsScene;
+
+namespace fincept::ui {
+
+class ChartOverlayManager : public QObject {
+ Q_OBJECT
+public:
+ explicit ChartOverlayManager(QObject* parent = nullptr);
+ ~ChartOverlayManager() override;
+
+ void set_chart(QGraphicsScene* scene, QChart* chart);
+
+ void add_layer(OverlayLayer* layer);
+ void remove_layer(const QString& id);
+ OverlayLayer* layer(const QString& id) const;
+ QVector<OverlayLayer*> layers() const { return layers_; }
+ bool has_layer(const QString& id) const;
+
+ void set_candles(QVector<CandleData> candles);
+ void append_candle(const CandleData& candle);
+
+ void recompute_all();
+ void reposition_all();
+
+ QStringList active_layer_ids() const;
+
+ // Returns the min/max price across all HorizontalLineLayer levels.
+ // Charts should expand their Y axis to include these values.
+ bool overlay_price_range(double& out_min, double& out_max) const;
+
+signals:
+ void layer_added(const QString& id);
+ void layer_removed(const QString& id);
+
+private:
+ QVector<OverlayLayer*> layers_;
+ QVector<CandleData> candles_;
+ QGraphicsScene* scene_ = nullptr;
+ QChart* chart_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/HorizontalLineLayer.cpp b/fincept-qt/src/ui/charts/HorizontalLineLayer.cpp
new file mode 100644
index 000000000..057a942c0
--- /dev/null
+++ b/fincept-qt/src/ui/charts/HorizontalLineLayer.cpp
@@ -0,0 +1,123 @@
+#include "ui/charts/HorizontalLineLayer.h"
+
+#include <QChart>
+#include <QGraphicsLineItem>
+#include <QGraphicsRectItem>
+#include <QGraphicsScene>
+#include <QGraphicsSimpleTextItem>
+#include <QPen>
+
+namespace fincept::ui {
+
+HorizontalLineLayer::HorizontalLineLayer(const QString& id, const QString& name, QObject* parent)
+ : OverlayLayer(parent), id_(id), name_(name) {}
+
+void HorizontalLineLayer::compute(const QVector<CandleData>&) {
+ // Levels are set externally via set_levels() — nothing to compute.
+}
+
+void HorizontalLineLayer::set_levels(const QVector<HorizontalLevel>& levels) {
+ levels_ = levels;
+ if (scene_ && chart_) {
+ clear_items();
+ rebuild_items();
+ reposition(chart_);
+ }
+}
+
+void HorizontalLineLayer::attach(QGraphicsScene* scene, QChart* chart) {
+ scene_ = scene;
+ chart_ = chart;
+ rebuild_items();
+ reposition(chart);
+}
+
+void HorizontalLineLayer::detach(QGraphicsScene* scene, QChart*) {
+ clear_items();
+ scene_ = nullptr;
+ chart_ = nullptr;
+}
+
+void HorizontalLineLayer::reposition(QChart* chart) {
+ if (!chart || items_.isEmpty())
+ return;
+
+ const QRectF plot = chart->plotArea();
+ constexpr qreal pad_x = 4, pad_y = 1;
+
+ for (int i = 0; i < items_.size() && i < levels_.size(); ++i) {
+ const auto& level = levels_[i];
+ const QPointF pos = chart->mapToPosition(QPointF(0, level.price));
+ const qreal y = pos.y();
+
+ const bool in_view = y >= plot.top() && y <= plot.bottom();
+
+ items_[i].line->setLine(plot.left(), y, plot.right(), y);
+ items_[i].line->setVisible(in_view && visible());
+
+ if (items_[i].tag_txt && items_[i].tag_bg) {
+ const QRectF tb = items_[i].tag_txt->boundingRect();
+ const qreal tag_w = tb.width() + 2 * pad_x;
+ const qreal tag_h = tb.height() + 2 * pad_y;
+ const qreal tag_x = plot.right() + 2;
+ const qreal tag_y = y - tag_h / 2.0;
+
+ items_[i].tag_bg->setRect(QRectF(tag_x, tag_y, tag_w, tag_h));
+ items_[i].tag_txt->setPos(tag_x + pad_x, tag_y + pad_y);
+ items_[i].tag_bg->setVisible(in_view && visible());
+ items_[i].tag_txt->setVisible(in_view && visible());
+ }
+ }
+}
+
+void HorizontalLineLayer::rebuild_items() {
+ if (!scene_)
+ return;
+
+ QFont tag_font;
+ tag_font.setFamily(QStringLiteral("Consolas"));
+ tag_font.setPixelSize(10);
+ tag_font.setWeight(QFont::DemiBold);
+
+ for (const auto& level : levels_) {
+ LineItem item;
+ QPen pen(level.color);
+ pen.setStyle(level.style);
+ pen.setWidth(1);
+ item.line = scene_->addLine(QLineF(), pen);
+ item.line->setZValue(5);
+
+ if (!level.label.isEmpty()) {
+ QColor bg_color = level.color;
+ bg_color.setAlpha(200);
+ item.tag_bg = scene_->addRect(QRectF(), QPen(Qt::NoPen), QBrush(bg_color));
+ item.tag_bg->setZValue(21);
+
+ item.tag_txt = scene_->addSimpleText(level.label);
+ item.tag_txt->setBrush(QBrush(QColor("#080808")));
+ item.tag_txt->setFont(tag_font);
+ item.tag_txt->setZValue(22);
+ }
+ items_.append(item);
+ }
+}
+
+void HorizontalLineLayer::clear_items() {
+ for (auto& item : items_) {
+ if (item.line && scene_) {
+ scene_->removeItem(item.line);
+ delete item.line;
+ }
+ if (item.tag_bg && scene_) {
+ scene_->removeItem(item.tag_bg);
+ delete item.tag_bg;
+ }
+ if (item.tag_txt && scene_) {
+ scene_->removeItem(item.tag_txt);
+ delete item.tag_txt;
+ }
+ }
+ items_.clear();
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/HorizontalLineLayer.h b/fincept-qt/src/ui/charts/HorizontalLineLayer.h
new file mode 100644
index 000000000..75f138632
--- /dev/null
+++ b/fincept-qt/src/ui/charts/HorizontalLineLayer.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include "ui/charts/OverlayLayer.h"
+
+#include <QColor>
+#include <QVector>
+
+class QGraphicsLineItem;
+class QGraphicsRectItem;
+class QGraphicsSimpleTextItem;
+
+namespace fincept::ui {
+
+struct HorizontalLevel {
+ double price = 0;
+ QString label;
+ QColor color;
+ Qt::PenStyle style = Qt::DashLine;
+};
+
+class HorizontalLineLayer : public OverlayLayer {
+ Q_OBJECT
+public:
+ explicit HorizontalLineLayer(const QString& id, const QString& name, QObject* parent = nullptr);
+
+ QString id() const override { return id_; }
+ QString display_name() const override { return name_; }
+ LayerType type() const override { return LayerType::HorizontalLine; }
+
+ void compute(const QVector<CandleData>& candles) override;
+ void attach(QGraphicsScene* scene, QChart* chart) override;
+ void detach(QGraphicsScene* scene, QChart* chart) override;
+ void reposition(QChart* chart) override;
+
+ void set_levels(const QVector<HorizontalLevel>& levels);
+ const QVector<HorizontalLevel>& levels() const { return levels_; }
+
+private:
+ void rebuild_items();
+ void clear_items();
+
+ QString id_;
+ QString name_;
+ QVector<HorizontalLevel> levels_;
+
+ struct LineItem {
+ QGraphicsLineItem* line = nullptr;
+ QGraphicsRectItem* tag_bg = nullptr;
+ QGraphicsSimpleTextItem* tag_txt = nullptr;
+ };
+ QVector<LineItem> items_;
+
+ QGraphicsScene* scene_ = nullptr;
+ QChart* chart_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/IndicatorParamDialog.cpp b/fincept-qt/src/ui/charts/IndicatorParamDialog.cpp
new file mode 100644
index 000000000..da800a8c0
--- /dev/null
+++ b/fincept-qt/src/ui/charts/IndicatorParamDialog.cpp
@@ -0,0 +1,78 @@
+#include "ui/charts/IndicatorParamDialog.h"
+
+#include <QComboBox>
+#include <QDialogButtonBox>
+#include <QDoubleSpinBox>
+#include <QFormLayout>
+#include <QLabel>
+#include <QSpinBox>
+#include <QVBoxLayout>
+
+namespace fincept::ui {
+
+IndicatorParamDialog::IndicatorParamDialog(const QString& indicator_id, QWidget* parent)
+ : QDialog(parent), id_(indicator_id) {
+ setObjectName("indicatorParamDialog");
+ setWindowTitle("Indicator Parameters");
+ setFixedWidth(280);
+
+ auto* layout = new QVBoxLayout(this);
+
+ if (id_.startsWith("ema"))
+ setup_ema_ui();
+ else if (id_.startsWith("bb"))
+ setup_bollinger_ui();
+ else if (id_.startsWith("pivot"))
+ setup_pivot_ui();
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
+ connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ layout->addWidget(buttons);
+}
+
+void IndicatorParamDialog::setup_ema_ui() {
+ auto* form = new QFormLayout();
+ period_spin_ = new QSpinBox(this);
+ period_spin_->setRange(2, 500);
+ period_spin_->setValue(21);
+ form->addRow("Period:", period_spin_);
+ qobject_cast<QVBoxLayout*>(layout())->insertLayout(0, form);
+}
+
+void IndicatorParamDialog::setup_bollinger_ui() {
+ auto* form = new QFormLayout();
+ period_spin_ = new QSpinBox(this);
+ period_spin_->setRange(2, 200);
+ period_spin_->setValue(20);
+ form->addRow("Period:", period_spin_);
+
+ std_spin_ = new QDoubleSpinBox(this);
+ std_spin_->setRange(0.5, 5.0);
+ std_spin_->setValue(2.0);
+ std_spin_->setSingleStep(0.5);
+ form->addRow("Std Dev:", std_spin_);
+ qobject_cast<QVBoxLayout*>(layout())->insertLayout(0, form);
+}
+
+void IndicatorParamDialog::setup_pivot_ui() {
+ auto* form = new QFormLayout();
+ pivot_combo_ = new QComboBox(this);
+ pivot_combo_->addItems({"Standard", "Camarilla", "Woodie", "Fibonacci"});
+ form->addRow("Type:", pivot_combo_);
+ qobject_cast<QVBoxLayout*>(layout())->insertLayout(0, form);
+}
+
+int IndicatorParamDialog::period() const {
+ return period_spin_ ? period_spin_->value() : 21;
+}
+
+double IndicatorParamDialog::std_dev() const {
+ return std_spin_ ? std_spin_->value() : 2.0;
+}
+
+QString IndicatorParamDialog::pivot_type() const {
+ return pivot_combo_ ? pivot_combo_->currentText() : "Standard";
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/IndicatorParamDialog.h b/fincept-qt/src/ui/charts/IndicatorParamDialog.h
new file mode 100644
index 000000000..02718a0fd
--- /dev/null
+++ b/fincept-qt/src/ui/charts/IndicatorParamDialog.h
@@ -0,0 +1,31 @@
+#pragma once
+
+#include <QDialog>
+
+class QSpinBox;
+class QDoubleSpinBox;
+class QComboBox;
+
+namespace fincept::ui {
+
+class IndicatorParamDialog : public QDialog {
+ Q_OBJECT
+public:
+ explicit IndicatorParamDialog(const QString& indicator_id, QWidget* parent = nullptr);
+
+ int period() const;
+ double std_dev() const;
+ QString pivot_type() const;
+
+private:
+ void setup_ema_ui();
+ void setup_bollinger_ui();
+ void setup_pivot_ui();
+
+ QString id_;
+ QSpinBox* period_spin_ = nullptr;
+ QDoubleSpinBox* std_spin_ = nullptr;
+ QComboBox* pivot_combo_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/IndicatorPicker.cpp b/fincept-qt/src/ui/charts/IndicatorPicker.cpp
new file mode 100644
index 000000000..83b36e38a
--- /dev/null
+++ b/fincept-qt/src/ui/charts/IndicatorPicker.cpp
@@ -0,0 +1,115 @@
+#include "ui/charts/IndicatorPicker.h"
+
+#include "ui/charts/ChartOverlayManager.h"
+#include "ui/charts/layers/BollingerLayer.h"
+#include "ui/charts/layers/EmaLayer.h"
+#include "ui/charts/layers/VwapLayer.h"
+
+#include <QHBoxLayout>
+#include <QMenu>
+#include <QPushButton>
+
+namespace fincept::ui {
+
+IndicatorPicker::IndicatorPicker(ChartOverlayManager* mgr, QWidget* parent)
+ : QWidget(parent), mgr_(mgr) {
+ setObjectName("indicatorPicker");
+ setFixedHeight(28);
+
+ auto* layout = new QHBoxLayout(this);
+ layout->setContentsMargins(8, 0, 8, 0);
+ layout->setSpacing(4);
+
+ add_btn_ = new QPushButton("+ Indicator");
+ add_btn_->setObjectName("indicatorAddBtn");
+ add_btn_->setFixedHeight(22);
+ add_btn_->setCursor(Qt::PointingHandCursor);
+ connect(add_btn_, &QPushButton::clicked, this, &IndicatorPicker::build_menu);
+ layout->addWidget(add_btn_);
+
+ chip_container_ = new QWidget(this);
+ chip_container_->setObjectName("indicatorChipContainer");
+ chip_layout_ = new QHBoxLayout(chip_container_);
+ chip_layout_->setContentsMargins(0, 0, 0, 0);
+ chip_layout_->setSpacing(4);
+ layout->addWidget(chip_container_);
+
+ layout->addStretch();
+
+ connect(mgr_, &ChartOverlayManager::layer_added, this, &IndicatorPicker::refresh_chips);
+ connect(mgr_, &ChartOverlayManager::layer_removed, this, &IndicatorPicker::refresh_chips);
+}
+
+void IndicatorPicker::build_menu() {
+ auto* menu = new QMenu(this);
+ menu->setObjectName("indicatorMenu");
+
+ const auto defs = available_indicators();
+ QString last_cat;
+ for (const auto& def : defs) {
+ if (def.category != last_cat) {
+ if (!last_cat.isEmpty())
+ menu->addSeparator();
+ menu->addSection(def.category);
+ last_cat = def.category;
+ }
+
+ auto* action = menu->addAction(def.name);
+ action->setEnabled(!mgr_->has_layer(def.id));
+ connect(action, &QAction::triggered, this, [this, id = def.id]() {
+ emit indicator_requested(id);
+ });
+ }
+ menu->popup(add_btn_->mapToGlobal(QPoint(0, add_btn_->height())));
+}
+
+void IndicatorPicker::add_chip(const QString& id, const QString& name) {
+ auto* chip = new QPushButton(name + QStringLiteral(" ×"), chip_container_);
+ chip->setObjectName("indicatorChip");
+ chip->setFixedHeight(20);
+ chip->setCursor(Qt::PointingHandCursor);
+ chip->setProperty("layerId", id);
+ connect(chip, &QPushButton::clicked, this, [this, id]() {
+ emit indicator_removed(id);
+ });
+ chip_layout_->addWidget(chip);
+}
+
+void IndicatorPicker::remove_chip(const QString& id) {
+ for (int i = chip_layout_->count() - 1; i >= 0; --i) {
+ auto* item = chip_layout_->itemAt(i);
+ if (auto* w = item->widget()) {
+ if (w->property("layerId").toString() == id) {
+ chip_layout_->removeWidget(w);
+ w->deleteLater();
+ return;
+ }
+ }
+ }
+}
+
+void IndicatorPicker::refresh_chips() {
+ while (chip_layout_->count() > 0) {
+ auto* item = chip_layout_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ for (auto* layer : mgr_->layers())
+ add_chip(layer->id(), layer->display_name());
+}
+
+QVector<IndicatorDef> IndicatorPicker::available_indicators() {
+ return {
+ {"ema_9", "EMA (9)", "Trend"},
+ {"ema_21", "EMA (21)", "Trend"},
+ {"ema_50", "EMA (50)", "Trend"},
+ {"ema_200", "EMA (200)", "Trend"},
+ {"vwap", "VWAP", "Volume"},
+ {"bb_20_2.0", "Bollinger (20,2)","Volatility"},
+ {"sr_auto", "Auto S/R", "Levels"},
+ {"pivot_std", "Pivot Points", "Levels"},
+ };
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/IndicatorPicker.h b/fincept-qt/src/ui/charts/IndicatorPicker.h
new file mode 100644
index 000000000..d47b63572
--- /dev/null
+++ b/fincept-qt/src/ui/charts/IndicatorPicker.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <QWidget>
+
+class QHBoxLayout;
+class QPushButton;
+
+namespace fincept::ui {
+
+class ChartOverlayManager;
+
+struct IndicatorDef {
+ QString id;
+ QString name;
+ QString category;
+};
+
+class IndicatorPicker : public QWidget {
+ Q_OBJECT
+public:
+ explicit IndicatorPicker(ChartOverlayManager* mgr, QWidget* parent = nullptr);
+
+signals:
+ void indicator_requested(const QString& id);
+ void indicator_removed(const QString& id);
+
+private:
+ void build_menu();
+ void add_chip(const QString& id, const QString& name);
+ void remove_chip(const QString& id);
+ void refresh_chips();
+
+ ChartOverlayManager* mgr_;
+ QPushButton* add_btn_ = nullptr;
+ QHBoxLayout* chip_layout_ = nullptr;
+ QWidget* chip_container_ = nullptr;
+
+ static QVector<IndicatorDef> available_indicators();
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/KLineChartWidget.cpp b/fincept-qt/src/ui/charts/KLineChartWidget.cpp
new file mode 100644
index 000000000..7089dfd0c
--- /dev/null
+++ b/fincept-qt/src/ui/charts/KLineChartWidget.cpp
@@ -0,0 +1,154 @@
+#include "ui/charts/KLineChartWidget.h"
+
+#ifdef HAS_QT_WEBENGINE
+#include <QWebEngineView>
+#include <QWebEnginePage>
+#include <QWebEngineSettings>
+#endif
+
+#include <QCoreApplication>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLabel>
+#include <QShowEvent>
+#include <QUrl>
+#include <QVBoxLayout>
+
+namespace fincept::ui {
+
+KLineChartWidget::KLineChartWidget(QWidget* parent) : QWidget(parent) {
+ setObjectName("klineChartWidget");
+
+ auto* layout = new QVBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(0);
+
+#ifndef HAS_QT_WEBENGINE
+ auto* fallback = new QLabel(this);
+ fallback->setObjectName("klineFallback");
+ fallback->setText(QStringLiteral("Advanced charting unavailable.\nInstall Qt WebEngine to enable KLineChart."));
+ fallback->setAlignment(Qt::AlignCenter);
+ layout->addWidget(fallback, 1);
+#endif
+}
+
+bool KLineChartWidget::is_available() const {
+#ifdef HAS_QT_WEBENGINE
+ return true;
+#else
+ return false;
+#endif
+}
+
+void KLineChartWidget::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ ensure_web_view();
+}
+
+void KLineChartWidget::ensure_web_view() {
+#ifdef HAS_QT_WEBENGINE
+ if (initialized_)
+ return;
+ initialized_ = true;
+
+ web_view_ = new QWebEngineView(this);
+ web_view_->setObjectName("klineWebView");
+
+ auto* settings = web_view_->page()->settings();
+ settings->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
+ settings->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);
+ settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, false);
+
+ connect(web_view_, &QWebEngineView::loadFinished,
+ this, &KLineChartWidget::on_load_finished);
+
+ const QString html_path = QCoreApplication::applicationDirPath()
+ + QStringLiteral("/resources/charts/klinechart.html");
+ web_view_->load(QUrl::fromLocalFile(html_path));
+
+ layout()->addWidget(web_view_);
+#endif
+}
+
+void KLineChartWidget::on_load_finished(bool ok) {
+ if (!ok) return;
+ page_ready_ = true;
+ flush_pending();
+ emit chart_ready();
+}
+
+void KLineChartWidget::run_js(const QString& js) {
+#ifdef HAS_QT_WEBENGINE
+ if (!page_ready_) {
+ pending_js_.enqueue(js);
+ return;
+ }
+ if (!web_view_) return;
+ web_view_->page()->runJavaScript(js);
+#else
+ Q_UNUSED(js);
+#endif
+}
+
+void KLineChartWidget::flush_pending() {
+#ifdef HAS_QT_WEBENGINE
+ if (!web_view_) return;
+ while (!pending_js_.isEmpty()) {
+ web_view_->page()->runJavaScript(pending_js_.dequeue());
+ }
+#endif
+}
+
+void KLineChartWidget::set_candles(const QJsonArray& candles) {
+ if (candles.isEmpty())
+ return;
+
+ QJsonArray converted;
+ for (const auto& v : candles) {
+ QJsonObject src = v.toObject();
+ QJsonObject dst;
+ dst[QStringLiteral("timestamp")] = static_cast<double>(src[QStringLiteral("timestamp")].toVariant().toLongLong()) * 1000.0;
+ dst[QStringLiteral("open")] = src[QStringLiteral("open")].toDouble();
+ dst[QStringLiteral("high")] = src[QStringLiteral("high")].toDouble();
+ dst[QStringLiteral("low")] = src[QStringLiteral("low")].toDouble();
+ dst[QStringLiteral("close")] = src[QStringLiteral("close")].toDouble();
+ dst[QStringLiteral("volume")] = src[QStringLiteral("volume")].toDouble();
+ converted.append(dst);
+ }
+
+ const QString json = QString::fromUtf8(QJsonDocument(converted).toJson(QJsonDocument::Compact));
+ run_js(QStringLiteral("window.setCandles(%1)").arg(json));
+}
+
+void KLineChartWidget::update_candle(const QJsonObject& candle) {
+ QJsonObject dst;
+ dst[QStringLiteral("timestamp")] = static_cast<double>(candle[QStringLiteral("timestamp")].toVariant().toLongLong()) * 1000.0;
+ dst[QStringLiteral("open")] = candle[QStringLiteral("open")].toDouble();
+ dst[QStringLiteral("high")] = candle[QStringLiteral("high")].toDouble();
+ dst[QStringLiteral("low")] = candle[QStringLiteral("low")].toDouble();
+ dst[QStringLiteral("close")] = candle[QStringLiteral("close")].toDouble();
+ dst[QStringLiteral("volume")] = candle[QStringLiteral("volume")].toDouble();
+
+ const QString json = QString::fromUtf8(QJsonDocument(dst).toJson(QJsonDocument::Compact));
+ run_js(QStringLiteral("window.updateCandle(%1)").arg(json));
+}
+
+void KLineChartWidget::add_indicator(const QString& name, const QString& pane_id) {
+ if (pane_id.isEmpty())
+ run_js(QStringLiteral("window.addIndicator('%1')").arg(name));
+ else
+ run_js(QStringLiteral("window.addIndicator('%1','%2')").arg(name, pane_id));
+}
+
+void KLineChartWidget::remove_indicator(const QString& name, const QString& pane_id) {
+ if (pane_id.isEmpty())
+ run_js(QStringLiteral("window.removeIndicator('%1')").arg(name));
+ else
+ run_js(QStringLiteral("window.removeIndicator('%1','%2')").arg(name, pane_id));
+}
+
+void KLineChartWidget::clear() {
+ run_js(QStringLiteral("window.clearChart()"));
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/KLineChartWidget.h b/fincept-qt/src/ui/charts/KLineChartWidget.h
new file mode 100644
index 000000000..6a1fc8180
--- /dev/null
+++ b/fincept-qt/src/ui/charts/KLineChartWidget.h
@@ -0,0 +1,47 @@
+#pragma once
+
+#include <QJsonArray>
+#include <QQueue>
+#include <QString>
+#include <QWidget>
+
+#ifdef HAS_QT_WEBENGINE
+class QWebEngineView;
+#endif
+
+namespace fincept::ui {
+
+class KLineChartWidget : public QWidget {
+ Q_OBJECT
+public:
+ explicit KLineChartWidget(QWidget* parent = nullptr);
+
+ void set_candles(const QJsonArray& candles);
+ void update_candle(const QJsonObject& candle);
+ void add_indicator(const QString& name, const QString& pane_id = QString());
+ void remove_indicator(const QString& name, const QString& pane_id = QString());
+ void clear();
+
+ bool is_available() const;
+
+signals:
+ void chart_ready();
+
+protected:
+ void showEvent(QShowEvent* e) override;
+
+private:
+ void ensure_web_view();
+ void run_js(const QString& js);
+ void flush_pending();
+ void on_load_finished(bool ok);
+
+#ifdef HAS_QT_WEBENGINE
+ QWebEngineView* web_view_ = nullptr;
+#endif
+ bool page_ready_ = false;
+ bool initialized_ = false;
+ QQueue<QString> pending_js_;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/OverlayLayer.cpp b/fincept-qt/src/ui/charts/OverlayLayer.cpp
new file mode 100644
index 000000000..113c360bb
--- /dev/null
+++ b/fincept-qt/src/ui/charts/OverlayLayer.cpp
@@ -0,0 +1,16 @@
+#include "ui/charts/OverlayLayer.h"
+
+namespace fincept::ui {
+
+OverlayLayer::OverlayLayer(QObject* parent) : QObject(parent) {}
+
+OverlayLayer::~OverlayLayer() = default;
+
+void OverlayLayer::set_visible(bool v) {
+ if (visible_ != v) {
+ visible_ = v;
+ emit visibility_changed(v);
+ }
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/OverlayLayer.h b/fincept-qt/src/ui/charts/OverlayLayer.h
new file mode 100644
index 000000000..4188f29aa
--- /dev/null
+++ b/fincept-qt/src/ui/charts/OverlayLayer.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include "ui/charts/CandleData.h"
+
+#include <QColor>
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+class QChart;
+class QGraphicsScene;
+
+namespace fincept::ui {
+
+enum class LayerType { Series, HorizontalLine, Region, Annotation };
+
+class OverlayLayer : public QObject {
+ Q_OBJECT
+public:
+ explicit OverlayLayer(QObject* parent = nullptr);
+ ~OverlayLayer() override;
+
+ virtual QString id() const = 0;
+ virtual QString display_name() const = 0;
+ virtual LayerType type() const = 0;
+
+ bool visible() const { return visible_; }
+ void set_visible(bool v);
+
+ virtual void compute(const QVector<CandleData>& candles) = 0;
+ virtual void attach(QGraphicsScene* scene, QChart* chart) = 0;
+ virtual void detach(QGraphicsScene* scene, QChart* chart) = 0;
+ virtual void reposition(QChart* chart) = 0;
+
+signals:
+ void visibility_changed(bool visible);
+
+private:
+ bool visible_ = true;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/SeriesLayer.cpp b/fincept-qt/src/ui/charts/SeriesLayer.cpp
new file mode 100644
index 000000000..f86881615
--- /dev/null
+++ b/fincept-qt/src/ui/charts/SeriesLayer.cpp
@@ -0,0 +1,78 @@
+#include "ui/charts/SeriesLayer.h"
+
+#include <QChart>
+#include <QGraphicsScene>
+#include <QLineSeries>
+
+#include <cmath>
+
+namespace fincept::ui {
+
+SeriesLayer::SeriesLayer(const QString& id, const QString& name,
+ const QColor& color, int width, QObject* parent)
+ : OverlayLayer(parent), id_(id), name_(name), color_(color), width_(width) {}
+
+void SeriesLayer::set_color(const QColor& c) {
+ color_ = c;
+ if (series_) {
+ QPen pen = series_->pen();
+ pen.setColor(c);
+ series_->setPen(pen);
+ }
+}
+
+void SeriesLayer::set_line_width(int w) {
+ width_ = w;
+ if (series_) {
+ QPen pen = series_->pen();
+ pen.setWidth(w);
+ series_->setPen(pen);
+ }
+}
+
+void SeriesLayer::attach(QGraphicsScene*, QChart* chart) {
+ chart_ = chart;
+ if (!series_) {
+ series_ = new QLineSeries();
+ QPen pen(color_);
+ pen.setWidth(width_);
+ series_->setPen(pen);
+ }
+ if (!chart_->series().contains(series_))
+ chart_->addSeries(series_);
+
+ for (auto* axis : chart_->axes(Qt::Horizontal))
+ series_->attachAxis(axis);
+ for (auto* axis : chart_->axes(Qt::Vertical))
+ series_->attachAxis(axis);
+
+ series_->setVisible(visible());
+}
+
+void SeriesLayer::detach(QGraphicsScene*, QChart* chart) {
+ if (series_ && chart->series().contains(series_))
+ chart->removeSeries(series_);
+ delete series_;
+ series_ = nullptr;
+ chart_ = nullptr;
+}
+
+void SeriesLayer::reposition(QChart*) {
+ // QLineSeries auto-repositions with chart axes — no manual work needed.
+}
+
+void SeriesLayer::update_series_data(const QVector<int64_t>& timestamps, const QVector<double>& values) {
+ if (!series_)
+ return;
+
+ QList<QPointF> points;
+ points.reserve(timestamps.size());
+ for (int i = 0; i < timestamps.size() && i < values.size(); ++i) {
+ if (!std::isnan(values[i]))
+ points.append(QPointF(static_cast<qreal>(timestamps[i]), values[i]));
+ }
+ series_->replace(points);
+ series_->setVisible(visible());
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/SeriesLayer.h b/fincept-qt/src/ui/charts/SeriesLayer.h
new file mode 100644
index 000000000..f8d1b8af8
--- /dev/null
+++ b/fincept-qt/src/ui/charts/SeriesLayer.h
@@ -0,0 +1,43 @@
+#pragma once
+
+#include "ui/charts/OverlayLayer.h"
+
+#include <QColor>
+#include <QPen>
+
+class QLineSeries;
+
+namespace fincept::ui {
+
+class SeriesLayer : public OverlayLayer {
+ Q_OBJECT
+public:
+ explicit SeriesLayer(const QString& id, const QString& name,
+ const QColor& color = QColor("#d97706"),
+ int width = 2, QObject* parent = nullptr);
+
+ QString id() const override { return id_; }
+ QString display_name() const override { return name_; }
+ LayerType type() const override { return LayerType::Series; }
+
+ void set_color(const QColor& c);
+ void set_line_width(int w);
+
+ void attach(QGraphicsScene* scene, QChart* chart) override;
+ void detach(QGraphicsScene* scene, QChart* chart) override;
+ void reposition(QChart* chart) override;
+
+protected:
+ void update_series_data(const QVector<int64_t>& timestamps, const QVector<double>& values);
+ QLineSeries* series() const { return series_; }
+
+private:
+ QString id_;
+ QString name_;
+ QColor color_;
+ int width_;
+ QLineSeries* series_ = nullptr;
+ QChart* chart_ = nullptr;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/BollingerLayer.cpp b/fincept-qt/src/ui/charts/layers/BollingerLayer.cpp
new file mode 100644
index 000000000..401d7a172
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/BollingerLayer.cpp
@@ -0,0 +1,82 @@
+#include "ui/charts/layers/BollingerLayer.h"
+
+#include "ui/charts/ChartIndicators.h"
+
+#include <QChart>
+#include <QLineSeries>
+
+#include <cmath>
+
+namespace fincept::ui {
+
+BollingerLayer::BollingerLayer(int period, double num_std, QObject* parent)
+ : SeriesLayer(QStringLiteral("bb_%1_%2").arg(period).arg(num_std, 0, 'f', 1),
+ QStringLiteral("BB (%1, %2)").arg(period).arg(num_std, 0, 'f', 1),
+ QColor("#ca8a04"), 1, parent),
+ period_(period), num_std_(num_std) {}
+
+void BollingerLayer::compute(const QVector<CandleData>& candles) {
+ QVector<double> closes;
+ QVector<int64_t> timestamps;
+ closes.reserve(candles.size());
+ timestamps.reserve(candles.size());
+
+ for (const auto& c : candles) {
+ closes.append(c.close);
+ timestamps.append(c.timestamp);
+ }
+
+ const auto bb = indicators::bollinger(closes, period_, num_std_);
+ update_series_data(timestamps, bb.middle);
+
+ auto update_band_data = [&](QLineSeries* s, const QVector<double>& vals) {
+ if (!s)
+ return;
+ QList<QPointF> pts;
+ pts.reserve(timestamps.size());
+ for (int i = 0; i < timestamps.size(); ++i) {
+ if (!std::isnan(vals[i]))
+ pts.append(QPointF(static_cast<qreal>(timestamps[i]), vals[i]));
+ }
+ s->replace(pts);
+ };
+
+ update_band_data(upper_, bb.upper);
+ update_band_data(lower_, bb.lower);
+}
+
+void BollingerLayer::attach(QGraphicsScene* scene, QChart* chart) {
+ SeriesLayer::attach(scene, chart);
+ attach_band(upper_, chart);
+ attach_band(lower_, chart);
+}
+
+void BollingerLayer::detach(QGraphicsScene* scene, QChart* chart) {
+ detach_band(upper_, chart);
+ detach_band(lower_, chart);
+ SeriesLayer::detach(scene, chart);
+}
+
+void BollingerLayer::attach_band(QLineSeries*& s, QChart* chart) {
+ if (!s)
+ s = new QLineSeries();
+ QPen pen(QColor("#ca8a04"));
+ pen.setWidth(1);
+ pen.setStyle(Qt::DashLine);
+ s->setPen(pen);
+ if (!chart->series().contains(s))
+ chart->addSeries(s);
+ for (auto* axis : chart->axes(Qt::Horizontal))
+ s->attachAxis(axis);
+ for (auto* axis : chart->axes(Qt::Vertical))
+ s->attachAxis(axis);
+}
+
+void BollingerLayer::detach_band(QLineSeries*& s, QChart* chart) {
+ if (s && chart->series().contains(s))
+ chart->removeSeries(s);
+ delete s;
+ s = nullptr;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/BollingerLayer.h b/fincept-qt/src/ui/charts/layers/BollingerLayer.h
new file mode 100644
index 000000000..b9c13cfca
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/BollingerLayer.h
@@ -0,0 +1,31 @@
+#pragma once
+
+#include "ui/charts/SeriesLayer.h"
+
+class QLineSeries;
+
+namespace fincept::ui {
+
+class BollingerLayer : public SeriesLayer {
+ Q_OBJECT
+public:
+ explicit BollingerLayer(int period = 20, double num_std = 2.0, QObject* parent = nullptr);
+
+ void compute(const QVector<CandleData>& candles) override;
+ void attach(QGraphicsScene* scene, QChart* chart) override;
+ void detach(QGraphicsScene* scene, QChart* chart) override;
+
+ int period() const { return period_; }
+ double num_std() const { return num_std_; }
+
+private:
+ int period_;
+ double num_std_;
+ QLineSeries* upper_ = nullptr;
+ QLineSeries* lower_ = nullptr;
+
+ void attach_band(QLineSeries*& s, QChart* chart);
+ void detach_band(QLineSeries*& s, QChart* chart);
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/EmaLayer.cpp b/fincept-qt/src/ui/charts/layers/EmaLayer.cpp
new file mode 100644
index 000000000..66006a18c
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/EmaLayer.cpp
@@ -0,0 +1,32 @@
+#include "ui/charts/layers/EmaLayer.h"
+
+#include "services/alpha_arena/Indicators.h"
+
+namespace fincept::ui {
+
+EmaLayer::EmaLayer(int period, const QColor& color, QObject* parent)
+ : SeriesLayer(QStringLiteral("ema_%1").arg(period),
+ QStringLiteral("EMA (%1)").arg(period),
+ color, 2, parent),
+ period_(period) {}
+
+void EmaLayer::compute(const QVector<CandleData>& candles) {
+ QVector<double> closes;
+ QVector<int64_t> timestamps;
+ closes.reserve(candles.size());
+ timestamps.reserve(candles.size());
+
+ for (const auto& c : candles) {
+ closes.append(c.close);
+ timestamps.append(c.timestamp);
+ }
+
+ const auto values = fincept::services::alpha_arena::ema(closes, period_);
+ update_series_data(timestamps, values);
+}
+
+void EmaLayer::set_period(int p) {
+ period_ = p;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/EmaLayer.h b/fincept-qt/src/ui/charts/layers/EmaLayer.h
new file mode 100644
index 000000000..0bc46b4d2
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/EmaLayer.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include "ui/charts/SeriesLayer.h"
+
+namespace fincept::ui {
+
+class EmaLayer : public SeriesLayer {
+ Q_OBJECT
+public:
+ explicit EmaLayer(int period = 21, const QColor& color = QColor("#d97706"),
+ QObject* parent = nullptr);
+
+ void compute(const QVector<CandleData>& candles) override;
+
+ int period() const { return period_; }
+ void set_period(int p);
+
+private:
+ int period_;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/PivotLayer.cpp b/fincept-qt/src/ui/charts/layers/PivotLayer.cpp
new file mode 100644
index 000000000..33f529f39
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/PivotLayer.cpp
@@ -0,0 +1,51 @@
+#include "ui/charts/layers/PivotLayer.h"
+
+namespace fincept::ui {
+
+PivotLayer::PivotLayer(PivotType type, QObject* parent)
+ : HorizontalLineLayer("pivot_std", "Pivot Points", parent), type_(type) {}
+
+void PivotLayer::compute(const QVector<CandleData>& candles) {
+ if (candles.size() < 2)
+ return;
+
+ double day_high = 0, day_low = 1e18, day_close = 0;
+ const int64_t last_ts = candles.last().timestamp;
+ const int64_t one_day_ms = 86400000LL;
+
+ for (const auto& c : candles) {
+ if (c.timestamp < last_ts - one_day_ms)
+ continue;
+ if (c.timestamp >= last_ts)
+ break;
+ if (c.high > day_high) day_high = c.high;
+ if (c.low < day_low) day_low = c.low;
+ day_close = c.close;
+ }
+
+ if (day_high <= 0 || day_low >= 1e18)
+ return;
+
+ const auto r = indicators::pivot_points(day_high, day_low, day_close, type_);
+
+ QVector<HorizontalLevel> levels;
+ auto add = [&](double price, const QString& label, const QColor& color) {
+ levels.append({price, label, color, Qt::DotLine});
+ };
+
+ add(r.pp, "PP", QColor("#e5e5e5"));
+ add(r.r1, "R1", QColor("#16a34a"));
+ add(r.r2, "R2", QColor("#16a34a"));
+ add(r.r3, "R3", QColor("#16a34a"));
+ add(r.s1, "S1", QColor("#dc2626"));
+ add(r.s2, "S2", QColor("#dc2626"));
+ add(r.s3, "S3", QColor("#dc2626"));
+
+ set_levels(levels);
+}
+
+void PivotLayer::set_pivot_type(PivotType t) {
+ type_ = t;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/PivotLayer.h b/fincept-qt/src/ui/charts/layers/PivotLayer.h
new file mode 100644
index 000000000..62e3caaed
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/PivotLayer.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include "ui/charts/ChartIndicators.h"
+#include "ui/charts/HorizontalLineLayer.h"
+
+namespace fincept::ui {
+
+class PivotLayer : public HorizontalLineLayer {
+ Q_OBJECT
+public:
+ explicit PivotLayer(PivotType type = PivotType::Standard, QObject* parent = nullptr);
+
+ void compute(const QVector<CandleData>& candles) override;
+
+ PivotType pivot_type() const { return type_; }
+ void set_pivot_type(PivotType t);
+
+private:
+ PivotType type_;
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/SupportResistanceLayer.cpp b/fincept-qt/src/ui/charts/layers/SupportResistanceLayer.cpp
new file mode 100644
index 000000000..313840f50
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/SupportResistanceLayer.cpp
@@ -0,0 +1,72 @@
+#include "ui/charts/layers/SupportResistanceLayer.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace fincept::ui {
+
+SupportResistanceLayer::SupportResistanceLayer(QObject* parent)
+ : HorizontalLineLayer("sr_auto", "Auto S/R", parent) {}
+
+void SupportResistanceLayer::compute(const QVector<CandleData>& candles) {
+ const auto clusters = find_clusters(candles);
+
+ QVector<HorizontalLevel> levels;
+ for (const auto& c : clusters) {
+ HorizontalLevel level;
+ level.price = c.price;
+ level.label = QStringLiteral("S/R %1 (%2x)")
+ .arg(c.price, 0, 'f', 2)
+ .arg(c.touches);
+ level.color = QColor("#808080");
+ level.style = Qt::DashLine;
+ levels.append(level);
+ }
+ set_levels(levels);
+}
+
+QVector<SupportResistanceLayer::Cluster>
+SupportResistanceLayer::find_clusters(const QVector<CandleData>& candles, double tolerance_pct) {
+ if (candles.size() < 5)
+ return {};
+
+ QVector<double> extremes;
+ extremes.reserve(candles.size() * 2);
+ for (const auto& c : candles) {
+ extremes.append(c.high);
+ extremes.append(c.low);
+ }
+
+ std::sort(extremes.begin(), extremes.end());
+
+ QVector<Cluster> clusters;
+ int i = 0;
+ while (i < extremes.size()) {
+ const double ref = extremes[i];
+ const double tolerance = ref * tolerance_pct / 100.0;
+ double sum = 0;
+ int count = 0;
+ int j = i;
+ while (j < extremes.size() && extremes[j] <= ref + tolerance) {
+ sum += extremes[j];
+ ++count;
+ ++j;
+ }
+ if (count >= 3) {
+ const double recency = 1.0;
+ clusters.append({sum / count, count, count * recency});
+ }
+ i = j;
+ }
+
+ std::sort(clusters.begin(), clusters.end(),
+ [](const Cluster& a, const Cluster& b) { return a.weight > b.weight; });
+
+ const int max_levels = 6;
+ if (clusters.size() > max_levels)
+ clusters.resize(max_levels);
+
+ return clusters;
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/SupportResistanceLayer.h b/fincept-qt/src/ui/charts/layers/SupportResistanceLayer.h
new file mode 100644
index 000000000..5470ab397
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/SupportResistanceLayer.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include "ui/charts/HorizontalLineLayer.h"
+
+namespace fincept::ui {
+
+class SupportResistanceLayer : public HorizontalLineLayer {
+ Q_OBJECT
+public:
+ explicit SupportResistanceLayer(QObject* parent = nullptr);
+
+ void compute(const QVector<CandleData>& candles) override;
+
+private:
+ struct Cluster {
+ double price = 0;
+ int touches = 0;
+ double weight = 0;
+ };
+
+ QVector<Cluster> find_clusters(const QVector<CandleData>& candles, double tolerance_pct = 0.3);
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/VwapLayer.cpp b/fincept-qt/src/ui/charts/layers/VwapLayer.cpp
new file mode 100644
index 000000000..548095ea0
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/VwapLayer.cpp
@@ -0,0 +1,104 @@
+#include "ui/charts/layers/VwapLayer.h"
+
+#include "ui/charts/ChartIndicators.h"
+
+#include <QChart>
+#include <QGraphicsScene>
+#include <QLineSeries>
+
+#include <cmath>
+
+namespace fincept::ui {
+
+VwapLayer::VwapLayer(bool show_bands, QObject* parent)
+ : SeriesLayer("vwap", "VWAP", QColor("#2563eb"), 2, parent),
+ show_bands_(show_bands) {}
+
+void VwapLayer::compute(const QVector<CandleData>& candles) {
+ QVector<double> highs, lows, closes, volumes;
+ QVector<int64_t> timestamps;
+ const int n = candles.size();
+ highs.reserve(n);
+ lows.reserve(n);
+ closes.reserve(n);
+ volumes.reserve(n);
+ timestamps.reserve(n);
+
+ for (const auto& c : candles) {
+ highs.append(c.high);
+ lows.append(c.low);
+ closes.append(c.close);
+ volumes.append(c.volume);
+ timestamps.append(c.timestamp);
+ }
+
+ const auto vwap_vals = indicators::vwap(highs, lows, closes, volumes);
+ update_series_data(timestamps, vwap_vals);
+
+ if (show_bands_) {
+ const auto dev = indicators::vwap_std_dev(highs, lows, closes, volumes, vwap_vals);
+ update_band(upper_1_, timestamps, vwap_vals, dev, 1.0);
+ update_band(lower_1_, timestamps, vwap_vals, dev, -1.0);
+ update_band(upper_2_, timestamps, vwap_vals, dev, 2.0);
+ update_band(lower_2_, timestamps, vwap_vals, dev, -2.0);
+ }
+}
+
+void VwapLayer::attach(QGraphicsScene* scene, QChart* chart) {
+ chart_ref_ = chart;
+ SeriesLayer::attach(scene, chart);
+ if (show_bands_) {
+ attach_band(upper_1_, chart, QColor(37, 99, 235, 60), 1);
+ attach_band(lower_1_, chart, QColor(37, 99, 235, 60), 1);
+ attach_band(upper_2_, chart, QColor(37, 99, 235, 30), 1);
+ attach_band(lower_2_, chart, QColor(37, 99, 235, 30), 1);
+ }
+}
+
+void VwapLayer::detach(QGraphicsScene* scene, QChart* chart) {
+ if (show_bands_) {
+ detach_band(upper_1_, chart);
+ detach_band(lower_1_, chart);
+ detach_band(upper_2_, chart);
+ detach_band(lower_2_, chart);
+ }
+ SeriesLayer::detach(scene, chart);
+ chart_ref_ = nullptr;
+}
+
+void VwapLayer::attach_band(QLineSeries*& s, QChart* chart, const QColor& color, int width) {
+ if (!s)
+ s = new QLineSeries();
+ QPen pen(color);
+ pen.setWidth(width);
+ pen.setStyle(Qt::DotLine);
+ s->setPen(pen);
+ if (!chart->series().contains(s))
+ chart->addSeries(s);
+ for (auto* axis : chart->axes(Qt::Horizontal))
+ s->attachAxis(axis);
+ for (auto* axis : chart->axes(Qt::Vertical))
+ s->attachAxis(axis);
+}
+
+void VwapLayer::detach_band(QLineSeries*& s, QChart* chart) {
+ if (s && chart->series().contains(s))
+ chart->removeSeries(s);
+ delete s;
+ s = nullptr;
+}
+
+void VwapLayer::update_band(QLineSeries* s, const QVector<int64_t>& ts,
+ const QVector<double>& base, const QVector<double>& dev, double mult) {
+ if (!s)
+ return;
+ QList<QPointF> pts;
+ pts.reserve(ts.size());
+ for (int i = 0; i < ts.size(); ++i) {
+ if (!std::isnan(base[i]) && !std::isnan(dev[i]))
+ pts.append(QPointF(static_cast<qreal>(ts[i]), base[i] + mult * dev[i]));
+ }
+ s->replace(pts);
+}
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/charts/layers/VwapLayer.h b/fincept-qt/src/ui/charts/layers/VwapLayer.h
new file mode 100644
index 000000000..4c8cc6deb
--- /dev/null
+++ b/fincept-qt/src/ui/charts/layers/VwapLayer.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include "ui/charts/SeriesLayer.h"
+
+class QLineSeries;
+
+namespace fincept::ui {
+
+class VwapLayer : public SeriesLayer {
+ Q_OBJECT
+public:
+ explicit VwapLayer(bool show_bands = true, QObject* parent = nullptr);
+
+ void compute(const QVector<CandleData>& candles) override;
+ void attach(QGraphicsScene* scene, QChart* chart) override;
+ void detach(QGraphicsScene* scene, QChart* chart) override;
+
+private:
+ bool show_bands_;
+ QLineSeries* upper_1_ = nullptr;
+ QLineSeries* lower_1_ = nullptr;
+ QLineSeries* upper_2_ = nullptr;
+ QLineSeries* lower_2_ = nullptr;
+ QChart* chart_ref_ = nullptr;
+
+ void attach_band(QLineSeries*& s, QChart* chart, const QColor& color, int width);
+ void detach_band(QLineSeries*& s, QChart* chart);
+ void update_band(QLineSeries* s, const QVector<int64_t>& ts,
+ const QVector<double>& base, const QVector<double>& dev, double mult);
+};
+
+} // namespace fincept::ui
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp b/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
new file mode 100644
index 000000000..192c6b2f4
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
@@ -0,0 +1,319 @@
+// src/ui/widgets/algo/ConditionBlock.cpp
+#include "ui/widgets/algo/ConditionBlock.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+
+using fincept::services::algo::algo_indicators;
+using fincept::services::algo::algo_operators;
+
+namespace fincept::ui::algo {
+
+ConditionBlock::ConditionBlock(bool is_entry, QWidget* parent)
+ : QFrame(parent), is_entry_(is_entry) {
+ setObjectName(is_entry ? QStringLiteral("conditionBlockEntry") : QStringLiteral("conditionBlockExit"));
+ setFrameShape(QFrame::StyledPanel);
+ build_ui();
+}
+
+void ConditionBlock::build_ui() {
+ auto* main_layout = new QVBoxLayout(this);
+ main_layout->setContentsMargins(8, 6, 8, 6);
+ main_layout->setSpacing(4);
+
+ // Row 1: indicator, operator, value
+ auto* row1 = new QHBoxLayout();
+ row1->setSpacing(6);
+
+ indicator_combo_ = new QComboBox(this);
+ indicator_combo_->setObjectName(QStringLiteral("condBlockIndicator"));
+ indicator_combo_->setMinimumWidth(120);
+ populate_indicators();
+
+ field_combo_ = new QComboBox(this);
+ field_combo_->setObjectName(QStringLiteral("condBlockField"));
+ field_combo_->setMinimumWidth(80);
+
+ operator_combo_ = new QComboBox(this);
+ operator_combo_->setObjectName(QStringLiteral("condBlockOperator"));
+ operator_combo_->setMinimumWidth(100);
+ populate_operators();
+
+ compare_mode_combo_ = new QComboBox(this);
+ compare_mode_combo_->setObjectName(QStringLiteral("condBlockCompareMode"));
+ compare_mode_combo_->addItem(tr("Value"), QStringLiteral("value"));
+ compare_mode_combo_->addItem(tr("Indicator"), QStringLiteral("indicator"));
+
+ value_spin_ = new QDoubleSpinBox(this);
+ value_spin_->setObjectName(QStringLiteral("condBlockValue"));
+ value_spin_->setRange(-999999, 999999);
+ value_spin_->setDecimals(4);
+
+ compare_indicator_combo_ = new QComboBox(this);
+ compare_indicator_combo_->setObjectName(QStringLiteral("condBlockCompareInd"));
+ compare_indicator_combo_->setMinimumWidth(120);
+ populate_indicators();
+ for (int i = 0; i < compare_indicator_combo_->count(); ++i) {
+ if (compare_indicator_combo_->itemData(i).toString().isEmpty())
+ compare_indicator_combo_->model()->setData(
+ compare_indicator_combo_->model()->index(i, 0), false, Qt::UserRole - 1);
+ }
+ compare_indicator_combo_->hide();
+
+ compare_field_combo_ = new QComboBox(this);
+ compare_field_combo_->setObjectName(QStringLiteral("condBlockCompareField"));
+ compare_field_combo_->setMinimumWidth(80);
+ compare_field_combo_->hide();
+
+ remove_btn_ = new QPushButton(this);
+ remove_btn_->setObjectName(QStringLiteral("condBlockRemove"));
+ remove_btn_->setText(QStringLiteral("X"));
+ remove_btn_->setFixedSize(24, 24);
+
+ row1->addWidget(indicator_combo_);
+ row1->addWidget(field_combo_);
+ row1->addWidget(operator_combo_);
+ row1->addWidget(compare_mode_combo_);
+ row1->addWidget(value_spin_);
+ row1->addWidget(compare_indicator_combo_);
+ row1->addWidget(compare_field_combo_);
+ row1->addStretch();
+ row1->addWidget(remove_btn_);
+ main_layout->addLayout(row1);
+
+ // Row 2: parameters (hidden by default for stock attributes)
+ params_container_ = new QWidget(this);
+ params_container_->setObjectName(QStringLiteral("condBlockParams"));
+ auto* params_layout = new QHBoxLayout(params_container_);
+ params_layout->setContentsMargins(0, 0, 0, 0);
+ params_layout->setSpacing(6);
+
+ param1_label_ = new QLabel(this);
+ param1_spin_ = new QDoubleSpinBox(this);
+ param1_spin_->setRange(1, 500);
+ param1_spin_->setDecimals(0);
+ param1_spin_->setValue(14);
+
+ param2_label_ = new QLabel(this);
+ param2_spin_ = new QDoubleSpinBox(this);
+ param2_spin_->setRange(1, 500);
+ param2_spin_->setDecimals(1);
+ param2_spin_->setValue(26);
+
+ param3_label_ = new QLabel(this);
+ param3_spin_ = new QDoubleSpinBox(this);
+ param3_spin_->setRange(0.1, 100);
+ param3_spin_->setDecimals(1);
+ param3_spin_->setValue(9);
+
+ params_layout->addWidget(param1_label_);
+ params_layout->addWidget(param1_spin_);
+ params_layout->addWidget(param2_label_);
+ params_layout->addWidget(param2_spin_);
+ params_layout->addWidget(param3_label_);
+ params_layout->addWidget(param3_spin_);
+ params_layout->addStretch();
+ main_layout->addWidget(params_container_);
+
+ // Connections
+ connect(indicator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, &ConditionBlock::on_indicator_changed);
+ connect(compare_mode_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, &ConditionBlock::on_compare_mode_changed);
+ connect(compare_indicator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, [this](int) {
+ populate_fields(compare_field_combo_,
+ compare_indicator_combo_->currentData().toString());
+ emit changed();
+ });
+ connect(remove_btn_, &QPushButton::clicked, this, &ConditionBlock::remove_requested);
+ connect(value_spin_, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
+ this, [this]() { emit changed(); });
+ connect(operator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, [this]() { emit changed(); });
+
+ on_indicator_changed(0);
+ on_compare_mode_changed(0);
+}
+
+void ConditionBlock::populate_indicators() {
+ QComboBox* combo = (sender() == nullptr) ? indicator_combo_ : compare_indicator_combo_;
+ if (!combo) combo = indicator_combo_;
+
+ auto inds = algo_indicators();
+ QString last_cat;
+ for (const auto& ind : inds) {
+ if (ind.category != last_cat) {
+ last_cat = ind.category;
+ QString label = ind.category.toUpper();
+ combo->addItem(QStringLiteral("-- %1 --").arg(label), QString());
+ }
+ combo->addItem(ind.label, ind.id);
+ }
+ // Also populate compare_indicator_combo_ on init
+ if (combo == indicator_combo_ && compare_indicator_combo_) {
+ compare_indicator_combo_->clear();
+ for (const auto& ind : inds) {
+ if (ind.category != last_cat) {
+ last_cat = ind.category;
+ }
+ compare_indicator_combo_->addItem(ind.label, ind.id);
+ }
+ }
+}
+
+void ConditionBlock::populate_fields(QComboBox* combo, const QString& indicator_id) {
+ combo->clear();
+ auto inds = algo_indicators();
+ for (const auto& ind : inds) {
+ if (ind.id == indicator_id) {
+ for (const auto& f : ind.fields)
+ combo->addItem(f);
+ break;
+ }
+ }
+ if (combo->count() == 0)
+ combo->addItem(QStringLiteral("value"));
+}
+
+void ConditionBlock::populate_operators() {
+ auto ops = algo_operators();
+ QStringList labels = {">", "<", ">=", "<=", "==",
+ "Crosses Above", "Crosses Below", "Rising", "Falling"};
+ for (int i = 0; i < ops.size() && i < labels.size(); ++i)
+ operator_combo_->addItem(labels[i], ops[i]);
+}
+
+void ConditionBlock::on_indicator_changed(int /*index*/) {
+ QString ind_id = indicator_combo_->currentData().toString();
+ if (ind_id.isEmpty()) {
+ indicator_combo_->setCurrentIndex(indicator_combo_->currentIndex() + 1);
+ return;
+ }
+ populate_fields(field_combo_, ind_id);
+ update_param_visibility();
+ emit changed();
+}
+
+void ConditionBlock::on_compare_mode_changed(int index) {
+ bool is_indicator = (index == 1);
+ value_spin_->setVisible(!is_indicator);
+ compare_indicator_combo_->setVisible(is_indicator);
+ compare_field_combo_->setVisible(is_indicator);
+ emit changed();
+}
+
+void ConditionBlock::update_param_visibility() {
+ QString ind_id = indicator_combo_->currentData().toString();
+ auto inds = algo_indicators();
+
+ QStringList param_names;
+ for (const auto& ind : inds) {
+ if (ind.id == ind_id) {
+ param_names = ind.params;
+ break;
+ }
+ }
+
+ param1_label_->setVisible(!param_names.isEmpty());
+ param1_spin_->setVisible(!param_names.isEmpty());
+ param2_label_->setVisible(param_names.size() > 1);
+ param2_spin_->setVisible(param_names.size() > 1);
+ param3_label_->setVisible(param_names.size() > 2);
+ param3_spin_->setVisible(param_names.size() > 2);
+
+ if (param_names.size() > 0) param1_label_->setText(param_names[0] + ":");
+ if (param_names.size() > 1) param2_label_->setText(param_names[1] + ":");
+ if (param_names.size() > 2) param3_label_->setText(param_names[2] + ":");
+
+ params_container_->setVisible(!param_names.isEmpty());
+}
+
+QJsonObject ConditionBlock::to_json() const {
+ QJsonObject obj;
+ obj["indicator"] = indicator_combo_->currentData().toString();
+ obj["field"] = field_combo_->currentText();
+ obj["operator"] = operator_combo_->currentData().toString();
+ obj["compare_mode"] = compare_mode_combo_->currentData().toString();
+ obj["value"] = value_spin_->value();
+
+ // Build params
+ QString ind_id = indicator_combo_->currentData().toString();
+ auto inds = algo_indicators();
+ QJsonObject params;
+ for (const auto& ind : inds) {
+ if (ind.id == ind_id) {
+ if (ind.params.size() > 0) params[ind.params[0]] = static_cast<int>(param1_spin_->value());
+ if (ind.params.size() > 1) params[ind.params[1]] = param2_spin_->value();
+ if (ind.params.size() > 2) params[ind.params[2]] = param3_spin_->value();
+ break;
+ }
+ }
+ obj["params"] = params;
+
+ if (compare_mode_combo_->currentData().toString() == "indicator") {
+ obj["compare_indicator"] = compare_indicator_combo_->currentData().toString();
+ obj["compare_field"] = compare_field_combo_->currentText();
+ obj["compare_params"] = QJsonObject();
+ }
+
+ return obj;
+}
+
+void ConditionBlock::from_json(const QJsonObject& obj) {
+ QString ind = obj.value("indicator").toString();
+ for (int i = 0; i < indicator_combo_->count(); ++i) {
+ if (indicator_combo_->itemData(i).toString() == ind) {
+ indicator_combo_->setCurrentIndex(i);
+ break;
+ }
+ }
+
+ QString field = obj.value("field").toString();
+ int fi = field_combo_->findText(field);
+ if (fi >= 0) field_combo_->setCurrentIndex(fi);
+
+ QString op = obj.value("operator").toString();
+ for (int i = 0; i < operator_combo_->count(); ++i) {
+ if (operator_combo_->itemData(i).toString() == op) {
+ operator_combo_->setCurrentIndex(i);
+ break;
+ }
+ }
+
+ value_spin_->setValue(obj.value("value").toDouble());
+
+ QString cmp = obj.value("compare_mode").toString("value");
+ compare_mode_combo_->setCurrentIndex(cmp == "indicator" ? 1 : 0);
+
+ if (cmp == "indicator") {
+ QString ci = obj.value("compare_indicator").toString();
+ for (int i = 0; i < compare_indicator_combo_->count(); ++i) {
+ if (compare_indicator_combo_->itemData(i).toString() == ci) {
+ compare_indicator_combo_->setCurrentIndex(i);
+ break;
+ }
+ }
+ QString cf = obj.value("compare_field").toString();
+ int cfi = compare_field_combo_->findText(cf);
+ if (cfi >= 0) compare_field_combo_->setCurrentIndex(cfi);
+ }
+
+ // Restore params
+ auto params = obj.value("params").toObject();
+ auto inds = algo_indicators();
+ for (const auto& indef : inds) {
+ if (indef.id == ind) {
+ if (indef.params.size() > 0 && params.contains(indef.params[0]))
+ param1_spin_->setValue(params.value(indef.params[0]).toDouble());
+ if (indef.params.size() > 1 && params.contains(indef.params[1]))
+ param2_spin_->setValue(params.value(indef.params[1]).toDouble());
+ if (indef.params.size() > 2 && params.contains(indef.params[2]))
+ param3_spin_->setValue(params.value(indef.params[2]).toDouble());
+ break;
+ }
+ }
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionBlock.h b/fincept-qt/src/ui/widgets/algo/ConditionBlock.h
new file mode 100644
index 000000000..c73128bbd
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/ConditionBlock.h
@@ -0,0 +1,58 @@
+// src/ui/widgets/algo/ConditionBlock.h
+#pragma once
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QComboBox>
+#include <QDoubleSpinBox>
+#include <QFrame>
+#include <QJsonObject>
+#include <QLabel>
+#include <QPushButton>
+#include <QWidget>
+
+namespace fincept::ui::algo {
+
+class ConditionBlock : public QFrame {
+ Q_OBJECT
+public:
+ explicit ConditionBlock(bool is_entry, QWidget* parent = nullptr);
+
+ QJsonObject to_json() const;
+ void from_json(const QJsonObject& obj);
+
+signals:
+ void remove_requested();
+ void changed();
+
+private:
+ void build_ui();
+ void on_indicator_changed(int index);
+ void on_compare_mode_changed(int index);
+ void populate_indicators();
+ void populate_fields(QComboBox* combo, const QString& indicator);
+ void populate_operators();
+ void update_param_visibility();
+
+ bool is_entry_;
+
+ QComboBox* indicator_combo_ = nullptr;
+ QComboBox* field_combo_ = nullptr;
+ QComboBox* operator_combo_ = nullptr;
+ QComboBox* compare_mode_combo_ = nullptr;
+ QDoubleSpinBox* value_spin_ = nullptr;
+ QComboBox* compare_indicator_combo_ = nullptr;
+ QComboBox* compare_field_combo_ = nullptr;
+
+ // Indicator parameters
+ QWidget* params_container_ = nullptr;
+ QDoubleSpinBox* param1_spin_ = nullptr;
+ QDoubleSpinBox* param2_spin_ = nullptr;
+ QDoubleSpinBox* param3_spin_ = nullptr;
+ QLabel* param1_label_ = nullptr;
+ QLabel* param2_label_ = nullptr;
+ QLabel* param3_label_ = nullptr;
+
+ QPushButton* remove_btn_ = nullptr;
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp b/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp
new file mode 100644
index 000000000..497d23016
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp
@@ -0,0 +1,123 @@
+// src/ui/widgets/algo/ConditionSection.cpp
+#include "ui/widgets/algo/ConditionSection.h"
+
+#include <QLabel>
+#include <QVBoxLayout>
+
+namespace fincept::ui::algo {
+
+ConditionSection::ConditionSection(Type type, QWidget* parent)
+ : QWidget(parent), type_(type) {
+ setObjectName(type == Type::Entry ? QStringLiteral("conditionSectionEntry")
+ : QStringLiteral("conditionSectionExit"));
+
+ auto* main_layout = new QVBoxLayout(this);
+ main_layout->setContentsMargins(0, 0, 0, 0);
+ main_layout->setSpacing(4);
+
+ // Section header
+ auto* header = new QLabel(
+ type == Type::Entry ? tr("ENTRY CONDITIONS") : tr("EXIT CONDITIONS"), this);
+ header->setObjectName(type == Type::Entry ? QStringLiteral("condSectionHeaderEntry")
+ : QStringLiteral("condSectionHeaderExit"));
+ main_layout->addWidget(header);
+
+ // Condition blocks container
+ blocks_layout_ = new QVBoxLayout();
+ blocks_layout_->setSpacing(0);
+ blocks_layout_->setContentsMargins(0, 0, 0, 0);
+ main_layout->addLayout(blocks_layout_);
+
+ // Add button
+ add_btn_ = new QPushButton(tr("+ Add Condition"), this);
+ add_btn_->setObjectName(QStringLiteral("condSectionAddBtn"));
+ connect(add_btn_, &QPushButton::clicked, this, &ConditionSection::add_condition);
+ main_layout->addWidget(add_btn_);
+
+ main_layout->addStretch();
+
+ add_condition();
+}
+
+void ConditionSection::add_condition() {
+ auto* block = new ConditionBlock(type_ == Type::Entry, this);
+ connect(block, &ConditionBlock::remove_requested, this, [this, block]() {
+ on_block_removed(block);
+ });
+ connect(block, &ConditionBlock::changed, this, &ConditionSection::conditions_changed);
+
+ blocks_.append(block);
+ rebuild_layout();
+ emit conditions_changed();
+}
+
+void ConditionSection::on_block_removed(ConditionBlock* block) {
+ int idx = blocks_.indexOf(block);
+ if (idx < 0) return;
+ if (blocks_.size() <= 1) return;
+
+ blocks_.removeAt(idx);
+ block->deleteLater();
+ rebuild_layout();
+ emit conditions_changed();
+}
+
+void ConditionSection::rebuild_layout() {
+ // Clear layout
+ while (blocks_layout_->count() > 0) {
+ auto* item = blocks_layout_->takeAt(0);
+ if (item->widget() && qobject_cast<LogicConnectorWidget*>(item->widget())) {
+ item->widget()->deleteLater();
+ }
+ delete item;
+ }
+ connectors_.clear();
+
+ for (int i = 0; i < blocks_.size(); ++i) {
+ if (i > 0) {
+ auto* connector = new LogicConnectorWidget(this);
+ connectors_.append(connector);
+ connect(connector, &LogicConnectorWidget::logic_changed,
+ this, &ConditionSection::conditions_changed);
+ blocks_layout_->addWidget(connector);
+ }
+ blocks_layout_->addWidget(blocks_[i]);
+ }
+}
+
+QJsonArray ConditionSection::conditions() const {
+ QJsonArray arr;
+ for (const auto* block : blocks_)
+ arr.append(block->to_json());
+ return arr;
+}
+
+QString ConditionSection::combined_logic() const {
+ if (connectors_.isEmpty()) return QStringLiteral("AND");
+ return connectors_.first()->logic();
+}
+
+void ConditionSection::set_conditions(const QJsonArray& conditions, const QString& logic) {
+ clear_all();
+ for (const auto& val : conditions) {
+ auto* block = new ConditionBlock(type_ == Type::Entry, this);
+ block->from_json(val.toObject());
+ connect(block, &ConditionBlock::remove_requested, this, [this, block]() {
+ on_block_removed(block);
+ });
+ connect(block, &ConditionBlock::changed, this, &ConditionSection::conditions_changed);
+ blocks_.append(block);
+ }
+ rebuild_layout();
+ for (auto* c : connectors_)
+ c->set_logic(logic);
+}
+
+void ConditionSection::clear_all() {
+ for (auto* b : blocks_)
+ b->deleteLater();
+ blocks_.clear();
+ rebuild_layout();
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionSection.h b/fincept-qt/src/ui/widgets/algo/ConditionSection.h
new file mode 100644
index 000000000..f0a63fa6d
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/ConditionSection.h
@@ -0,0 +1,42 @@
+// src/ui/widgets/algo/ConditionSection.h
+#pragma once
+#include "ui/widgets/algo/ConditionBlock.h"
+#include "ui/widgets/algo/LogicConnectorWidget.h"
+
+#include <QJsonArray>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QWidget>
+
+namespace fincept::ui::algo {
+
+class ConditionSection : public QWidget {
+ Q_OBJECT
+public:
+ enum class Type { Entry, Exit };
+
+ explicit ConditionSection(Type type, QWidget* parent = nullptr);
+
+ QJsonArray conditions() const;
+ QString combined_logic() const;
+ void set_conditions(const QJsonArray& conditions, const QString& logic);
+ void clear_all();
+
+signals:
+ void conditions_changed();
+
+public slots:
+ void add_condition();
+
+private:
+ void rebuild_layout();
+ void on_block_removed(ConditionBlock* block);
+
+ Type type_;
+ QVector<ConditionBlock*> blocks_;
+ QVector<LogicConnectorWidget*> connectors_;
+ QVBoxLayout* blocks_layout_ = nullptr;
+ QPushButton* add_btn_ = nullptr;
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.cpp b/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.cpp
new file mode 100644
index 000000000..6aa52a7bf
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.cpp
@@ -0,0 +1,79 @@
+// src/ui/widgets/algo/LogicConnectorWidget.cpp
+#include "ui/widgets/algo/LogicConnectorWidget.h"
+
+#include <QHBoxLayout>
+#include <QFrame>
+
+namespace fincept::ui::algo {
+
+LogicConnectorWidget::LogicConnectorWidget(QWidget* parent)
+ : QWidget(parent) {
+ setObjectName(QStringLiteral("logicConnector"));
+ setFixedHeight(28);
+
+ auto* layout = new QHBoxLayout(this);
+ layout->setContentsMargins(20, 0, 20, 0);
+ layout->setSpacing(0);
+
+ auto* left_line = new QFrame(this);
+ left_line->setObjectName(QStringLiteral("logicLine"));
+ left_line->setFrameShape(QFrame::HLine);
+ left_line->setFixedHeight(1);
+
+ and_btn_ = new QPushButton(tr("AND"), this);
+ and_btn_->setObjectName(QStringLiteral("logicBtnAnd"));
+ and_btn_->setCheckable(true);
+ and_btn_->setChecked(true);
+ and_btn_->setFixedSize(48, 22);
+
+ or_btn_ = new QPushButton(tr("OR"), this);
+ or_btn_->setObjectName(QStringLiteral("logicBtnOr"));
+ or_btn_->setCheckable(true);
+ or_btn_->setFixedSize(36, 22);
+
+ auto* right_line = new QFrame(this);
+ right_line->setObjectName(QStringLiteral("logicLine"));
+ right_line->setFrameShape(QFrame::HLine);
+ right_line->setFixedHeight(1);
+
+ layout->addWidget(left_line, 1);
+ layout->addWidget(and_btn_);
+ layout->addWidget(or_btn_);
+ layout->addWidget(right_line, 1);
+
+ connect(and_btn_, &QPushButton::clicked, this, [this]() {
+ and_btn_->setChecked(true);
+ or_btn_->setChecked(false);
+ update_style();
+ emit logic_changed(QStringLiteral("AND"));
+ });
+ connect(or_btn_, &QPushButton::clicked, this, [this]() {
+ or_btn_->setChecked(true);
+ and_btn_->setChecked(false);
+ update_style();
+ emit logic_changed(QStringLiteral("OR"));
+ });
+ update_style();
+}
+
+QString LogicConnectorWidget::logic() const {
+ return and_btn_->isChecked() ? QStringLiteral("AND") : QStringLiteral("OR");
+}
+
+void LogicConnectorWidget::set_logic(const QString& logic) {
+ bool is_and = (logic.toUpper() == "AND");
+ and_btn_->setChecked(is_and);
+ or_btn_->setChecked(!is_and);
+ update_style();
+}
+
+void LogicConnectorWidget::update_style() {
+ and_btn_->setProperty("active", and_btn_->isChecked());
+ or_btn_->setProperty("active", or_btn_->isChecked());
+ and_btn_->style()->unpolish(and_btn_);
+ and_btn_->style()->polish(and_btn_);
+ or_btn_->style()->unpolish(or_btn_);
+ or_btn_->style()->polish(or_btn_);
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.h b/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.h
new file mode 100644
index 000000000..efef6d044
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.h
@@ -0,0 +1,25 @@
+// src/ui/widgets/algo/LogicConnectorWidget.h
+#pragma once
+#include <QPushButton>
+#include <QWidget>
+
+namespace fincept::ui::algo {
+
+class LogicConnectorWidget : public QWidget {
+ Q_OBJECT
+public:
+ explicit LogicConnectorWidget(QWidget* parent = nullptr);
+
+ QString logic() const;
+ void set_logic(const QString& logic);
+
+signals:
+ void logic_changed(const QString& logic);
+
+private:
+ QPushButton* and_btn_ = nullptr;
+ QPushButton* or_btn_ = nullptr;
+ void update_style();
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp
new file mode 100644
index 000000000..76a2cb437
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp
@@ -0,0 +1,108 @@
+// src/ui/widgets/algo/RiskManagementPanel.cpp
+#include "ui/widgets/algo/RiskManagementPanel.h"
+
+#include <QGridLayout>
+#include <QLabel>
+#include <QVBoxLayout>
+
+namespace fincept::ui::algo {
+
+RiskManagementPanel::RiskManagementPanel(QWidget* parent)
+ : QWidget(parent) {
+ setObjectName(QStringLiteral("riskManagementPanel"));
+
+ auto* layout = new QVBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(6);
+
+ auto* header = new QLabel(tr("RISK MANAGEMENT"), this);
+ header->setObjectName(QStringLiteral("riskPanelHeader"));
+ layout->addWidget(header);
+
+ auto* grid = new QGridLayout();
+ grid->setSpacing(6);
+
+ stop_loss_ = create_row(tr("Stop Loss %"), 0, 50, 2.0, 1, this);
+ take_profit_ = create_row(tr("Take Profit %"), 0, 100, 5.0, 1, this);
+ trailing_stop_ = create_row(tr("Trailing Stop %"), 0, 50, 0, 1, this);
+
+ grid->addWidget(stop_loss_.label, 0, 0);
+ grid->addWidget(stop_loss_.slider, 0, 1);
+ grid->addWidget(stop_loss_.spin, 0, 2);
+ grid->addWidget(take_profit_.label, 1, 0);
+ grid->addWidget(take_profit_.slider, 1, 1);
+ grid->addWidget(take_profit_.spin, 1, 2);
+ grid->addWidget(trailing_stop_.label, 2, 0);
+ grid->addWidget(trailing_stop_.slider, 2, 1);
+ grid->addWidget(trailing_stop_.spin, 2, 2);
+
+ // Quantity
+ auto* qty_label = new QLabel(tr("Quantity"), this);
+ quantity_spin_ = new QDoubleSpinBox(this);
+ quantity_spin_->setObjectName(QStringLiteral("riskQtySpin"));
+ quantity_spin_->setRange(1, 100000);
+ quantity_spin_->setDecimals(0);
+ quantity_spin_->setValue(1);
+ grid->addWidget(qty_label, 3, 0);
+ grid->addWidget(quantity_spin_, 3, 1, 1, 2);
+
+ // Max order value
+ auto* mov_label = new QLabel(tr("Max Order Value"), this);
+ max_order_spin_ = new QDoubleSpinBox(this);
+ max_order_spin_->setObjectName(QStringLiteral("riskMaxOrderSpin"));
+ max_order_spin_->setRange(0, 10000000);
+ max_order_spin_->setDecimals(0);
+ max_order_spin_->setValue(0);
+ max_order_spin_->setSpecialValueText(tr("No Limit"));
+ grid->addWidget(mov_label, 4, 0);
+ grid->addWidget(max_order_spin_, 4, 1, 1, 2);
+
+ layout->addLayout(grid);
+
+ connect(quantity_spin_, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
+ this, &RiskManagementPanel::values_changed);
+ connect(max_order_spin_, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
+ this, &RiskManagementPanel::values_changed);
+}
+
+RiskManagementPanel::SliderRow RiskManagementPanel::create_row(
+ const QString& label_text, double min_val, double max_val,
+ double default_val, int decimals, QWidget* parent) {
+
+ SliderRow row;
+ row.label = new QLabel(label_text, parent);
+ row.slider = new QSlider(Qt::Horizontal, parent);
+ row.slider->setRange(static_cast<int>(min_val * 10), static_cast<int>(max_val * 10));
+ row.slider->setValue(static_cast<int>(default_val * 10));
+
+ row.spin = new QDoubleSpinBox(parent);
+ row.spin->setRange(min_val, max_val);
+ row.spin->setDecimals(decimals);
+ row.spin->setValue(default_val);
+
+ connect(row.slider, &QSlider::valueChanged, parent, [row](int val) {
+ row.spin->setValue(val / 10.0);
+ });
+ connect(row.spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
+ parent, [row, this](double val) {
+ row.slider->setValue(static_cast<int>(val * 10));
+ emit values_changed();
+ });
+ return row;
+}
+
+double RiskManagementPanel::stop_loss() const { return stop_loss_.spin->value(); }
+double RiskManagementPanel::take_profit() const { return take_profit_.spin->value(); }
+double RiskManagementPanel::trailing_stop() const { return trailing_stop_.spin->value(); }
+double RiskManagementPanel::quantity() const { return quantity_spin_->value(); }
+double RiskManagementPanel::max_order_value() const { return max_order_spin_->value(); }
+
+void RiskManagementPanel::set_values(double sl, double tp, double ts, double qty, double mov) {
+ stop_loss_.spin->setValue(sl);
+ take_profit_.spin->setValue(tp);
+ trailing_stop_.spin->setValue(ts);
+ quantity_spin_->setValue(qty);
+ max_order_spin_->setValue(mov);
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h
new file mode 100644
index 000000000..71814a171
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h
@@ -0,0 +1,43 @@
+// src/ui/widgets/algo/RiskManagementPanel.h
+#pragma once
+#include <QDoubleSpinBox>
+#include <QLabel>
+#include <QSlider>
+#include <QWidget>
+
+namespace fincept::ui::algo {
+
+class RiskManagementPanel : public QWidget {
+ Q_OBJECT
+public:
+ explicit RiskManagementPanel(QWidget* parent = nullptr);
+
+ double stop_loss() const;
+ double take_profit() const;
+ double trailing_stop() const;
+ double quantity() const;
+ double max_order_value() const;
+
+ void set_values(double sl, double tp, double ts, double qty, double mov);
+
+signals:
+ void values_changed();
+
+private:
+ struct SliderRow {
+ QLabel* label = nullptr;
+ QSlider* slider = nullptr;
+ QDoubleSpinBox* spin = nullptr;
+ };
+
+ SliderRow create_row(const QString& label_text, double min_val, double max_val,
+ double default_val, int decimals, QWidget* parent);
+
+ SliderRow stop_loss_;
+ SliderRow take_profit_;
+ SliderRow trailing_stop_;
+ QDoubleSpinBox* quantity_spin_ = nullptr;
+ QDoubleSpinBox* max_order_spin_ = nullptr;
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp b/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp
new file mode 100644
index 000000000..3780f4b14
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.cpp
@@ -0,0 +1,32 @@
+// src/ui/widgets/algo/SymbolSearchCombo.cpp
+#include "ui/widgets/algo/SymbolSearchCombo.h"
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+namespace fincept::ui::algo {
+
+SymbolSearchCombo::SymbolSearchCombo(QWidget* parent)
+ : QComboBox(parent) {
+ setObjectName(QStringLiteral("symbolSearchCombo"));
+ setEditable(true);
+ setInsertPolicy(QComboBox::NoInsert);
+
+ model_ = new QStringListModel(this);
+ completer_ = new QCompleter(model_, this);
+ completer_->setCaseSensitivity(Qt::CaseInsensitive);
+ completer_->setFilterMode(Qt::MatchContains);
+ setCompleter(completer_);
+
+ QStringList defaults;
+ defaults << services::algo::nifty50_symbols() << services::algo::bank_nifty_symbols();
+ defaults.removeDuplicates();
+ defaults.sort();
+ set_symbols(defaults);
+}
+
+void SymbolSearchCombo::set_symbols(const QStringList& symbols) {
+ clear();
+ addItems(symbols);
+ model_->setStringList(symbols);
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.h b/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.h
new file mode 100644
index 000000000..8ff3be3e2
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/SymbolSearchCombo.h
@@ -0,0 +1,20 @@
+// src/ui/widgets/algo/SymbolSearchCombo.h
+#pragma once
+#include <QComboBox>
+#include <QCompleter>
+#include <QStringListModel>
+
+namespace fincept::ui::algo {
+
+class SymbolSearchCombo : public QComboBox {
+ Q_OBJECT
+public:
+ explicit SymbolSearchCombo(QWidget* parent = nullptr);
+ void set_symbols(const QStringList& symbols);
+
+private:
+ QCompleter* completer_ = nullptr;
+ QStringListModel* model_ = nullptr;
+};
+
+} // namespace fincept::ui::algo