FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
Broker Update
tilakpatel22f002269eec6a
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex c9b6be05f..b3fcd250e 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -682,6 +682,7 @@ set(CORE_SOURCESsrc/core/config/ProfileManager.cppsrc/core/logging/Logger.cppsrc/core/events/EventBus.cpp+ src/core/HealthMonitor.cppsrc/core/layout/LayoutTypes.cppsrc/core/layout/LayoutCatalog.cppsrc/core/layout/LayoutTemplates.cpp@@ -840,6 +841,12 @@ set(STORAGE_SOURCESsrc/storage/sqlite/migrations/v029_secure_credentials.cppsrc/storage/sqlite/migrations/v030_max_tool_rounds.cppsrc/storage/sqlite/migrations/v031_rss_feeds.cpp+ src/storage/sqlite/migrations/v032_pending_orders.cpp+ src/storage/sqlite/migrations/v033_historify.cpp+ src/storage/sqlite/migrations/v034_strategy_portfolio.cpp++ # Historical OHLCV data store (Historify, Phase 3 §13)+ src/storage/HistoricalDataStore.cpp)# Python runner@@ -898,6 +905,7 @@ set(MCP_SOURCESsrc/mcp/tools/PortfolioTools.cppsrc/mcp/tools/CryptoTradingTools.cppsrc/mcp/tools/PaperTradingTools.cpp+ src/mcp/tools/LiveTradingTools.cppsrc/mcp/tools/EdgarTools.cppsrc/mcp/tools/MAAnalyticsTools.cppsrc/mcp/tools/AltInvestmentsTools.cpp@@ -938,6 +946,15 @@ set(TRADING_SOURCESsrc/trading/OrderMatcher.cppsrc/trading/BrokerRegistry.cppsrc/trading/UnifiedTrading.cpp+ src/trading/SmartOrderEngine.cpp+ src/trading/RateLimiter.cpp+ src/trading/ActionCenter.cpp+ src/trading/OptionsStrategyBuilder.cpp+ src/trading/StrategyPortfolio.cpp+ src/trading/WebhookListener.cpp+ src/trading/OrderValidator.cpp+ src/trading/LatencyTracker.cpp+ src/trading/TradingNotificationBridge.cppsrc/trading/AccountManager.cppsrc/trading/AccountDataStream.cppsrc/trading/DataStreamManager.cpp@@ -959,6 +976,17 @@ set(TRADING_SOURCESsrc/trading/websocket/ZerodhaWebSocket.cppsrc/trading/websocket/AngelOneWebSocket.cppsrc/trading/websocket/FyersWebSocket.cpp+ # Phase 2 broker WebSocket adapters (shared base + per-broker)+ src/trading/websocket/BrokerWebSocketBase.cpp+ src/trading/websocket/NorenWebSocket.cpp+ src/trading/websocket/AliceBlueWebSocket.cpp+ src/trading/websocket/ShoonyaWebSocket.cpp+ src/trading/websocket/FivePaisaWebSocket.cpp+ src/trading/websocket/MotilalPoller.cpp+ src/trading/websocket/DhanWebSocket.cpp+ src/trading/websocket/UpstoxWebSocket.cpp+ src/trading/websocket/KotakWebSocket.cpp+ src/trading/websocket/IIFLWebSocket.cpp# Indian brokerssrc/trading/brokers/zerodha/ZerodhaBroker.cppsrc/trading/brokers/zerodha/Totp.cpp@@ -975,6 +1003,10 @@ set(TRADING_SOURCESsrc/trading/brokers/iifl/IIFLBroker.cppsrc/trading/brokers/motilal/MotilalBroker.cppsrc/trading/brokers/shoonya/ShoonyaBroker.cpp+ src/trading/brokers/samco/SamcoBroker.cpp+ src/trading/brokers/flattrade/FlattradeBroker.cpp+ src/trading/brokers/paytm/PaytmBroker.cpp+ src/trading/brokers/tradejini/TradejiniBroker.cpp# Global brokerssrc/trading/brokers/alpaca/AlpacaBroker.cppsrc/trading/brokers/alpaca/AlpacaWebSocket.cpp@@ -1056,6 +1088,7 @@ set(SERVICE_SOURCESsrc/services/geopolitics/GeopoliticsService.cppsrc/services/maritime/MaritimeService.cppsrc/services/maritime/PortsCatalog.cpp+ src/services/maritime/GeocodingService.cppsrc/services/ai_quant_lab/AIQuantLabService.cppsrc/services/backtesting/BacktestingService.cppsrc/services/algo_trading/AlgoTradingService.cpp@@ -1336,6 +1369,7 @@ set(SCREEN_SOURCESsrc/screens/dashboard/widgets/NewsWidget.cppsrc/screens/dashboard/widgets/SectorHeatmapWidget.cppsrc/screens/dashboard/widgets/StockQuoteWidget.cpp+ src/screens/dashboard/widgets/DashboardCandleWidget.cppsrc/screens/dashboard/widgets/WatchlistWidget.cppsrc/screens/dashboard/widgets/PerformanceWidget.cppsrc/screens/dashboard/widgets/MarketSentimentWidget.cpp@@ -1413,6 +1447,8 @@ set(SCREEN_SOURCESsrc/screens/equity_trading/EquityBottomPanel.cppsrc/screens/equity_trading/AccountManagementDialog.cppsrc/screens/equity_trading/BroadcastOrderDialog.cpp+ # Action Center — semi-auto order approval (Phase 3 §2).+ src/screens/action_center/ActionCenterScreen.cpp# DataSourcesScreen split; see DataSourcesScreen.cpp header.src/screens/data_sources/DataSourcesScreen.cppsrc/screens/data_sources/DataSourcesScreen_Layout.cpp@@ -1865,6 +1901,8 @@ set_source_files_properties(src/screens/equity_trading/EquityBottomPanel.cppsrc/screens/equity_trading/AccountManagementDialog.cppsrc/screens/equity_trading/BroadcastOrderDialog.cpp+ # Action Center — semi-auto order approval (Phase 3 §2).+ src/screens/action_center/ActionCenterScreen.cpp# DataSourcesScreen split; see DataSourcesScreen.cpp header.src/screens/data_sources/DataSourcesScreen.cppsrc/screens/data_sources/DataSourcesScreen_Layout.cpp@@ -2194,6 +2232,9 @@ set_source_files_properties(src/storage/sqlite/migrations/v029_secure_credentials.cppsrc/storage/sqlite/migrations/v030_max_tool_rounds.cppsrc/storage/sqlite/migrations/v031_rss_feeds.cpp+ src/storage/sqlite/migrations/v032_pending_orders.cpp+ src/storage/sqlite/migrations/v033_historify.cpp+ src/storage/sqlite/migrations/v034_strategy_portfolio.cpp# Polymarket screen files — each defines static fmt_* helpers in same namespacesrc/screens/polymarket/PolymarketScreen.cppsrc/screens/polymarket/PolymarketCommandBar.cpp@@ -2232,6 +2273,10 @@ set_source_files_properties(src/trading/brokers/iifl/IIFLBroker.cppsrc/trading/brokers/motilal/MotilalBroker.cppsrc/trading/brokers/shoonya/ShoonyaBroker.cpp+ src/trading/brokers/samco/SamcoBroker.cpp+ src/trading/brokers/flattrade/FlattradeBroker.cpp+ src/trading/brokers/paytm/PaytmBroker.cpp+ src/trading/brokers/tradejini/TradejiniBroker.cppsrc/trading/brokers/alpaca/AlpacaBroker.cppsrc/trading/brokers/alpaca/AlpacaWebSocket.cppsrc/trading/brokers/ibkr/IBKRBroker.cpp@@ -2302,6 +2347,7 @@ set_source_files_properties(src/mcp/tools/PortfolioTools.cppsrc/mcp/tools/CryptoTradingTools.cppsrc/mcp/tools/PaperTradingTools.cpp+ src/mcp/tools/LiveTradingTools.cppsrc/mcp/tools/EdgarTools.cppsrc/mcp/tools/MAAnalyticsTools.cppsrc/mcp/tools/AltInvestmentsTools.cpp@@ -2353,6 +2399,10 @@ set_source_files_properties(src/trading/brokers/iifl/IIFLBroker.cppsrc/trading/brokers/motilal/MotilalBroker.cppsrc/trading/brokers/shoonya/ShoonyaBroker.cpp+ src/trading/brokers/samco/SamcoBroker.cpp+ src/trading/brokers/flattrade/FlattradeBroker.cpp+ src/trading/brokers/paytm/PaytmBroker.cpp+ src/trading/brokers/tradejini/TradejiniBroker.cppsrc/trading/brokers/alpaca/AlpacaBroker.cppsrc/trading/brokers/alpaca/AlpacaWebSocket.cppsrc/trading/brokers/ibkr/IBKRBroker.cpp@@ -2361,6 +2411,26 @@ set_source_files_properties(src/trading/websocket/ZerodhaWebSocket.cppsrc/trading/websocket/AngelOneWebSocket.cppsrc/trading/websocket/FyersWebSocket.cpp+ # Phase 2 broker WebSocket adapters — each defines file-scope kWsUrl /+ # anonymous-namespace helpers; keep out of unity to avoid ODR clashes+ src/trading/websocket/BrokerWebSocketBase.cpp+ src/trading/websocket/NorenWebSocket.cpp+ src/trading/websocket/AliceBlueWebSocket.cpp+ src/trading/websocket/ShoonyaWebSocket.cpp+ src/trading/websocket/FivePaisaWebSocket.cpp+ src/trading/websocket/MotilalPoller.cpp+ src/trading/websocket/DhanWebSocket.cpp+ src/trading/websocket/UpstoxWebSocket.cpp+ src/trading/websocket/KotakWebSocket.cpp+ src/trading/websocket/IIFLWebSocket.cpp+ # Phase 3 trading services — file-scope kLog / anonymous-namespace helpers+ src/trading/ActionCenter.cpp+ src/trading/StrategyPortfolio.cpp+ src/trading/OptionsStrategyBuilder.cpp+ src/trading/WebhookListener.cpp+ # Phase 3 storage/core — file-scope kLog / anonymous-namespace helpers+ src/storage/HistoricalDataStore.cpp+ src/core/HealthMonitor.cppPROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE)@@ -2918,17 +2988,24 @@ if(WIN32)endif()# ── Copy Python scripts to build output ──────────────────────────────────────-# POST_BUILD drags the whole scripts/ tree over. Afterwards we prune junk-# that must never ship — backup folders (agents.deleted.*), test caches,-# local SQLite databases — because on macOS anything unexpected in the-# .app bundle makes codesign reject it ("bundle format unrecognized").+# Syncs the scripts/ tree into the build output, then prunes junk that must+# never ship — backup folders (agents.deleted.*), test caches, local SQLite+# databases — because on macOS anything unexpected in the .app bundle makes+# codesign reject it ("bundle format unrecognized").+#+# This is delegated to sync_scripts.cmake, which is STAMP-GUARDED: it skips the+# whole copy+prune when nothing under scripts/ changed since the last sync. The+# previous version did an unconditional copy_directory of 4000+ files on every+# link, taxing every one-line C++ change with a multi-minute scripts re-copy.add_custom_command(TARGET FinceptTerminal POST_BUILD- COMMAND ${CMAKE_COMMAND} -E copy_directory- "${CMAKE_CURRENT_SOURCE_DIR}/scripts"- "$<TARGET_FILE_DIR:FinceptTerminal>/scripts"- COMMAND ${CMAKE_COMMAND} -DSCRIPTS_DIR=$<TARGET_FILE_DIR:FinceptTerminal>/scripts- -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/prune_scripts_junk.cmake"- COMMENT "Copying Python scripts to build output + pruning junk..."+ COMMAND ${CMAKE_COMMAND}+ -DSRC_DIR=${CMAKE_CURRENT_SOURCE_DIR}/scripts+ -DDST_DIR=$<TARGET_FILE_DIR:FinceptTerminal>/scripts+ -DSTAMP_FILE=${CMAKE_CURRENT_BINARY_DIR}/scripts_sync.stamp+ -DPRUNE_SCRIPT=${CMAKE_CURRENT_SOURCE_DIR}/cmake/prune_scripts_junk.cmake+ -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/sync_scripts.cmake"+ COMMENT "Syncing Python scripts to build output (skips when unchanged)..."+ VERBATIM)# ── Copy requirements files to build output ──────────────────────────────────diff --git a/fincept-qt/CMakePresets.json b/fincept-qt/CMakePresets.jsonindex d82bcca64..35461768e 100644--- a/fincept-qt/CMakePresets.json+++ b/fincept-qt/CMakePresets.json@@ -13,6 +13,19 @@}},+ {+ "name": "win-dev",+ "displayName": "Windows Dev (fast incremental)",+ "description": "Dev build — unity build OFF for fast single-file rebuilds (~10s vs ~2min).",+ "inherits": "base",+ "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" },+ "architecture": { "value": "x64", "strategy": "external" },+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "RelWithDebInfo",+ "CMAKE_UNITY_BUILD": "OFF"+ }+ },+{"name": "win-release","displayName": "Windows Release",@@ -50,6 +63,7 @@],"buildPresets": [+ { "name": "win-dev", "configurePreset": "win-dev" },{ "name": "win-release", "configurePreset": "win-release" },{ "name": "linux-release", "configurePreset": "linux-release" },{ "name": "macos-release", "configurePreset": "macos-release" }diff --git a/fincept-qt/cmake/sync_scripts.cmake b/fincept-qt/cmake/sync_scripts.cmakenew file mode 100644index 000000000..64c55bc4d--- /dev/null+++ b/fincept-qt/cmake/sync_scripts.cmake@@ -0,0 +1,74 @@+# Incrementally sync the Python scripts/ tree into the build output, then prune+# junk — but skip the whole job when nothing under scripts/ has changed since+# the last sync. Runs under `cmake -P`, portable across Windows/macOS/Linux.+#+# Why this exists:+# The old POST_BUILD did an unconditional `copy_directory` of 4000+ files+# plus a prune on EVERY link, so a one-line C++ change paid a multi-minute+# tax. copy_directory re-copies the whole tree every time. This guard makes+# the steady state (no script edits) cost a single directory stat instead.+#+# Required defines (passed via -D):+# SRC_DIR — source scripts/ directory+# DST_DIR — destination scripts/ directory (next to the exe)+# STAMP_FILE — path to the sync stamp file+# PRUNE_SCRIPT — path to prune_scripts_junk.cmake++foreach(_var SRC_DIR DST_DIR STAMP_FILE PRUNE_SCRIPT)+ if(NOT DEFINED ${_var})+ message(FATAL_ERROR "sync_scripts.cmake: ${_var} must be set")+ endif()+endforeach()++if(NOT IS_DIRECTORY "${SRC_DIR}")+ message(STATUS "sync_scripts: source '${SRC_DIR}' missing — nothing to do")+ return()+endif()++# Build a cheap change signature from the newest mtime across the source tree.+# GLOB_RECURSE here walks paths only (no content hashing), which is fast even+# for thousands of files. If the destination + stamp already reflect the+# newest source mtime, the tree is unchanged and we can bail immediately.+file(GLOB_RECURSE _src_files LIST_DIRECTORIES false "${SRC_DIR}/*")++set(_newest 0)+foreach(_f IN LISTS _src_files)+ file(TIMESTAMP "${_f}" _ts "%s" UTC)+ if(_ts GREATER _newest)+ set(_newest "${_ts}")+ endif()+endforeach()++set(_prev "")+if(EXISTS "${STAMP_FILE}")+ file(READ "${STAMP_FILE}" _prev)+ string(STRIP "${_prev}" _prev)+endif()++if(_prev STREQUAL "${_newest}" AND IS_DIRECTORY "${DST_DIR}")+ # Unchanged since last sync — skip the expensive copy + prune entirely.+ return()+endif()++message(STATUS "sync_scripts: changes detected — syncing scripts/ to build output")++# copy_directory_if_different (CMake 3.26+) only writes files whose content+# actually differs, so even when this branch runs it avoids needless writes.+execute_process(+ COMMAND "${CMAKE_COMMAND}" -E copy_directory_if_different "${SRC_DIR}" "${DST_DIR}"+ RESULT_VARIABLE _copy_rc+)+if(NOT _copy_rc EQUAL 0)+ message(FATAL_ERROR "sync_scripts: copy_directory_if_different failed (${_copy_rc})")+endif()++# Prune junk that must never ship (see prune_scripts_junk.cmake for rationale).+execute_process(+ COMMAND "${CMAKE_COMMAND}" -DSCRIPTS_DIR=${DST_DIR} -P "${PRUNE_SCRIPT}"+ RESULT_VARIABLE _prune_rc+)+if(NOT _prune_rc EQUAL 0)+ message(FATAL_ERROR "sync_scripts: prune step failed (${_prune_rc})")+endif()++file(WRITE "${STAMP_FILE}" "${_newest}")diff --git a/fincept-qt/scripts/Analytics/options/gex_calculator.py b/fincept-qt/scripts/Analytics/options/gex_calculator.pynew file mode 100644index 000000000..1b1baf589--- /dev/null+++ b/fincept-qt/scripts/Analytics/options/gex_calculator.py@@ -0,0 +1,396 @@+"""+Gamma Exposure (GEX) Calculator+===============================++Computes per-strike Gamma Exposure for an option chain using the Black-76+model (options on futures/forwards — the correct model for Indian F&O and+also used here for equities/indices where the spot is treated as the forward).++ GEX(leg) = gamma * open_interest * lot_size+ Net GEX = Call GEX - Put GEX (per strike)++Ported from OpenAlgo `services/gex_service.py` + the Black-76 greeks math in+`services/option_greeks_service.py`. All broker/Flask/DB fetching is stripped;+the option chain is PASSED IN. Self-contained: numpy + scipy only (with a+pure-python fallback for the normal distribution and IV root-find).++----------------------------------------------------------------------------+I/O CONVENTION (matches scripts/databento_fno_chain.py etc.)+----------------------------------------------------------------------------+Invoked by PythonRunner as:++ python gex_calculator.py compute '<json_args>'+ python gex_calculator.py compute @C:/path/to/spilled_args.json (large args)++argv[1] = command ("compute")+argv[2] = JSON args object (or "@<path>" pointing at a temp file to read+delete)++Result JSON is printed to stdout (single line).++----------------------------------------------------------------------------+INPUT SCHEMA (argv[2] JSON object)+----------------------------------------------------------------------------+{+ "spot": 22500.0, # underlying spot / forward price (required, > 0)+ "expiry": "30JAN26", # optional, echoed back; used for DTE if time_to_expiry absent+ "time_to_expiry": 0.0192, # optional, years to expiry. If absent, derived from+ # "days_to_expiry" or defaults to 7/365.+ "days_to_expiry": 7, # optional alternative to time_to_expiry+ "interest_rate": 0.0, # optional, annualized decimal (e.g. 0.065). Default 0.+ "lot_size": 50, # optional default lot size if a row omits it. Default 1.+ "chain": [ # required: list of per-strike rows+ {+ "strike": 22500,+ "lot_size": 50, # optional per-row override+ "ce_oi": 123400, "ce_iv": 12.5, "ce_ltp": 180.0, # CE open interest / IV(%) / price+ "pe_oi": 98700, "pe_iv": 13.1, "pe_ltp": 165.0 # PE open interest / IV(%) / price+ },+ ...+ ]+}++IV handling per leg, in priority order:+ 1. If "ce_iv"/"pe_iv" given (> 0) it is used directly (interpreted as percent,+ e.g. 12.5 -> 0.125). Pass "iv_is_decimal": true to treat IV as a decimal.+ 2. Else if "ce_ltp"/"pe_ltp" given (> 0) IV is back-solved from price via Black-76.+ 3. Else that leg contributes zero gamma/GEX.++----------------------------------------------------------------------------+OUTPUT SCHEMA+----------------------------------------------------------------------------+{+ "error": false,+ "spot": 22500.0,+ "expiry": "30JAN26",+ "atm_strike": 22500,+ "time_to_expiry": 0.0192,+ "interest_rate": 0.0,+ "chain": [+ {"strike": 22500, "ce_oi": ..., "pe_oi": ...,+ "ce_gamma": 0.000123, "pe_gamma": 0.000119,+ "ce_iv": 0.125, "pe_iv": 0.131,+ "ce_gex": 760.5, "pe_gex": 700.2, "net_gex": 60.3}, ...+ ],+ "totals": {+ "total_ce_oi": ..., "total_pe_oi": ...,+ "total_ce_gex": ..., "total_pe_gex": ..., "total_net_gex": ...,+ "pcr_oi": 0.84+ },+ "oi_walls": {+ "call_wall": 23000, # strike with the largest CE OI (gamma resistance)+ "put_wall": 22000 # strike with the largest PE OI (gamma support)+ },+ "timestamp": 1730000000+}+"""++import json+import math+import os+import sys+from datetime import datetime+from typing import Any, Dict, List, Optional++# numpy/scipy are available in the bundled venv-numpy2. Fall back gracefully so+# the script stays importable/runnable even without scipy.+try:+ from scipy.stats import norm+ from scipy.optimize import brentq++ def _norm_cdf(x: float) -> float:+ return float(norm.cdf(x))++ def _norm_pdf(x: float) -> float:+ return float(norm.pdf(x))++ _HAVE_SCIPY = True+except Exception: # pragma: no cover - exercised only without scipy+ _HAVE_SCIPY = False++ def _norm_cdf(x: float) -> float:+ return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))++ def _norm_pdf(x: float) -> float:+ return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)+++# ── Black-76 core ────────────────────────────────────────────────────────────+# Black-76: options on a forward/future F. d1/d2 omit the (r - q) drift since F+# already embeds carry; the whole price is discounted by exp(-r * T).++def _black76_d1_d2(F: float, K: float, t: float, sigma: float):+ if F <= 0 or K <= 0 or t <= 0 or sigma <= 0:+ return None, None+ vol_sqrt_t = sigma * math.sqrt(t)+ d1 = (math.log(F / K) + 0.5 * sigma * sigma * t) / vol_sqrt_t+ d2 = d1 - vol_sqrt_t+ return d1, d2+++def black76_price(F: float, K: float, t: float, r: float, sigma: float, flag: str) -> float:+ """Black-76 option price. flag 'c' for call, 'p' for put. r is decimal."""+ d1, d2 = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ # Degenerate -> intrinsic (discounted)+ disc = math.exp(-r * max(t, 0.0))+ if flag == "c":+ return disc * max(F - K, 0.0)+ return disc * max(K - F, 0.0)+ disc = math.exp(-r * t)+ if flag == "c":+ return disc * (F * _norm_cdf(d1) - K * _norm_cdf(d2))+ return disc * (K * _norm_cdf(-d2) - F * _norm_cdf(-d1))+++def black76_gamma(F: float, K: float, t: float, r: float, sigma: float) -> float:+ """Black-76 gamma (same for calls and puts). dGamma/dF^2 sensitivity."""+ d1, _ = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ return 0.0+ disc = math.exp(-r * t)+ return disc * _norm_pdf(d1) / (F * sigma * math.sqrt(t))+++def black76_implied_vol(price: float, F: float, K: float, t: float, r: float,+ flag: str) -> Optional[float]:+ """+ Back-solve Black-76 implied volatility from an option price.++ Uses scipy.brentq when available, else a bounded Newton-Raphson with a+ bisection fallback. Returns None if the price is below intrinsic / no root.+ """+ if price is None or price <= 0 or F <= 0 or K <= 0 or t <= 0:+ return None++ disc = math.exp(-r * t)+ intrinsic = disc * (max(F - K, 0.0) if flag == "c" else max(K - F, 0.0))+ # Price at or below discounted intrinsic -> no positive-vol solution.+ if price <= intrinsic + 1e-9:+ return None++ def objective(sigma: float) -> float:+ return black76_price(F, K, t, r, sigma, flag) - price++ lo, hi = 1e-4, 5.0+ f_lo, f_hi = objective(lo), objective(hi)+ if f_lo * f_hi > 0:+ # Expand the upper bound once for very high-vol quotes.+ hi = 10.0+ f_hi = objective(hi)+ if f_lo * f_hi > 0:+ return None++ if _HAVE_SCIPY:+ try:+ return float(brentq(objective, lo, hi, xtol=1e-6, maxiter=100))+ except Exception:+ pass++ # Newton-Raphson seeded at a Brenner-Subrahmanyam-style guess, vega-driven.+ sigma = max(min(math.sqrt(2.0 * math.pi / t) * price / F, hi), lo)+ for _ in range(60):+ d1, _ = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ break+ vega = disc * F * _norm_pdf(d1) * math.sqrt(t)+ diff = black76_price(F, K, t, r, sigma, flag) - price+ if abs(diff) < 1e-7:+ return sigma+ if vega < 1e-12:+ break+ sigma -= diff / vega+ if sigma <= lo or sigma >= hi:+ break+ # Bisection fallback.+ for _ in range(100):+ mid = 0.5 * (lo + hi)+ f_mid = objective(mid)+ if abs(f_mid) < 1e-7:+ return mid+ if f_lo * f_mid < 0:+ hi = mid+ else:+ lo = mid+ f_lo = f_mid+ return 0.5 * (lo + hi)+++# ── Helpers ──────────────────────────────────────────────────────────────────++def _to_float(v, default=0.0) -> float:+ try:+ if v is None:+ return default+ return float(v)+ except (TypeError, ValueError):+ return default+++def _resolve_time_to_expiry(args: Dict[str, Any]) -> float:+ tte = args.get("time_to_expiry")+ if tte is not None:+ tte = _to_float(tte, 0.0)+ if tte > 0:+ return tte+ dte = args.get("days_to_expiry")+ if dte is not None:+ dte = _to_float(dte, 0.0)+ if dte > 0:+ return dte / 365.0+ # Default: ~1 trading week, avoids div-by-zero in the model.+ return 7.0 / 365.0+++def _resolve_leg_iv(iv_raw, ltp, F, K, t, r, flag, iv_is_decimal) -> Optional[float]:+ """Return decimal IV for a leg: from the quoted IV if present, else solved."""+ iv = _to_float(iv_raw, 0.0)+ if iv > 0:+ return iv if iv_is_decimal else iv / 100.0+ ltp = _to_float(ltp, 0.0)+ if ltp > 0:+ return black76_implied_vol(ltp, F, K, t, r, flag)+ return None+++# ── Main computation ─────────────────────────────────────────────────────────++def compute(args: Dict[str, Any]) -> Dict[str, Any]:+ spot = _to_float(args.get("spot"), 0.0)+ if spot <= 0:+ return {"error": True, "message": "spot price is required and must be > 0",+ "timestamp": int(datetime.now().timestamp())}++ chain = args.get("chain")+ if not isinstance(chain, list) or not chain:+ return {"error": True, "message": "chain must be a non-empty list",+ "timestamp": int(datetime.now().timestamp())}++ t = _resolve_time_to_expiry(args)+ r = _to_float(args.get("interest_rate"), 0.0)+ default_lot = int(_to_float(args.get("lot_size"), 1.0)) or 1+ iv_is_decimal = bool(args.get("iv_is_decimal", False))++ out_rows: List[Dict[str, Any]] = []+ atm_strike = None+ atm_dist = None++ for item in chain:+ if not isinstance(item, dict):+ continue+ strike = _to_float(item.get("strike"), 0.0)+ if strike <= 0:+ continue+ lot_size = int(_to_float(item.get("lot_size"), 0.0)) or default_lot++ # Track ATM as the strike nearest spot.+ dist = abs(strike - spot)+ if atm_dist is None or dist < atm_dist:+ atm_dist = dist+ atm_strike = strike++ ce_oi = _to_float(item.get("ce_oi"), 0.0)+ pe_oi = _to_float(item.get("pe_oi"), 0.0)++ ce_iv = _resolve_leg_iv(item.get("ce_iv"), item.get("ce_ltp"), spot, strike, t, r, "c", iv_is_decimal)+ pe_iv = _resolve_leg_iv(item.get("pe_iv"), item.get("pe_ltp"), spot, strike, t, r, "p", iv_is_decimal)++ ce_gamma = black76_gamma(spot, strike, t, r, ce_iv) if ce_iv and ce_iv > 0 else 0.0+ pe_gamma = black76_gamma(spot, strike, t, r, pe_iv) if pe_iv and pe_iv > 0 else 0.0++ ce_gex = ce_gamma * ce_oi * lot_size+ pe_gex = pe_gamma * pe_oi * lot_size+ net_gex = ce_gex - pe_gex++ out_rows.append({+ "strike": strike,+ "lot_size": lot_size,+ "ce_oi": ce_oi,+ "pe_oi": pe_oi,+ "ce_iv": round(ce_iv, 6) if ce_iv else None,+ "pe_iv": round(pe_iv, 6) if pe_iv else None,+ "ce_gamma": round(ce_gamma, 8),+ "pe_gamma": round(pe_gamma, 8),+ "ce_gex": round(ce_gex, 2),+ "pe_gex": round(pe_gex, 2),+ "net_gex": round(net_gex, 2),+ })++ out_rows.sort(key=lambda x: x["strike"])++ total_ce_oi = sum(rw["ce_oi"] for rw in out_rows)+ total_pe_oi = sum(rw["pe_oi"] for rw in out_rows)+ total_ce_gex = sum(rw["ce_gex"] for rw in out_rows)+ total_pe_gex = sum(rw["pe_gex"] for rw in out_rows)+ total_net_gex = sum(rw["net_gex"] for rw in out_rows)+ pcr_oi = round(total_pe_oi / total_ce_oi, 4) if total_ce_oi > 0 else 0.0++ # OI walls: the largest OI strikes act as gamma "magnets"/barriers.+ call_wall = max(out_rows, key=lambda x: x["ce_oi"])["strike"] if out_rows else None+ put_wall = max(out_rows, key=lambda x: x["pe_oi"])["strike"] if out_rows else None++ return {+ "error": False,+ "spot": spot,+ "expiry": args.get("expiry", ""),+ "atm_strike": atm_strike,+ "time_to_expiry": round(t, 6),+ "interest_rate": r,+ "chain": out_rows,+ "totals": {+ "total_ce_oi": total_ce_oi,+ "total_pe_oi": total_pe_oi,+ "total_ce_gex": round(total_ce_gex, 2),+ "total_pe_gex": round(total_pe_gex, 2),+ "total_net_gex": round(total_net_gex, 2),+ "pcr_oi": pcr_oi,+ },+ "oi_walls": {"call_wall": call_wall, "put_wall": put_wall},+ "timestamp": int(datetime.now().timestamp()),+ }+++# ── CLI plumbing (matches Fincept PythonRunner convention) ───────────────────++def resolve_arg(arg: str) -> str:+ """If arg starts with '@', read content from that file path and delete it."""+ if arg and arg.startswith("@"):+ path = arg[1:]+ try:+ with open(path, "r", encoding="utf-8") as f:+ data = f.read()+ try:+ os.remove(path)+ except OSError:+ pass+ return data+ except OSError:+ return arg+ return arg+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": True,+ "message": "Usage: gex_calculator.py <command> <json_args>",+ "commands": ["compute"]}), flush=True)+ sys.exit(1)++ command = sys.argv[1]+ raw = resolve_arg(sys.argv[2]) if len(sys.argv) > 2 else "{}"++ try:+ args = json.loads(raw) if raw else {}+ except json.JSONDecodeError as e:+ print(json.dumps({"error": True, "message": f"Invalid JSON args: {e}"}), flush=True)+ sys.exit(1)++ if command == "compute":+ result = compute(args)+ else:+ result = {"error": True, "message": f"Unknown command: {command}"}++ print(json.dumps(result, default=str), flush=True)+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/Analytics/options/iv_smile.py b/fincept-qt/scripts/Analytics/options/iv_smile.pynew file mode 100644index 000000000..fc07c3860--- /dev/null+++ b/fincept-qt/scripts/Analytics/options/iv_smile.py@@ -0,0 +1,305 @@+"""+Implied Volatility Smile+========================++Computes the implied-volatility curve across strikes for a single expiry using+the Black-76 model, plus ATM IV and the put/call IV skew.++Ported from OpenAlgo `services/iv_smile_service.py` (Black-76 IV from+`services/option_greeks_service.py`). Broker/Flask/DB fetching is stripped; the+option chain is PASSED IN. Self-contained: numpy + scipy only (pure-python+fallback for the normal distribution and IV root-find).++----------------------------------------------------------------------------+I/O CONVENTION (matches scripts/databento_fno_chain.py etc.)+----------------------------------------------------------------------------+ python iv_smile.py compute '<json_args>'+ python iv_smile.py compute @C:/path/to/spilled_args.json++argv[1] = command ("compute"); argv[2] = JSON args (or "@<path>" temp file).+Result JSON printed to stdout.++----------------------------------------------------------------------------+INPUT SCHEMA (argv[2] JSON object)+----------------------------------------------------------------------------+{+ "spot": 22500.0, # required, > 0+ "expiry": "30JAN26", # optional, echoed back+ "time_to_expiry": 0.0192, # optional years; else days_to_expiry; else 7/365+ "days_to_expiry": 7, # optional+ "interest_rate": 0.0, # optional decimal+ "iv_is_decimal": false, # treat quoted IV as decimal (else percent)+ "chain": [+ {"strike": 22500, "ce_iv": 12.5, "pe_iv": 13.1, # quoted IV (percent) OR+ "ce_ltp": 180.0, "pe_ltp": 165.0} # prices to back-solve IV+ ]+}++----------------------------------------------------------------------------+OUTPUT SCHEMA+----------------------------------------------------------------------------+{+ "error": false,+ "spot": 22500.0, "expiry": "30JAN26", "atm_strike": 22500,+ "atm_iv": 0.128, # decimal, avg of ATM CE/PE+ "skew": 0.012, # OTM put IV - OTM call IV (~5% OTM proxy, decimal)+ "chain": [+ {"strike": 22500, "ce_iv": 0.125, "pe_iv": 0.131, "smile_iv": 0.128}, ...+ ],+ "timestamp": 1730000000+}+"smile_iv" is the OTM-convention curve point: PE IV below ATM, CE IV at/above.+"""++import json+import math+import os+import sys+from datetime import datetime+from typing import Any, Dict, List, Optional++try:+ from scipy.stats import norm+ from scipy.optimize import brentq++ def _norm_cdf(x: float) -> float:+ return float(norm.cdf(x))++ def _norm_pdf(x: float) -> float:+ return float(norm.pdf(x))++ _HAVE_SCIPY = True+except Exception: # pragma: no cover+ _HAVE_SCIPY = False++ def _norm_cdf(x: float) -> float:+ return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))++ def _norm_pdf(x: float) -> float:+ return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)+++def _black76_d1_d2(F: float, K: float, t: float, sigma: float):+ if F <= 0 or K <= 0 or t <= 0 or sigma <= 0:+ return None, None+ vol_sqrt_t = sigma * math.sqrt(t)+ d1 = (math.log(F / K) + 0.5 * sigma * sigma * t) / vol_sqrt_t+ return d1, d1 - vol_sqrt_t+++def black76_price(F, K, t, r, sigma, flag) -> float:+ d1, d2 = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ disc = math.exp(-r * max(t, 0.0))+ return disc * (max(F - K, 0.0) if flag == "c" else max(K - F, 0.0))+ disc = math.exp(-r * t)+ if flag == "c":+ return disc * (F * _norm_cdf(d1) - K * _norm_cdf(d2))+ return disc * (K * _norm_cdf(-d2) - F * _norm_cdf(-d1))+++def black76_implied_vol(price, F, K, t, r, flag) -> Optional[float]:+ if price is None or price <= 0 or F <= 0 or K <= 0 or t <= 0:+ return None+ disc = math.exp(-r * t)+ intrinsic = disc * (max(F - K, 0.0) if flag == "c" else max(K - F, 0.0))+ if price <= intrinsic + 1e-9:+ return None++ def objective(sigma):+ return black76_price(F, K, t, r, sigma, flag) - price++ lo, hi = 1e-4, 5.0+ f_lo, f_hi = objective(lo), objective(hi)+ if f_lo * f_hi > 0:+ hi = 10.0+ f_hi = objective(hi)+ if f_lo * f_hi > 0:+ return None++ if _HAVE_SCIPY:+ try:+ return float(brentq(objective, lo, hi, xtol=1e-6, maxiter=100))+ except Exception:+ pass++ sigma = max(min(math.sqrt(2.0 * math.pi / t) * price / F, hi), lo)+ for _ in range(60):+ d1, _ = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ break+ vega = disc * F * _norm_pdf(d1) * math.sqrt(t)+ diff = black76_price(F, K, t, r, sigma, flag) - price+ if abs(diff) < 1e-7:+ return sigma+ if vega < 1e-12:+ break+ sigma -= diff / vega+ if sigma <= lo or sigma >= hi:+ break+ for _ in range(100):+ mid = 0.5 * (lo + hi)+ f_mid = objective(mid)+ if abs(f_mid) < 1e-7:+ return mid+ if f_lo * f_mid < 0:+ hi = mid+ else:+ lo, f_lo = mid, f_mid+ return 0.5 * (lo + hi)+++def _to_float(v, default=0.0) -> float:+ try:+ return default if v is None else float(v)+ except (TypeError, ValueError):+ return default+++def _resolve_time_to_expiry(args: Dict[str, Any]) -> float:+ tte = _to_float(args.get("time_to_expiry"), 0.0)+ if tte > 0:+ return tte+ dte = _to_float(args.get("days_to_expiry"), 0.0)+ if dte > 0:+ return dte / 365.0+ return 7.0 / 365.0+++def _resolve_leg_iv(iv_raw, ltp, F, K, t, r, flag, iv_is_decimal) -> Optional[float]:+ iv = _to_float(iv_raw, 0.0)+ if iv > 0:+ return iv if iv_is_decimal else iv / 100.0+ ltp = _to_float(ltp, 0.0)+ if ltp > 0:+ return black76_implied_vol(ltp, F, K, t, r, flag)+ return None+++def compute(args: Dict[str, Any]) -> Dict[str, Any]:+ spot = _to_float(args.get("spot"), 0.0)+ if spot <= 0:+ return {"error": True, "message": "spot price is required and must be > 0",+ "timestamp": int(datetime.now().timestamp())}+ chain = args.get("chain")+ if not isinstance(chain, list) or not chain:+ return {"error": True, "message": "chain must be a non-empty list",+ "timestamp": int(datetime.now().timestamp())}++ t = _resolve_time_to_expiry(args)+ r = _to_float(args.get("interest_rate"), 0.0)+ iv_is_decimal = bool(args.get("iv_is_decimal", False))++ rows: List[Dict[str, Any]] = []+ atm_strike, atm_dist = None, None+ for item in chain:+ if not isinstance(item, dict):+ continue+ strike = _to_float(item.get("strike"), 0.0)+ if strike <= 0:+ continue+ dist = abs(strike - spot)+ if atm_dist is None or dist < atm_dist:+ atm_dist, atm_strike = dist, strike++ ce_iv = _resolve_leg_iv(item.get("ce_iv"), item.get("ce_ltp"), spot, strike, t, r, "c", iv_is_decimal)+ pe_iv = _resolve_leg_iv(item.get("pe_iv"), item.get("pe_ltp"), spot, strike, t, r, "p", iv_is_decimal)+ rows.append({"strike": strike, "ce_iv": ce_iv, "pe_iv": pe_iv})++ rows.sort(key=lambda x: x["strike"])++ # OTM-convention smile point + rounded output.+ out_rows = []+ atm_ce_iv = atm_pe_iv = None+ for rw in rows:+ strike = rw["strike"]+ ce_iv, pe_iv = rw["ce_iv"], rw["pe_iv"]+ if strike == atm_strike:+ atm_ce_iv, atm_pe_iv = ce_iv, pe_iv+ if strike >= (atm_strike or spot):+ smile_iv = ce_iv if ce_iv else pe_iv+ else:+ smile_iv = pe_iv if pe_iv else ce_iv+ out_rows.append({+ "strike": strike,+ "ce_iv": round(ce_iv, 6) if ce_iv else None,+ "pe_iv": round(pe_iv, 6) if pe_iv else None,+ "smile_iv": round(smile_iv, 6) if smile_iv else None,+ })++ # ATM IV: average of CE & PE at ATM (fall back to whichever exists).+ atm_iv = None+ if atm_ce_iv and atm_pe_iv:+ atm_iv = (atm_ce_iv + atm_pe_iv) / 2.0+ elif atm_ce_iv:+ atm_iv = atm_ce_iv+ elif atm_pe_iv:+ atm_iv = atm_pe_iv++ # Skew: nearest OTM put IV (below ATM) minus nearest OTM call IV (above ATM),+ # probing ~5% away from ATM (25-delta proxy, per OpenAlgo).+ skew = None+ if atm_strike:+ otm = atm_strike * 0.05+ put_iv = None+ for rw in sorted(out_rows, key=lambda x: abs(x["strike"] - (atm_strike - otm))):+ if rw["strike"] < atm_strike and rw["pe_iv"] is not None:+ put_iv = rw["pe_iv"]+ break+ call_iv = None+ for rw in sorted(out_rows, key=lambda x: abs(x["strike"] - (atm_strike + otm))):+ if rw["strike"] > atm_strike and rw["ce_iv"] is not None:+ call_iv = rw["ce_iv"]+ break+ if put_iv is not None and call_iv is not None:+ skew = round(put_iv - call_iv, 6)++ return {+ "error": False,+ "spot": spot,+ "expiry": args.get("expiry", ""),+ "atm_strike": atm_strike,+ "time_to_expiry": round(t, 6),+ "interest_rate": r,+ "atm_iv": round(atm_iv, 6) if atm_iv else None,+ "skew": skew,+ "chain": out_rows,+ "timestamp": int(datetime.now().timestamp()),+ }+++def resolve_arg(arg: str) -> str:+ if arg and arg.startswith("@"):+ path = arg[1:]+ try:+ with open(path, "r", encoding="utf-8") as f:+ data = f.read()+ try:+ os.remove(path)+ except OSError:+ pass+ return data+ except OSError:+ return arg+ return arg+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": True,+ "message": "Usage: iv_smile.py <command> <json_args>",+ "commands": ["compute"]}), flush=True)+ sys.exit(1)+ command = sys.argv[1]+ raw = resolve_arg(sys.argv[2]) if len(sys.argv) > 2 else "{}"+ try:+ args = json.loads(raw) if raw else {}+ except json.JSONDecodeError as e:+ print(json.dumps({"error": True, "message": f"Invalid JSON args: {e}"}), flush=True)+ sys.exit(1)+ result = compute(args) if command == "compute" else {"error": True, "message": f"Unknown command: {command}"}+ print(json.dumps(result, default=str), flush=True)+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/Analytics/options/iv_surface.py b/fincept-qt/scripts/Analytics/options/iv_surface.pynew file mode 100644index 000000000..483e16f83--- /dev/null+++ b/fincept-qt/scripts/Analytics/options/iv_surface.py@@ -0,0 +1,318 @@+"""+Implied Volatility Surface+=========================++Builds a 3D implied-volatility surface across strikes and expiries from a set+of per-expiry option chains, using the Black-76 model. Uses the OTM convention+(CE IV for strikes >= ATM, PE IV below ATM) like OpenAlgo's vol surface.++Ported from OpenAlgo `services/vol_surface_service.py`. Broker/Flask/DB fetching+is stripped; the multi-expiry chains are PASSED IN. Self-contained: numpy ++scipy only (pure-python fallback for normal dist and IV root-find).++----------------------------------------------------------------------------+I/O CONVENTION (matches scripts/databento_fno_chain.py etc.)+----------------------------------------------------------------------------+ python iv_surface.py compute '<json_args>'+ python iv_surface.py compute @C:/path/to/spilled_args.json++argv[1] = command ("compute"); argv[2] = JSON args (or "@<path>" temp file).+Result JSON printed to stdout.++----------------------------------------------------------------------------+INPUT SCHEMA (argv[2] JSON object)+----------------------------------------------------------------------------+{+ "spot": 22500.0, # required underlying spot/forward, > 0+ "interest_rate": 0.0, # optional decimal+ "iv_is_decimal": false, # treat quoted IV as decimal (else percent)+ "expiries": [ # required: one entry per expiry+ {+ "expiry": "30JAN26",+ "time_to_expiry": 0.0192, # optional years; else days_to_expiry; else 7/365+ "days_to_expiry": 7, # optional+ "chain": [+ {"strike": 22500, "ce_iv": 12.5, "pe_iv": 13.1,+ "ce_ltp": 180.0, "pe_ltp": 165.0}, ...+ ]+ }, ...+ ]+}++Surface grid uses the intersection of strikes common to all expiries when there+are >= 3 common strikes; otherwise falls back to the union (gaps = null).++----------------------------------------------------------------------------+OUTPUT SCHEMA+----------------------------------------------------------------------------+{+ "error": false,+ "spot": 22500.0,+ "atm_strike": 22500,+ "strikes": [22000, 22500, 23000, ...], # grid X axis+ "expiries": [{"expiry": "30JAN26", "dte": 7.0, "time_to_expiry": 0.0192}, ...], # Y axis+ "surface": [[0.131, 0.128, 0.127, ...], ...], # surface[expiry_idx][strike_idx] = decimal IV or null+ "points": [{"strike": 22500, "expiry": "30JAN26", "dte": 7.0, "iv": 0.128}, ...],+ "timestamp": 1730000000+}+"""++import json+import math+import os+import sys+from datetime import datetime+from typing import Any, Dict, List, Optional++try:+ from scipy.stats import norm+ from scipy.optimize import brentq++ def _norm_cdf(x: float) -> float:+ return float(norm.cdf(x))++ def _norm_pdf(x: float) -> float:+ return float(norm.pdf(x))++ _HAVE_SCIPY = True+except Exception: # pragma: no cover+ _HAVE_SCIPY = False++ def _norm_cdf(x: float) -> float:+ return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))++ def _norm_pdf(x: float) -> float:+ return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)+++def _black76_d1_d2(F, K, t, sigma):+ if F <= 0 or K <= 0 or t <= 0 or sigma <= 0:+ return None, None+ vst = sigma * math.sqrt(t)+ d1 = (math.log(F / K) + 0.5 * sigma * sigma * t) / vst+ return d1, d1 - vst+++def black76_price(F, K, t, r, sigma, flag) -> float:+ d1, d2 = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ disc = math.exp(-r * max(t, 0.0))+ return disc * (max(F - K, 0.0) if flag == "c" else max(K - F, 0.0))+ disc = math.exp(-r * t)+ if flag == "c":+ return disc * (F * _norm_cdf(d1) - K * _norm_cdf(d2))+ return disc * (K * _norm_cdf(-d2) - F * _norm_cdf(-d1))+++def black76_implied_vol(price, F, K, t, r, flag) -> Optional[float]:+ if price is None or price <= 0 or F <= 0 or K <= 0 or t <= 0:+ return None+ disc = math.exp(-r * t)+ intrinsic = disc * (max(F - K, 0.0) if flag == "c" else max(K - F, 0.0))+ if price <= intrinsic + 1e-9:+ return None++ def objective(sigma):+ return black76_price(F, K, t, r, sigma, flag) - price++ lo, hi = 1e-4, 5.0+ f_lo, f_hi = objective(lo), objective(hi)+ if f_lo * f_hi > 0:+ hi = 10.0+ f_hi = objective(hi)+ if f_lo * f_hi > 0:+ return None+ if _HAVE_SCIPY:+ try:+ return float(brentq(objective, lo, hi, xtol=1e-6, maxiter=100))+ except Exception:+ pass+ sigma = max(min(math.sqrt(2.0 * math.pi / t) * price / F, hi), lo)+ for _ in range(60):+ d1, _ = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ break+ vega = disc * F * _norm_pdf(d1) * math.sqrt(t)+ diff = black76_price(F, K, t, r, sigma, flag) - price+ if abs(diff) < 1e-7:+ return sigma+ if vega < 1e-12:+ break+ sigma -= diff / vega+ if sigma <= lo or sigma >= hi:+ break+ for _ in range(100):+ mid = 0.5 * (lo + hi)+ f_mid = objective(mid)+ if abs(f_mid) < 1e-7:+ return mid+ if f_lo * f_mid < 0:+ hi = mid+ else:+ lo, f_lo = mid, f_mid+ return 0.5 * (lo + hi)+++def _to_float(v, default=0.0) -> float:+ try:+ return default if v is None else float(v)+ except (TypeError, ValueError):+ return default+++def _resolve_tte(entry: Dict[str, Any]) -> float:+ tte = _to_float(entry.get("time_to_expiry"), 0.0)+ if tte > 0:+ return tte+ dte = _to_float(entry.get("days_to_expiry"), 0.0)+ if dte > 0:+ return dte / 365.0+ return 7.0 / 365.0+++def _resolve_leg_iv(iv_raw, ltp, F, K, t, r, flag, iv_is_decimal) -> Optional[float]:+ iv = _to_float(iv_raw, 0.0)+ if iv > 0:+ return iv if iv_is_decimal else iv / 100.0+ ltp = _to_float(ltp, 0.0)+ if ltp > 0:+ return black76_implied_vol(ltp, F, K, t, r, flag)+ return None+++def compute(args: Dict[str, Any]) -> Dict[str, Any]:+ spot = _to_float(args.get("spot"), 0.0)+ if spot <= 0:+ return {"error": True, "message": "spot price is required and must be > 0",+ "timestamp": int(datetime.now().timestamp())}+ expiries = args.get("expiries")+ if not isinstance(expiries, list) or not expiries:+ return {"error": True, "message": "expiries must be a non-empty list",+ "timestamp": int(datetime.now().timestamp())}++ r = _to_float(args.get("interest_rate"), 0.0)+ iv_is_decimal = bool(args.get("iv_is_decimal", False))++ # Per-expiry: parse rows into {strike: (ce_iv, pe_iv)} maps.+ parsed_expiries = []+ for entry in expiries:+ if not isinstance(entry, dict):+ continue+ chain = entry.get("chain")+ if not isinstance(chain, list) or not chain:+ continue+ t = _resolve_tte(entry)+ iv_by_strike: Dict[float, Dict[str, Optional[float]]] = {}+ for item in chain:+ if not isinstance(item, dict):+ continue+ strike = _to_float(item.get("strike"), 0.0)+ if strike <= 0:+ continue+ ce_iv = _resolve_leg_iv(item.get("ce_iv"), item.get("ce_ltp"), spot, strike, t, r, "c", iv_is_decimal)+ pe_iv = _resolve_leg_iv(item.get("pe_iv"), item.get("pe_ltp"), spot, strike, t, r, "p", iv_is_decimal)+ iv_by_strike[strike] = {"ce": ce_iv, "pe": pe_iv}+ if iv_by_strike:+ parsed_expiries.append({+ "expiry": entry.get("expiry", ""),+ "time_to_expiry": t,+ "iv_by_strike": iv_by_strike,+ })++ if not parsed_expiries:+ return {"error": True, "message": "No valid expiry data found",+ "timestamp": int(datetime.now().timestamp())}++ # ATM strike: nearest-to-spot among the first expiry's strikes.+ first_strikes = sorted(parsed_expiries[0]["iv_by_strike"].keys())+ atm_strike = min(first_strikes, key=lambda k: abs(k - spot))++ # Grid X axis: intersection of all expiries' strikes if >= 3, else union.+ strike_sets = [set(e["iv_by_strike"].keys()) for e in parsed_expiries]+ common = set.intersection(*strike_sets)+ if len(common) >= 3:+ grid_strikes = sorted(common)+ else:+ grid_strikes = sorted(set().union(*strike_sets))++ surface: List[List[Optional[float]]] = []+ expiry_info: List[Dict[str, Any]] = []+ points: List[Dict[str, Any]] = []++ for e in parsed_expiries:+ t = e["time_to_expiry"]+ ivmap = e["iv_by_strike"]+ row: List[Optional[float]] = []+ for strike in grid_strikes:+ cell = ivmap.get(strike)+ iv_val = None+ if cell:+ # OTM convention: CE at/above ATM, PE below ATM, with fallback.+ if strike >= atm_strike:+ iv_val = cell["ce"] if cell["ce"] else cell["pe"]+ else:+ iv_val = cell["pe"] if cell["pe"] else cell["ce"]+ iv_round = round(iv_val, 6) if iv_val and iv_val > 0 else None+ row.append(iv_round)+ if iv_round is not None:+ points.append({+ "strike": strike,+ "expiry": e["expiry"],+ "dte": round(t * 365.0, 2),+ "iv": iv_round,+ })+ surface.append(row)+ expiry_info.append({+ "expiry": e["expiry"],+ "dte": round(t * 365.0, 2),+ "time_to_expiry": round(t, 6),+ })++ return {+ "error": False,+ "spot": spot,+ "interest_rate": r,+ "atm_strike": atm_strike,+ "strikes": grid_strikes,+ "expiries": expiry_info,+ "surface": surface,+ "points": points,+ "timestamp": int(datetime.now().timestamp()),+ }+++def resolve_arg(arg: str) -> str:+ if arg and arg.startswith("@"):+ path = arg[1:]+ try:+ with open(path, "r", encoding="utf-8") as f:+ data = f.read()+ try:+ os.remove(path)+ except OSError:+ pass+ return data+ except OSError:+ return arg+ return arg+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": True,+ "message": "Usage: iv_surface.py <command> <json_args>",+ "commands": ["compute"]}), flush=True)+ sys.exit(1)+ command = sys.argv[1]+ raw = resolve_arg(sys.argv[2]) if len(sys.argv) > 2 else "{}"+ try:+ args = json.loads(raw) if raw else {}+ except json.JSONDecodeError as e:+ print(json.dumps({"error": True, "message": f"Invalid JSON args: {e}"}), flush=True)+ sys.exit(1)+ result = compute(args) if command == "compute" else {"error": True, "message": f"Unknown command: {command}"}+ print(json.dumps(result, default=str), flush=True)+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/Analytics/options/oi_tracker.py b/fincept-qt/scripts/Analytics/options/oi_tracker.pynew file mode 100644index 000000000..34e35f948--- /dev/null+++ b/fincept-qt/scripts/Analytics/options/oi_tracker.py@@ -0,0 +1,223 @@+"""+Open Interest Tracker + Max Pain+================================++Aggregates open interest across an option chain (totals, PCR, per-strike PCR)+and computes the Max Pain strike — the strike at which option writers suffer the+least aggregate loss at expiry.++Ported from OpenAlgo `services/oi_tracker_service.py`. Broker/Flask/DB fetching+is stripped; the option chain is PASSED IN. Pure math — no external deps beyond+the standard library (numpy used only if available, not required).++----------------------------------------------------------------------------+I/O CONVENTION (matches scripts/databento_fno_chain.py etc.)+----------------------------------------------------------------------------+ python oi_tracker.py compute '<json_args>'+ python oi_tracker.py compute @C:/path/to/spilled_args.json++argv[1] = command ("compute"); argv[2] = JSON args (or "@<path>" temp file).+Result JSON printed to stdout.++----------------------------------------------------------------------------+INPUT SCHEMA (argv[2] JSON object)+----------------------------------------------------------------------------+{+ "spot": 22500.0, # optional underlying spot (used to mark ATM)+ "expiry": "30JAN26", # optional, echoed back+ "lot_size": 50, # optional default lot size. Default 1.+ "chain": [ # required: per-strike rows+ {"strike": 22500, "lot_size": 50,+ "ce_oi": 123400, "pe_oi": 98700,+ "ce_volume": 45000, "pe_volume": 38000,+ "ce_oi_change": 5000, "pe_oi_change": -2000} # optional OI change fields+ ]+}++----------------------------------------------------------------------------+OUTPUT SCHEMA+----------------------------------------------------------------------------+{+ "error": false,+ "spot": 22500.0, "expiry": "30JAN26", "atm_strike": 22500, "lot_size": 50,+ "totals": {+ "total_ce_oi": ..., "total_pe_oi": ...,+ "total_ce_volume": ..., "total_pe_volume": ...,+ "total_ce_oi_change": ..., "total_pe_oi_change": ...,+ "pcr_oi": 0.84, "pcr_volume": 0.92+ },+ "chain": [+ {"strike": 22500, "ce_oi": ..., "pe_oi": ..., "pcr": 0.80,+ "ce_volume": ..., "pe_volume": ..., "ce_oi_change": ..., "pe_oi_change": ...}, ...+ ],+ "max_pain_strike": 22400,+ "pain_data": [+ {"strike": 22400, "ce_pain": ..., "pe_pain": ..., "total_pain": ...}, ...+ ],+ "support_resistance": {"max_ce_oi_strike": 23000, "max_pe_oi_strike": 22000},+ "timestamp": 1730000000+}+"""++import json+import os+import sys+from datetime import datetime+from typing import Any, Dict, List, Optional+++def _to_float(v, default=0.0) -> float:+ try:+ return default if v is None else float(v)+ except (TypeError, ValueError):+ return default+++def compute(args: Dict[str, Any]) -> Dict[str, Any]:+ chain = args.get("chain")+ if not isinstance(chain, list) or not chain:+ return {"error": True, "message": "chain must be a non-empty list",+ "timestamp": int(datetime.now().timestamp())}++ spot = _to_float(args.get("spot"), 0.0)+ default_lot = int(_to_float(args.get("lot_size"), 1.0)) or 1++ rows: List[Dict[str, Any]] = []+ lot_size_seen: Optional[int] = None+ atm_strike, atm_dist = None, None++ for item in chain:+ if not isinstance(item, dict):+ continue+ strike = _to_float(item.get("strike"), 0.0)+ if strike <= 0:+ continue+ row_lot = int(_to_float(item.get("lot_size"), 0.0))+ if row_lot > 0 and lot_size_seen is None:+ lot_size_seen = row_lot++ if spot > 0:+ dist = abs(strike - spot)+ if atm_dist is None or dist < atm_dist:+ atm_dist, atm_strike = dist, strike++ ce_oi = _to_float(item.get("ce_oi"), 0.0)+ pe_oi = _to_float(item.get("pe_oi"), 0.0)+ rows.append({+ "strike": strike,+ "ce_oi": ce_oi,+ "pe_oi": pe_oi,+ "ce_volume": _to_float(item.get("ce_volume"), 0.0),+ "pe_volume": _to_float(item.get("pe_volume"), 0.0),+ "ce_oi_change": _to_float(item.get("ce_oi_change"), 0.0),+ "pe_oi_change": _to_float(item.get("pe_oi_change"), 0.0),+ "pcr": round(pe_oi / ce_oi, 4) if ce_oi > 0 else 0.0,+ })++ if not rows:+ return {"error": True, "message": "No valid strike rows",+ "timestamp": int(datetime.now().timestamp())}++ rows.sort(key=lambda x: x["strike"])+ lot_size = lot_size_seen or default_lot++ total_ce_oi = sum(rw["ce_oi"] for rw in rows)+ total_pe_oi = sum(rw["pe_oi"] for rw in rows)+ total_ce_vol = sum(rw["ce_volume"] for rw in rows)+ total_pe_vol = sum(rw["pe_volume"] for rw in rows)+ total_ce_oi_chg = sum(rw["ce_oi_change"] for rw in rows)+ total_pe_oi_chg = sum(rw["pe_oi_change"] for rw in rows)++ pcr_oi = round(total_pe_oi / total_ce_oi, 4) if total_ce_oi > 0 else 0.0+ pcr_vol = round(total_pe_vol / total_ce_vol, 4) if total_ce_vol > 0 else 0.0++ # ── Max Pain ──────────────────────────────────────────────────────────────+ # For each candidate settlement strike, sum writer losses:+ # CE writers lose (candidate - strike) * ce_oi for all strikes BELOW candidate+ # PE writers lose (strike - candidate) * pe_oi for all strikes ABOVE candidate+ # Max pain = candidate with minimum total writer loss.+ pain_data: List[Dict[str, Any]] = []+ for candidate in rows:+ c_strike = candidate["strike"]+ ce_pain = 0.0+ pe_pain = 0.0+ for item in rows:+ strike = item["strike"]+ if c_strike > strike and item["ce_oi"] > 0:+ ce_pain += (c_strike - strike) * item["ce_oi"]+ if c_strike < strike and item["pe_oi"] > 0:+ pe_pain += (strike - c_strike) * item["pe_oi"]+ total_pain = ce_pain + pe_pain+ pain_data.append({+ "strike": c_strike,+ "ce_pain": round(ce_pain, 2),+ "pe_pain": round(pe_pain, 2),+ "total_pain": round(total_pain, 2),+ })++ max_pain_entry = min(pain_data, key=lambda x: x["total_pain"])+ max_pain_strike = max_pain_entry["strike"]++ # Support/resistance proxies: highest PE OI = support, highest CE OI = resistance.+ max_ce = max(rows, key=lambda x: x["ce_oi"])["strike"]+ max_pe = max(rows, key=lambda x: x["pe_oi"])["strike"]++ return {+ "error": False,+ "spot": spot,+ "expiry": args.get("expiry", ""),+ "atm_strike": atm_strike,+ "lot_size": lot_size,+ "totals": {+ "total_ce_oi": total_ce_oi,+ "total_pe_oi": total_pe_oi,+ "total_ce_volume": total_ce_vol,+ "total_pe_volume": total_pe_vol,+ "total_ce_oi_change": total_ce_oi_chg,+ "total_pe_oi_change": total_pe_oi_chg,+ "pcr_oi": pcr_oi,+ "pcr_volume": pcr_vol,+ },+ "chain": rows,+ "max_pain_strike": max_pain_strike,+ "pain_data": pain_data,+ "support_resistance": {"max_ce_oi_strike": max_ce, "max_pe_oi_strike": max_pe},+ "timestamp": int(datetime.now().timestamp()),+ }+++def resolve_arg(arg: str) -> str:+ if arg and arg.startswith("@"):+ path = arg[1:]+ try:+ with open(path, "r", encoding="utf-8") as f:+ data = f.read()+ try:+ os.remove(path)+ except OSError:+ pass+ return data+ except OSError:+ return arg+ return arg+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": True,+ "message": "Usage: oi_tracker.py <command> <json_args>",+ "commands": ["compute"]}), flush=True)+ sys.exit(1)+ command = sys.argv[1]+ raw = resolve_arg(sys.argv[2]) if len(sys.argv) > 2 else "{}"+ try:+ args = json.loads(raw) if raw else {}+ except json.JSONDecodeError as e:+ print(json.dumps({"error": True, "message": f"Invalid JSON args: {e}"}), flush=True)+ sys.exit(1)+ result = compute(args) if command == "compute" else {"error": True, "message": f"Unknown command: {command}"}+ print(json.dumps(result, default=str), flush=True)+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/Analytics/options/straddle_simulator.py b/fincept-qt/scripts/Analytics/options/straddle_simulator.pynew file mode 100644index 000000000..ed99c9cd9--- /dev/null+++ b/fincept-qt/scripts/Analytics/options/straddle_simulator.py@@ -0,0 +1,297 @@+"""+Straddle Simulator (Intraday Short ATM Straddle)+===============================================++Simulates an intraday short ATM straddle with automatic strike adjustments:++ 1. ENTRY at the first candle -> sell ATM CE + PE+ 2. ADJUST when spot moves >= N pts -> exit old legs, re-enter at the new ATM+ 3. EXIT at the last candle -> close the position++Produces a cumulative P&L time-series, a trade log, and a summary. Short+straddle P&L per leg = (entry_price - current_price) * quantity (premium decays+in the seller's favour).++Ported from OpenAlgo `services/custom_straddle_service.py`. All broker/Flask/DB+history fetching is stripped; the intraday option prices are PASSED IN. Pure+math — standard library only.++----------------------------------------------------------------------------+I/O CONVENTION (matches scripts/databento_fno_chain.py etc.)+----------------------------------------------------------------------------+ python straddle_simulator.py simulate '<json_args>'+ python straddle_simulator.py simulate @C:/path/to/spilled_args.json++argv[1] = command ("simulate"); argv[2] = JSON args (or "@<path>" temp file).+Result JSON printed to stdout.++----------------------------------------------------------------------------+INPUT SCHEMA (argv[2] JSON object)+----------------------------------------------------------------------------+{+ "underlying": "NIFTY", # optional, echoed back+ "expiry": "30JAN26", # optional, echoed back+ "lot_size": 50, # contract lot size. Default 1.+ "lots": 1, # number of lots. Default 1.+ "adjustment_points": 50, # re-center when |spot - entry_strike| >= this. Default 50.+ "strike_step": 50, # strike grid step used to round ATM. Default: auto from data.+ "candles": [ # required: chronological intraday candles+ {+ "time": 1730000000, # epoch seconds (or any sortable timestamp)+ "spot": 22500.0, # underlying price at this candle+ "options": { # option close prices keyed by strike then leg+ "22500": {"ce": 180.0, "pe": 165.0},+ "22550": {"ce": 150.0, "pe": 190.0}+ }+ }, ...+ ]+}++The ATM strike per candle is the nearest available strike in that candle's+"options" map (or rounded to "strike_step" if provided). A candle is skipped if+its ATM legs have no price.++----------------------------------------------------------------------------+OUTPUT SCHEMA+----------------------------------------------------------------------------+{+ "error": false,+ "underlying": "NIFTY", "expiry": "30JAN26",+ "lot_size": 50, "lots": 1, "quantity": 50, "adjustment_points": 50,+ "pnl_series": [+ {"time": ..., "spot": ..., "atm_strike": ..., "entry_strike": ...,+ "ce_price": ..., "pe_price": ..., "straddle": ..., "pnl": ...}, ...+ ],+ "trades": [+ {"time": ..., "type": "ENTRY|ADJUSTMENT|EXIT", "strike": ..., "spot": ...,+ "ce_price": ..., "pe_price": ..., "straddle": ..., "leg_pnl": ...,+ "cumulative_pnl": ...}, ...+ ],+ "summary": {"total_pnl": ..., "total_adjustments": ..., "max_pnl": ..., "min_pnl": ...},+ "timestamp": 1730000000+}+"""++import json+import os+import sys+from datetime import datetime+from typing import Any, Dict, List, Optional+++def _to_float(v, default=0.0) -> float:+ try:+ return default if v is None else float(v)+ except (TypeError, ValueError):+ return default+++def _leg_price(options: Dict[str, Any], strike: float, leg: str) -> Optional[float]:+ """Look up a leg close price for a strike from a candle's options map."""+ if not isinstance(options, dict):+ return None+ # Strikes may be keyed as "22500" or "22500.0" or numeric — try a few forms.+ for key in (str(int(strike)) if float(strike).is_integer() else None,+ str(strike), repr(strike)):+ if key is None:+ continue+ cell = options.get(key)+ if isinstance(cell, dict):+ val = cell.get(leg)+ if val is not None:+ return _to_float(val, None)+ return None+++def _nearest_atm(options: Dict[str, Any], spot: float, strike_step: float) -> Optional[float]:+ """Nearest strike to spot among the candle's option strikes (with both legs)."""+ if not isinstance(options, dict) or not options:+ return None+ strikes = []+ for k in options.keys():+ s = _to_float(k, None)+ if s is not None and s > 0:+ strikes.append(s)+ if not strikes:+ return None+ if strike_step and strike_step > 0:+ rounded = round(spot / strike_step) * strike_step+ # Snap the rounded value to an actual available strike if present.+ if any(abs(s - rounded) < 1e-6 for s in strikes):+ return rounded+ return min(strikes, key=lambda s: abs(s - spot))+++def simulate(args: Dict[str, Any]) -> Dict[str, Any]:+ candles = args.get("candles")+ if not isinstance(candles, list) or not candles:+ return {"error": True, "message": "candles must be a non-empty list",+ "timestamp": int(datetime.now().timestamp())}++ lot_size = int(_to_float(args.get("lot_size"), 1.0)) or 1+ lots = int(_to_float(args.get("lots"), 1.0)) or 1+ quantity = lot_size * lots+ adjustment_points = _to_float(args.get("adjustment_points"), 50.0)+ strike_step = _to_float(args.get("strike_step"), 0.0)++ # Sort candles chronologically by their timestamp.+ candles = [c for c in candles if isinstance(c, dict)]+ candles.sort(key=lambda c: _to_float(c.get("time"), 0.0))++ pnl_series: List[Dict[str, Any]] = []+ trades: List[Dict[str, Any]] = []++ entry_strike: Optional[float] = None+ entry_ce = 0.0+ entry_pe = 0.0+ realized = 0.0+ adjustments = 0+ last_unrealized = 0.0++ n = len(candles)+ for i, candle in enumerate(candles):+ spot = _to_float(candle.get("spot"), 0.0)+ options = candle.get("options", {})+ ts = candle.get("time")+ if spot <= 0:+ continue+ atm = _nearest_atm(options, spot, strike_step)+ if atm is None:+ continue+ is_last = (i == n - 1)++ # ── ENTRY ──+ if entry_strike is None:+ ce0 = _leg_price(options, atm, "ce")+ pe0 = _leg_price(options, atm, "pe")+ if ce0 is None or pe0 is None:+ continue+ entry_strike, entry_ce, entry_pe = atm, ce0, pe0+ trades.append({+ "time": ts, "type": "ENTRY", "strike": atm, "spot": round(spot, 2),+ "ce_price": round(ce0, 2), "pe_price": round(pe0, 2),+ "straddle": round(ce0 + pe0, 2), "leg_pnl": 0.0,+ "cumulative_pnl": round(realized, 2),+ })+ else:+ # ── ADJUSTMENT ──+ if abs(atm - entry_strike) >= adjustment_points:+ old_ce = _leg_price(options, entry_strike, "ce")+ old_pe = _leg_price(options, entry_strike, "pe")+ new_ce = _leg_price(options, atm, "ce")+ new_pe = _leg_price(options, atm, "pe")+ if None not in (old_ce, old_pe, new_ce, new_pe):+ leg_pnl = ((entry_ce - old_ce) + (entry_pe - old_pe)) * quantity+ realized += leg_pnl+ adjustments += 1+ trades.append({+ "time": ts, "type": "ADJUSTMENT",+ "old_strike": entry_strike, "strike": atm, "spot": round(spot, 2),+ "exit_ce": round(old_ce, 2), "exit_pe": round(old_pe, 2),+ "exit_straddle": round(old_ce + old_pe, 2),+ "ce_price": round(new_ce, 2), "pe_price": round(new_pe, 2),+ "straddle": round(new_ce + new_pe, 2),+ "leg_pnl": round(leg_pnl, 2),+ "cumulative_pnl": round(realized, 2),+ })+ entry_strike, entry_ce, entry_pe = atm, new_ce, new_pe++ # ── Mark-to-market the open position ──+ cur_ce = _leg_price(options, entry_strike, "ce")+ cur_pe = _leg_price(options, entry_strike, "pe")+ if cur_ce is not None and cur_pe is not None:+ unrealized = ((entry_ce - cur_ce) + (entry_pe - cur_pe)) * quantity+ last_unrealized = unrealized+ else:+ unrealized = last_unrealized++ atm_ce = _leg_price(options, atm, "ce") or 0.0+ atm_pe = _leg_price(options, atm, "pe") or 0.0++ pnl_series.append({+ "time": ts, "spot": round(spot, 2), "atm_strike": atm,+ "entry_strike": entry_strike,+ "ce_price": round(atm_ce, 2), "pe_price": round(atm_pe, 2),+ "straddle": round(atm_ce + atm_pe, 2),+ "pnl": round(realized + unrealized, 2),+ "adjustments": adjustments,+ })++ # ── EXIT at last candle ──+ if is_last and entry_strike is not None:+ exit_ce = _leg_price(options, entry_strike, "ce")+ exit_pe = _leg_price(options, entry_strike, "pe")+ if exit_ce is not None and exit_pe is not None:+ leg_pnl = ((entry_ce - exit_ce) + (entry_pe - exit_pe)) * quantity+ else:+ leg_pnl = last_unrealized+ realized += leg_pnl+ trades.append({+ "time": ts, "type": "EXIT", "strike": entry_strike, "spot": round(spot, 2),+ "ce_price": round(exit_ce or 0.0, 2), "pe_price": round(exit_pe or 0.0, 2),+ "straddle": round((exit_ce or 0.0) + (exit_pe or 0.0), 2),+ "leg_pnl": round(leg_pnl, 2),+ "cumulative_pnl": round(realized, 2),+ })++ if not pnl_series:+ return {"error": True, "message": "No simulation data (option prices may be missing)",+ "timestamp": int(datetime.now().timestamp())}++ pnl_values = [p["pnl"] for p in pnl_series]++ return {+ "error": False,+ "underlying": args.get("underlying", ""),+ "expiry": args.get("expiry", ""),+ "lot_size": lot_size,+ "lots": lots,+ "quantity": quantity,+ "adjustment_points": adjustment_points,+ "pnl_series": pnl_series,+ "trades": trades,+ "summary": {+ "total_pnl": round(realized, 2),+ "total_adjustments": adjustments,+ "max_pnl": round(max(pnl_values), 2),+ "min_pnl": round(min(pnl_values), 2),+ },+ "timestamp": int(datetime.now().timestamp()),+ }+++def resolve_arg(arg: str) -> str:+ if arg and arg.startswith("@"):+ path = arg[1:]+ try:+ with open(path, "r", encoding="utf-8") as f:+ data = f.read()+ try:+ os.remove(path)+ except OSError:+ pass+ return data+ except OSError:+ return arg+ return arg+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": True,+ "message": "Usage: straddle_simulator.py <command> <json_args>",+ "commands": ["simulate"]}), flush=True)+ sys.exit(1)+ command = sys.argv[1]+ raw = resolve_arg(sys.argv[2]) if len(sys.argv) > 2 else "{}"+ try:+ args = json.loads(raw) if raw else {}+ except json.JSONDecodeError as e:+ print(json.dumps({"error": True, "message": f"Invalid JSON args: {e}"}), flush=True)+ sys.exit(1)+ result = simulate(args) if command == "simulate" else {"error": True, "message": f"Unknown command: {command}"}+ print(json.dumps(result, default=str), flush=True)+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/Analytics/options/strategy_chart.py b/fincept-qt/scripts/Analytics/options/strategy_chart.pynew file mode 100644index 000000000..e59aded03--- /dev/null+++ b/fincept-qt/scripts/Analytics/options/strategy_chart.py@@ -0,0 +1,334 @@+"""+Strategy Chart (Multi-Leg Payoff + Aggregate Greeks)+===================================================++Computes the payoff curve of a multi-leg options strategy across a range of+underlying prices at expiry, plus the net (position-weighted) Greeks of the+combined position evaluated at the current spot.++Each leg: {strike, type (CE/PE/FUT), side (BUY/SELL), qty, premium, iv}.+Payoff at expiry for a spot S is the sum over legs of:++ option: side_sign * qty * lot_size * (intrinsic(S) - premium)+ future: side_sign * qty * lot_size * (S - entry_price)++where side_sign = +1 for BUY, -1 for SELL and intrinsic is max(S-K,0) for a+call, max(K-S,0) for a put. Net Greeks use Black-76 (options on the forward).++Aligned with the task spec (§12 strategy_chart) and OpenAlgo's+`services/strategy_chart_service.py` leg model (sign by side, OPTION legs drive+premium). Self-contained: numpy + scipy only (pure-python fallback). All+broker/Flask/DB fetching is stripped; legs + spot range are PASSED IN.++----------------------------------------------------------------------------+I/O CONVENTION (matches scripts/databento_fno_chain.py etc.)+----------------------------------------------------------------------------+ python strategy_chart.py compute '<json_args>'+ python strategy_chart.py compute @C:/path/to/spilled_args.json++argv[1] = command ("compute"); argv[2] = JSON args (or "@<path>" temp file).+Result JSON printed to stdout.++----------------------------------------------------------------------------+INPUT SCHEMA (argv[2] JSON object)+----------------------------------------------------------------------------+{+ "spot": 22500.0, # required current spot/forward, > 0+ "lot_size": 50, # default contract lot size. Default 1.+ "interest_rate": 0.0, # optional decimal, for Greeks+ "time_to_expiry": 0.0192, # optional years; else days_to_expiry; else 7/365+ "days_to_expiry": 7, # optional+ "iv_is_decimal": false, # treat leg "iv" as decimal (else percent)+ "spot_range": { # optional payoff X-axis. Defaults to +-15% of spot.+ "min": 20000, "max": 25000, "points": 101+ },+ "legs": [+ {+ "type": "CE", # CE | PE | FUT+ "side": "SELL", # BUY | SELL+ "strike": 22500, # required for CE/PE+ "qty": 1, # number of lots (default 1)+ "premium": 180.0, # entry premium per share (option) / entry price (FUT)+ "iv": 12.5, # optional IV for Greeks (percent unless iv_is_decimal)+ "lot_size": 50 # optional per-leg lot size override+ }, ...+ ]+}++----------------------------------------------------------------------------+OUTPUT SCHEMA+----------------------------------------------------------------------------+{+ "error": false,+ "spot": 22500.0, "time_to_expiry": 0.0192, "interest_rate": 0.0,+ "net_premium": -345.0, # net cashflow at entry (credit positive)+ "tag": "credit", # credit | debit | flat+ "payoff": [{"spot": 20000, "pnl": ...}, ...], # payoff at expiry across spot range+ "breakevens": [22155.0, 22845.0], # spots where payoff crosses zero+ "max_profit": 17250.0, # over the evaluated range (may be capped)+ "max_loss": -50000.0,+ "greeks": { # net position Greeks at current spot+ "delta": -0.02, "gamma": 0.0001, "theta": 35.2, "vega": -120.5, "rho": -4.3+ },+ "legs": [ {echoed normalized leg + per-leg greeks}, ... ],+ "timestamp": 1730000000+}+"""++import json+import math+import os+import sys+from datetime import datetime+from typing import Any, Dict, List, Optional++try:+ from scipy.stats import norm++ def _norm_cdf(x: float) -> float:+ return float(norm.cdf(x))++ def _norm_pdf(x: float) -> float:+ return float(norm.pdf(x))+except Exception: # pragma: no cover+ def _norm_cdf(x: float) -> float:+ return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))++ def _norm_pdf(x: float) -> float:+ return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)+++# ── Black-76 Greeks (options on forward F) ───────────────────────────────────++def _black76_d1_d2(F, K, t, sigma):+ if F <= 0 or K <= 0 or t <= 0 or sigma <= 0:+ return None, None+ vst = sigma * math.sqrt(t)+ d1 = (math.log(F / K) + 0.5 * sigma * sigma * t) / vst+ return d1, d1 - vst+++def black76_greeks(F, K, t, r, sigma, flag) -> Dict[str, float]:+ """Per-share Black-76 greeks. theta per-day, vega/rho per 1% move."""+ zero = {"delta": 0.0, "gamma": 0.0, "theta": 0.0, "vega": 0.0, "rho": 0.0}+ d1, d2 = _black76_d1_d2(F, K, t, sigma)+ if d1 is None:+ return zero+ disc = math.exp(-r * t)+ pdf = _norm_pdf(d1)+ sqrt_t = math.sqrt(t)+ gamma = disc * pdf / (F * sigma * sqrt_t)+ vega = disc * F * pdf * sqrt_t / 100.0 # per 1% vol change+ if flag == "c":+ delta = disc * _norm_cdf(d1)+ theta = (-F * disc * pdf * sigma / (2.0 * sqrt_t)+ - r * K * disc * _norm_cdf(d2)+ + r * F * disc * _norm_cdf(d1)) / 365.0+ rho = -t * disc * (F * _norm_cdf(d1) - K * _norm_cdf(d2)) / 100.0+ else:+ delta = -disc * _norm_cdf(-d1)+ theta = (-F * disc * pdf * sigma / (2.0 * sqrt_t)+ + r * K * disc * _norm_cdf(-d2)+ - r * F * disc * _norm_cdf(-d1)) / 365.0+ rho = -t * disc * (K * _norm_cdf(-d2) - F * _norm_cdf(-d1)) / 100.0+ return {"delta": delta, "gamma": gamma, "theta": theta, "vega": vega, "rho": rho}+++def _to_float(v, default=0.0) -> float:+ try:+ return default if v is None else float(v)+ except (TypeError, ValueError):+ return default+++def _resolve_tte(args: Dict[str, Any]) -> float:+ tte = _to_float(args.get("time_to_expiry"), 0.0)+ if tte > 0:+ return tte+ dte = _to_float(args.get("days_to_expiry"), 0.0)+ if dte > 0:+ return dte / 365.0+ return 7.0 / 365.0+++def _normalize_leg(leg: Dict[str, Any], default_lot: int, iv_is_decimal: bool) -> Optional[Dict[str, Any]]:+ if not isinstance(leg, dict):+ return None+ typ = str(leg.get("type", "")).upper().strip()+ if typ in ("C", "CALL"):+ typ = "CE"+ elif typ in ("P", "PUT"):+ typ = "PE"+ elif typ in ("F", "FUTURE", "FUTURES"):+ typ = "FUT"+ if typ not in ("CE", "PE", "FUT"):+ return None+ side = str(leg.get("side", "")).upper().strip()+ if side not in ("BUY", "SELL"):+ return None+ qty = _to_float(leg.get("qty"), 1.0) or 1.0+ lot_size = int(_to_float(leg.get("lot_size"), 0.0)) or default_lot+ strike = _to_float(leg.get("strike"), 0.0)+ if typ in ("CE", "PE") and strike <= 0:+ return None+ iv_raw = _to_float(leg.get("iv"), 0.0)+ iv = (iv_raw if iv_is_decimal else iv_raw / 100.0) if iv_raw > 0 else 0.0+ return {+ "type": typ,+ "side": side,+ "sign": 1 if side == "BUY" else -1,+ "qty": qty,+ "lot_size": lot_size,+ "strike": strike,+ "premium": _to_float(leg.get("premium"), 0.0),+ "iv": iv,+ }+++def _leg_payoff(leg: Dict[str, Any], S: float) -> float:+ """P&L of one leg at expiry for underlying price S (total, incl. lot * qty)."""+ contracts = leg["qty"] * leg["lot_size"]+ sign = leg["sign"]+ if leg["type"] == "CE":+ intrinsic = max(S - leg["strike"], 0.0)+ return sign * contracts * (intrinsic - leg["premium"])+ if leg["type"] == "PE":+ intrinsic = max(leg["strike"] - S, 0.0)+ return sign * contracts * (intrinsic - leg["premium"])+ # FUT: linear P&L from entry price (premium field holds entry price).+ return sign * contracts * (S - leg["premium"])+++def compute(args: Dict[str, Any]) -> Dict[str, Any]:+ spot = _to_float(args.get("spot"), 0.0)+ if spot <= 0:+ return {"error": True, "message": "spot price is required and must be > 0",+ "timestamp": int(datetime.now().timestamp())}+ raw_legs = args.get("legs")+ if not isinstance(raw_legs, list) or not raw_legs:+ return {"error": True, "message": "legs must be a non-empty list",+ "timestamp": int(datetime.now().timestamp())}++ default_lot = int(_to_float(args.get("lot_size"), 1.0)) or 1+ iv_is_decimal = bool(args.get("iv_is_decimal", False))+ t = _resolve_tte(args)+ r = _to_float(args.get("interest_rate"), 0.0)++ legs = [nl for nl in (_normalize_leg(l, default_lot, iv_is_decimal) for l in raw_legs) if nl]+ if not legs:+ return {"error": True, "message": "No valid legs provided",+ "timestamp": int(datetime.now().timestamp())}++ # Spot range for the payoff X axis.+ rng = args.get("spot_range") or {}+ s_min = _to_float(rng.get("min"), 0.0)+ s_max = _to_float(rng.get("max"), 0.0)+ points = int(_to_float(rng.get("points"), 101.0)) or 101+ points = max(3, min(points, 2001))+ if s_min <= 0 or s_max <= 0 or s_max <= s_min:+ s_min = spot * 0.85+ s_max = spot * 1.15++ step = (s_max - s_min) / (points - 1)+ payoff: List[Dict[str, Any]] = []+ prev_s = None+ prev_pnl = None+ breakevens: List[float] = []+ for i in range(points):+ S = s_min + i * step+ pnl = sum(_leg_payoff(leg, S) for leg in legs)+ payoff.append({"spot": round(S, 2), "pnl": round(pnl, 2)})+ # Linear-interpolate zero crossings for breakeven points.+ if prev_pnl is not None and ((prev_pnl <= 0 <= pnl) or (prev_pnl >= 0 >= pnl)) and pnl != prev_pnl:+ be = prev_s + (0 - prev_pnl) * (S - prev_s) / (pnl - prev_pnl)+ breakevens.append(round(be, 2))+ prev_s, prev_pnl = S, pnl++ pnls = [p["pnl"] for p in payoff]+ max_profit = max(pnls)+ max_loss = min(pnls)++ # Net (position) Greeks at the current spot, position-weighted.+ net_greeks = {"delta": 0.0, "gamma": 0.0, "theta": 0.0, "vega": 0.0, "rho": 0.0}+ out_legs: List[Dict[str, Any]] = []+ for leg in legs:+ contracts = leg["qty"] * leg["lot_size"]+ leg_greeks = {"delta": 0.0, "gamma": 0.0, "theta": 0.0, "vega": 0.0, "rho": 0.0}+ if leg["type"] == "FUT":+ # Future: delta 1 per share, no convexity/decay.+ leg_greeks["delta"] = 1.0+ elif leg["iv"] > 0:+ flag = "c" if leg["type"] == "CE" else "p"+ leg_greeks = black76_greeks(spot, leg["strike"], t, r, leg["iv"], flag)+ for g in net_greeks:+ net_greeks[g] += leg["sign"] * contracts * leg_greeks[g]+ out_legs.append({+ "type": leg["type"], "side": leg["side"], "strike": leg["strike"],+ "qty": leg["qty"], "lot_size": leg["lot_size"], "premium": leg["premium"],+ "iv": round(leg["iv"], 6) if leg["iv"] else None,+ "greeks": {k: round(v, 8) for k, v in leg_greeks.items()},+ })++ # Net entry premium: credit (received) positive, debit (paid) negative.+ # For SELL we receive premium (+), for BUY we pay (-). FUT premia excluded.+ net_premium = 0.0+ for leg in legs:+ if leg["type"] == "FUT":+ continue+ contracts = leg["qty"] * leg["lot_size"]+ # SELL -> +premium received, BUY -> -premium paid.+ net_premium += (-leg["sign"]) * contracts * leg["premium"]+ tag = "credit" if net_premium > 0 else ("debit" if net_premium < 0 else "flat")++ return {+ "error": False,+ "spot": spot,+ "time_to_expiry": round(t, 6),+ "interest_rate": r,+ "net_premium": round(net_premium, 2),+ "tag": tag,+ "payoff": payoff,+ "breakevens": breakevens,+ "max_profit": round(max_profit, 2),+ "max_loss": round(max_loss, 2),+ "greeks": {k: round(v, 6) for k, v in net_greeks.items()},+ "legs": out_legs,+ "timestamp": int(datetime.now().timestamp()),+ }+++def resolve_arg(arg: str) -> str:+ if arg and arg.startswith("@"):+ path = arg[1:]+ try:+ with open(path, "r", encoding="utf-8") as f:+ data = f.read()+ try:+ os.remove(path)+ except OSError:+ pass+ return data+ except OSError:+ return arg+ return arg+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": True,+ "message": "Usage: strategy_chart.py <command> <json_args>",+ "commands": ["compute"]}), flush=True)+ sys.exit(1)+ command = sys.argv[1]+ raw = resolve_arg(sys.argv[2]) if len(sys.argv) > 2 else "{}"+ try:+ args = json.loads(raw) if raw else {}+ except json.JSONDecodeError as e:+ print(json.dumps({"error": True, "message": f"Invalid JSON args: {e}"}), flush=True)+ sys.exit(1)+ result = compute(args) if command == "compute" else {"error": True, "message": f"Unknown command: {command}"}+ print(json.dumps(result, default=str), flush=True)+++if __name__ == "__main__":+ main()diff --git a/fincept-qt/scripts/agents/finagent_core/main.py b/fincept-qt/scripts/agents/finagent_core/main.pyindex 355cf5cbc..208dc1e86 100644--- a/fincept-qt/scripts/agents/finagent_core/main.py+++ b/fincept-qt/scripts/agents/finagent_core/main.py@@ -9,6 +9,7 @@ Performance notes:- Uses optimized agent loader to avoid slow file scanning"""+import osimport sysimport jsonimport logging@@ -174,6 +175,14 @@ def main(args=None):return json.dumps({"success": False, "error": "No payload provided"})else:payload_str = args[0]+ if payload_str.startswith("@"):+ fpath = payload_str[1:]+ with open(fpath, "r", encoding="utf-8") as f:+ payload_str = f.read()+ try:+ os.remove(fpath)+ except OSError:+ passpayload = json.loads(payload_str)action = payload.get("action")diff --git a/fincept-qt/src/app/DockScreenRouter.cpp b/fincept-qt/src/app/DockScreenRouter.cppindex 7993d126b..d57f4299b 100644--- a/fincept-qt/src/app/DockScreenRouter.cpp+++ b/fincept-qt/src/app/DockScreenRouter.cpp@@ -56,6 +56,7 @@ QString DockScreenRouter::title_for_id(const QString& id) {{"crypto_trading", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Crypto Trading")},{"equity_trading", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Equity Trading")},{"algo_trading", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Algo Trading")},+ {"action_center", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Action Center")},{"backtesting", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Backtesting")},{"portfolio", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Portfolio")},{"watchlist", QT_TRANSLATE_NOOP("fincept::DockScreenRouter", "Watchlist")},diff --git a/fincept-qt/src/app/WindowFrame_Setup.cpp b/fincept-qt/src/app/WindowFrame_Setup.cppindex a688c74bb..a267d609f 100644--- a/fincept-qt/src/app/WindowFrame_Setup.cpp+++ b/fincept-qt/src/app/WindowFrame_Setup.cpp@@ -21,6 +21,7 @@#include "core/session/SessionManager.h"#include "screens/common/ComingSoonScreen.h"#include "screens/about/AboutScreen.h"+#include "screens/action_center/ActionCenterScreen.h"#include "screens/agent_config/AgentConfigScreen.h"#include "screens/ai_chat/AiChatScreen.h"#include "screens/ai_quant_lab/AIQuantLabScreen.h"@@ -262,6 +263,7 @@ void WindowFrame::setup_dock_screens() {dock_router_->register_factory("asia_markets", []() { return new screens::AsiaMarketsScreen; });dock_router_->register_factory("relationship_map", []() { return new screens::RelationshipMapScreen; });dock_router_->register_factory("equity_trading", []() { return new screens::EquityTradingScreen; });+ dock_router_->register_factory("action_center", []() { return new screens::ActionCenterScreen; });dock_router_->register_factory("alpha_arena", []() { return new screens::AlphaArenaScreen; });dock_router_->register_factory("polymarket", []() { return new screens::PolymarketScreen; });dock_router_->register_factory("derivatives", []() { return new screens::DerivativesScreen; });diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cppindex c94261a72..6d3a051d1 100644--- a/fincept-qt/src/app/main.cpp+++ b/fincept-qt/src/app/main.cpp@@ -634,6 +634,9 @@ int main(int argc, char* argv[]) {fincept::register_migration_v029();fincept::register_migration_v030();fincept::register_migration_v031();+ fincept::register_migration_v032();+ fincept::register_migration_v033();+ fincept::register_migration_v034();// Open main databaseQString db_path = fincept::AppPaths::data() + "/fincept.db";diff --git a/fincept-qt/src/core/HealthMonitor.cpp b/fincept-qt/src/core/HealthMonitor.cppnew file mode 100644index 000000000..5cd377ed9--- /dev/null+++ b/fincept-qt/src/core/HealthMonitor.cpp@@ -0,0 +1,233 @@+#include "core/HealthMonitor.h"++#include "core/logging/Logger.h"+#include "datahub/DataHub.h"+#include "python/PythonRunner.h"+#include "trading/AccountManager.h"+#include "trading/BrokerAccount.h"+#include "trading/DataStreamManager.h"++#include <QJsonArray>++namespace fincept {++namespace {+constexpr const char* HM_TAG = "HealthMonitor";+} // namespace++// ── HealthStatus ─────────────────────────────────────────────────────────────++bool HealthStatus::all_ok() const {+ for (const auto& c : checks) {+ if (!c.ok)+ return false;+ }+ return true;+}++QJsonObject HealthStatus::to_json() const {+ QJsonArray arr;+ for (const auto& c : checks) {+ arr.append(QJsonObject{+ {"name", c.name},+ {"ok", c.ok},+ {"detail", c.detail},+ });+ }+ return QJsonObject{+ {"all_ok", all_ok()},+ {"checks", arr},+ };+}++// ── HealthMonitor ────────────────────────────────────────────────────────────++HealthMonitor& HealthMonitor::instance() {+ static HealthMonitor inst;+ return inst;+}++HealthStatus HealthMonitor::check() const {+ HealthStatus status;+ status.checks.append(check_broker_connections());+ status.checks.append(check_websocket_streams());+ status.checks.append(check_python_pool());+ status.checks.append(check_datahub());+ LOG_DEBUG(HM_TAG, QString("Health snapshot: all_ok=%1 (%2 checks)")+ .arg(status.all_ok() ? "true" : "false")+ .arg(status.checks.size()));+ return status;+}++// Broker connection states across all accounts. Healthy if every active live+// account is Connected and none are in TokenExpired / Error. Paper-only or+// inactive accounts are ignored (they have no live connection to assess).+HealthStatus::Check HealthMonitor::check_broker_connections() const {+ HealthStatus::Check c;+ c.name = "broker_connections";+ try {+ auto& am = trading::AccountManager::instance();+ const auto accounts = am.list_accounts();++ int considered = 0;+ int connected = 0;+ int token_expired = 0;+ int errored = 0;+ QStringList problems;++ for (const auto& acct : accounts) {+ // Only live accounts hold a real broker connection. Paper-mode and+ // deactivated accounts are out of scope for connection health.+ if (!acct.is_active || acct.trading_mode != "live")+ continue;+ ++considered;+ const auto state = am.connection_state(acct.account_id);+ switch (state) {+ case trading::ConnectionState::Connected:+ ++connected;+ break;+ case trading::ConnectionState::TokenExpired:+ ++token_expired;+ problems.append(QString("%1 (token expired)").arg(acct.display_name));+ break;+ case trading::ConnectionState::Error:+ ++errored;+ problems.append(QString("%1 (error)").arg(acct.display_name));+ break;+ case trading::ConnectionState::Disconnected:+ case trading::ConnectionState::Connecting:+ problems.append(QString("%1 (%2)")+ .arg(acct.display_name,+ trading::connection_state_str(state)));+ break;+ }+ }++ if (considered == 0) {+ c.ok = true;+ c.detail = "No active live broker accounts";+ } else if (token_expired == 0 && errored == 0 && connected == considered) {+ c.ok = true;+ c.detail = QString("%1/%2 live accounts connected").arg(connected).arg(considered);+ } else {+ c.ok = false;+ c.detail = QString("%1/%2 connected; issues: %3")+ .arg(connected)+ .arg(considered)+ .arg(problems.join(", "));+ }+ } catch (...) {+ c.ok = false;+ c.detail = "Exception while reading broker connection states";+ }+ return c;+}++// WebSocket stream health — how many per-account data streams are currently+// active. DataStreamManager tracks one AccountDataStream per active account but+// does not expose a per-stream "is the socket connected" flag publicly, so this+// check reports the count of managed streams vs the number of active live+// accounts that should have one.+HealthStatus::Check HealthMonitor::check_websocket_streams() const {+ HealthStatus::Check c;+ c.name = "websocket_streams";+ try {+ auto& dsm = trading::DataStreamManager::instance();+ const int active_streams = dsm.active_stream_ids().size();++ // Count active live accounts as the "expected" stream count.+ int expected = 0;+ const auto accounts = trading::AccountManager::instance().list_accounts();+ for (const auto& acct : accounts) {+ if (acct.is_active && acct.trading_mode == "live")+ ++expected;+ }++ if (expected == 0) {+ c.ok = true;+ c.detail = QString("%1 stream(s) active; no live accounts expecting a stream")+ .arg(active_streams);+ } else if (active_streams >= expected) {+ c.ok = true;+ c.detail = QString("%1 stream(s) active for %2 live account(s)")+ .arg(active_streams)+ .arg(expected);+ } else {+ c.ok = false;+ c.detail = QString("%1 stream(s) active but %2 live account(s) expect one")+ .arg(active_streams)+ .arg(expected);+ }+ } catch (...) {+ c.ok = false;+ c.detail = "Exception while reading data stream manager state";+ }+ return c;+}++// Python process pool — PythonRunner enforces a concurrency limit but does not+// publicly expose active / queued counts (those members are private). We can+// only verify the interpreter is available. TODO: surface active_count_ /+// queue_.size() from PythonRunner if a public accessor is added so this check+// can report real pool pressure / backlog.+HealthStatus::Check HealthMonitor::check_python_pool() const {+ HealthStatus::Check c;+ c.name = "python_pool";+ try {+ const bool available = python::PythonRunner::instance().is_available();+ c.ok = available;+ c.detail = available+ ? "Python interpreter available (pool active/queued counts not exposed)"+ : "Python interpreter not available";+ } catch (...) {+ c.ok = false;+ c.detail = "Exception while querying Python runner";+ }+ return c;+}++// DataHub producer / topic health — counts known topics and how many have a+// recorded error. Healthy if no topic is currently in an error state.+HealthStatus::Check HealthMonitor::check_datahub() const {+ HealthStatus::Check c;+ c.name = "datahub";+ try {+ const auto stats = datahub::DataHub::instance().stats();+ const int topic_count = stats.size();++ int errored = 0;+ int subscribed_topics = 0;+ QStringList errored_topics;+ for (const auto& ts : stats) {+ if (ts.subscriber_count > 0)+ ++subscribed_topics;+ if (!ts.last_error.isEmpty()) {+ ++errored;+ if (errored_topics.size() < 5)+ errored_topics.append(ts.topic);+ }+ }++ if (errored == 0) {+ c.ok = true;+ c.detail = QString("%1 topic(s), %2 with subscribers, no errors")+ .arg(topic_count)+ .arg(subscribed_topics);+ } else {+ c.ok = false;+ QString sample = errored_topics.join(", ");+ if (errored > errored_topics.size())+ sample += ", ...";+ c.detail = QString("%1 topic(s), %2 in error state: %3")+ .arg(topic_count)+ .arg(errored)+ .arg(sample);+ }+ } catch (...) {+ c.ok = false;+ c.detail = "Exception while reading DataHub stats";+ }+ return c;+}++} // namespace finceptdiff --git a/fincept-qt/src/core/HealthMonitor.h b/fincept-qt/src/core/HealthMonitor.hnew file mode 100644index 000000000..40e82f824--- /dev/null+++ b/fincept-qt/src/core/HealthMonitor.h@@ -0,0 +1,61 @@+#pragma once+// HealthMonitor — aggregates local subsystem health checks for the desktop app.+// See OPENALGO_BRIDGE_PHASE3.md §18.+//+// Unlike OpenAlgo's server-side health blueprint, Fincept is a desktop app, so+// this monitor focuses on the live trading / data subsystems that can silently+// degrade: broker connection states, per-account WebSocket streams, the Python+// process pool, and the DataHub producer/topic layer.+//+// Each check is defensively wrapped so a single failing/uninitialised subsystem+// reports as a failed Check rather than crashing the whole snapshot. Where a+// subsystem does not expose the information needed for a meaningful check, the+// Check reports "not available" instead of inventing an API call.++#include <QJsonObject>+#include <QString>+#include <QVector>++namespace fincept {++/// Snapshot of all health checks at one point in time.+struct HealthStatus {+ struct Check {+ QString name; ///< short identifier, e.g. "broker_connections"+ bool ok = false; ///< true if the subsystem is healthy+ QString detail; ///< human-readable summary / failure reason+ };++ QVector<Check> checks;++ /// True only if every check passed.+ bool all_ok() const;++ /// Serialise to a JSON object suitable for the MCP system_health_check tool.+ /// Shape: { "all_ok": bool, "checks": [ { name, ok, detail }, ... ] }+ QJsonObject to_json() const;+};++/// Singleton that runs all health checks synchronously on demand.+class HealthMonitor {+ public:+ static HealthMonitor& instance();++ /// Run every check now and return a snapshot. Safe to call from the main+ /// thread (each check is non-blocking — reads in-memory state only).+ HealthStatus check() const;++ private:+ HealthMonitor() = default;+ ~HealthMonitor() = default;+ HealthMonitor(const HealthMonitor&) = delete;+ HealthMonitor& operator=(const HealthMonitor&) = delete;++ // Individual checks — each returns a single Check and never throws.+ HealthStatus::Check check_broker_connections() const;+ HealthStatus::Check check_websocket_streams() const;+ HealthStatus::Check check_python_pool() const;+ HealthStatus::Check check_datahub() const;+};++} // namespace finceptdiff --git a/fincept-qt/src/mcp/McpInit.cpp b/fincept-qt/src/mcp/McpInit.cppindex 26ecf1d41..2f23ceb3f 100644--- a/fincept-qt/src/mcp/McpInit.cpp+++ b/fincept-qt/src/mcp/McpInit.cpp@@ -20,6 +20,7 @@#include "mcp/tools/ForumTools.h"#include "mcp/tools/GeopoliticsTools.h"#include "mcp/tools/GovDataTools.h"+#include "mcp/tools/LiveTradingTools.h"#include "mcp/tools/MAAnalyticsTools.h"#include "mcp/tools/MarketsTools.h"#include "mcp/tools/McpServersTools.h"@@ -116,6 +117,9 @@ void initialize_all_tools() {// paper trading tabprovider.register_tools(tools::get_paper_trading_tools());+ // live broker trading (order placement/cancel, account state, market data)+ provider.register_tools(tools::get_live_trading_tools());+// sec edgar (CIK resolution, XBRL financials, filing search)provider.register_tools(tools::get_edgar_tools());diff --git a/fincept-qt/src/mcp/tools/LiveTradingTools.cpp b/fincept-qt/src/mcp/tools/LiveTradingTools.cppnew file mode 100644index 000000000..1c2856d2b--- /dev/null+++ b/fincept-qt/src/mcp/tools/LiveTradingTools.cpp@@ -0,0 +1,785 @@+// LiveTradingTools.cpp — Live broker trading MCP tools (Phase 3 §15)+//+// Exposes UnifiedTrading / broker order, account-state, and market-data+// operations to the MCP layer so the AI can place/cancel live orders and read+// account state. All order-mutating tools are is_destructive=true so the+// Phase 6.12 confirmation modal fires before execution.+//+// Account resolution: every tool takes an optional account_id. If omitted and+// exactly one active account exists, that account is used; otherwise the tool+// fails and asks the caller to specify account_id.++#include "mcp/tools/LiveTradingTools.h"++#include "core/logging/Logger.h"+#include "mcp/ToolSchemaBuilder.h"+#include "trading/AccountManager.h"+#include "trading/BrokerInterface.h"+#include "trading/BrokerRegistry.h"+#include "trading/TradingTypes.h"+#include "trading/UnifiedTrading.h"++namespace fincept::mcp::tools {++static constexpr const char* TAG = "LiveTradingTools";++namespace {++using namespace fincept::trading;++// Resolve the account to operate on. Returns true on success and writes the+// resolved id into `out`. On failure, writes a caller-friendly message into+// `err`. If `arg` is non-empty it must name a real account; if empty, falls+// back to the single active account (else asks the caller to specify one).+bool resolve_account(const QString& arg, QString& out, QString& err) {+ auto& mgr = AccountManager::instance();+ if (!arg.isEmpty()) {+ if (!mgr.has_account(arg)) {+ err = QString("Unknown account_id: %1").arg(arg);+ return false;+ }+ out = arg;+ return true;+ }+ auto active = mgr.active_accounts();+ if (active.isEmpty()) {+ err = "No active broker accounts — connect a broker account first";+ return false;+ }+ if (active.size() > 1) {+ QStringList ids;+ for (const auto& a : active)+ ids.append(QString("%1 (%2)").arg(a.account_id, a.display_name));+ err = "Multiple active accounts — specify account_id. Active: " + ids.join(", ");+ return false;+ }+ out = active.first().account_id;+ return true;+}++// Resolve the IBroker* + credentials for an account, for account-state and+// market-data tools that hit the broker directly (no UnifiedTrading helper).+bool resolve_broker(const QString& account_id, IBroker*& broker, BrokerCredentials& creds, QString& err) {+ auto& mgr = AccountManager::instance();+ auto account = mgr.get_account(account_id);+ broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker) {+ err = QString("No broker registered for id: %1").arg(account.broker_id);+ return false;+ }+ creds = mgr.load_credentials(account_id);+ return true;+}++OrderSide parse_side(const QString& s) {+ return s.trimmed().toUpper() == "SELL" ? OrderSide::Sell : OrderSide::Buy;+}++// MARKET / LIMIT / SL / SL-M (OpenAlgo price-type vocabulary).+OrderType parse_order_type(const QString& s) {+ const QString u = s.trimmed().toUpper();+ if (u == "LIMIT")+ return OrderType::Limit;+ if (u == "SL" || u == "SL-L" || u == "SLL" || u == "STOP_LIMIT")+ return OrderType::StopLossLimit;+ if (u == "SL-M" || u == "SLM" || u == "STOP" || u == "STOP_MARKET")+ return OrderType::StopLoss;+ return OrderType::Market;+}++// MIS / CNC / NRML / etc. → ProductType. Empty defaults to Intraday (MIS).+ProductType parse_product(const QString& s) {+ const QString u = s.trimmed().toUpper();+ if (u == "CNC" || u == "DELIVERY")+ return ProductType::Delivery;+ if (u == "NRML" || u == "MARGIN")+ return ProductType::Margin;+ if (u == "CO" || u == "COVER")+ return ProductType::CoverOrder;+ if (u == "BO" || u == "BRACKET")+ return ProductType::BracketOrder;+ if (u == "MTF")+ return ProductType::MTF;+ return ProductType::Intraday; // MIS / default+}++QJsonObject order_info_to_json(const BrokerOrderInfo& o) {+ return QJsonObject{{"order_id", o.order_id},+ {"exchange_order_id", o.exchange_order_id},+ {"symbol", o.symbol},+ {"exchange", o.exchange},+ {"side", o.side},+ {"order_type", o.order_type},+ {"product_type", o.product_type},+ {"quantity", o.quantity},+ {"price", o.price},+ {"trigger_price", o.trigger_price},+ {"filled_qty", o.filled_qty},+ {"avg_price", o.avg_price},+ {"status", o.status},+ {"timestamp", o.timestamp},+ {"message", o.message}};+}++QJsonObject quote_to_json(const BrokerQuote& q) {+ return QJsonObject{{"symbol", q.symbol},+ {"ltp", q.ltp},+ {"open", q.open},+ {"high", q.high},+ {"low", q.low},+ {"close", q.close},+ {"volume", q.volume},+ {"change", q.change},+ {"change_pct", q.change_pct},+ {"bid", q.bid},+ {"ask", q.ask},+ {"bid_size", q.bid_size},+ {"ask_size", q.ask_size},+ {"oi", static_cast<double>(q.oi)},+ {"oi_change_pct", q.oi_change_pct},+ {"timestamp", static_cast<double>(q.timestamp)}};+}++} // namespace++std::vector<ToolDef> get_live_trading_tools() {+ std::vector<ToolDef> tools;++ // ════════════════════════════════════════════════════════════════════+ // Order management (is_destructive = true — AI must confirm)+ // ════════════════════════════════════════════════════════════════════++ // ── live_place_order ───────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_place_order";+ t.description = "Place a LIVE broker order. Real money. action BUY/SELL; "+ "order_type MARKET/LIMIT/SL/SL-M; product MIS/CNC/NRML. "+ "Requires confirmation.";+ t.category = "live-trading";+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("symbol", "Trading symbol (e.g. SBIN, RELIANCE)").required().length(1, 64)+ .string("exchange", "Exchange (e.g. NSE, BSE, NFO, MCX)").required()+ .string("action", "Order side").required().enums({"BUY", "SELL"})+ .number("quantity", "Order quantity (must be > 0)").required().min(0.0)+ .string("order_type", "Price type").default_str("MARKET")+ .enums({"MARKET", "LIMIT", "SL", "SL-M"})+ .number("price", "Limit price (required for LIMIT / SL)")+ .number("trigger_price", "Trigger price (required for SL / SL-M)")+ .string("product", "Product type").default_str("MIS")+ .enums({"MIS", "CNC", "NRML"})+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString symbol = args["symbol"].toString().trimmed();+ QString exchange = args["exchange"].toString().trimmed();+ double quantity = args["quantity"].toDouble(0.0);+ if (symbol.isEmpty() || exchange.isEmpty() || quantity <= 0)+ return ToolResult::fail("Missing required: symbol, exchange, quantity (>0)");++ UnifiedOrder order;+ order.symbol = symbol;+ order.exchange = exchange;+ order.side = parse_side(args["action"].toString());+ order.order_type = parse_order_type(args["order_type"].toString("MARKET"));+ order.quantity = quantity;+ order.price = args["price"].toDouble(0.0);+ order.stop_price = args["trigger_price"].toDouble(0.0);+ order.product_type = parse_product(args["product"].toString("MIS"));++ auto resp = UnifiedTrading::instance().place_order(account_id, order);+ if (!resp.success)+ return ToolResult::fail(resp.message.isEmpty() ? "Order placement failed" : resp.message);++ LOG_INFO(TAG, QString("Live order placed: %1 %2 %3 -> %4")+ .arg(args["action"].toString(), symbol)+ .arg(quantity).arg(resp.order_id));+ return ToolResult::ok("Order placed", QJsonObject{{"order_id", resp.order_id},+ {"account_id", account_id},+ {"symbol", symbol},+ {"exchange", exchange},+ {"mode", resp.mode},+ {"message", resp.message}});+ };+ tools.push_back(std::move(t));+ }++ // ── live_smart_order ───────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_smart_order";+ t.description = "Place a position-aware LIVE smart order. Targets a net "+ "position_size (positive=long, negative=short, 0=flatten) "+ "and places the delta order. Requires confirmation.";+ t.category = "live-trading";+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("symbol", "Trading symbol").required().length(1, 64)+ .string("exchange", "Exchange (e.g. NSE, NFO)").required()+ .number("position_size", "Target net position (positive=long, negative=short, 0=flatten)").required()+ .string("order_type", "Price type").default_str("MARKET")+ .enums({"MARKET", "LIMIT", "SL", "SL-M"})+ .number("price", "Limit price (required for LIMIT / SL)")+ .string("product", "Product type").default_str("MIS")+ .enums({"MIS", "CNC", "NRML"})+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString symbol = args["symbol"].toString().trimmed();+ QString exchange = args["exchange"].toString().trimmed();+ if (symbol.isEmpty() || exchange.isEmpty())+ return ToolResult::fail("Missing required: symbol, exchange");+ if (!args.contains("position_size"))+ return ToolResult::fail("Missing required: position_size");++ SmartOrder order;+ order.symbol = symbol;+ order.exchange = exchange;+ order.position_size = args["position_size"].toDouble(0.0);+ order.order_type = parse_order_type(args["order_type"].toString("MARKET"));+ order.price = args["price"].toDouble(0.0);+ order.product_type = parse_product(args["product"].toString("MIS"));++ auto resp = UnifiedTrading::instance().place_smart_order(account_id, order);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Smart order failed" : resp.error);++ const auto& r = resp.data.value();+ LOG_INFO(TAG, QString("Live smart order: %1 -> action_taken=%2 %3")+ .arg(symbol).arg(r.action_taken).arg(r.order_id));+ return ToolResult::ok(r.message.isEmpty() ? "Smart order processed" : r.message,+ QJsonObject{{"account_id", account_id},+ {"symbol", symbol},+ {"action_taken", r.action_taken},+ {"order_id", r.order_id},+ {"executed_action", order_side_str(r.executed_action)},+ {"executed_quantity", r.executed_quantity},+ {"message", r.message}});+ };+ tools.push_back(std::move(t));+ }++ // ── live_cancel_order ──────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_cancel_order";+ t.description = "Cancel a single open LIVE order by order_id. Requires confirmation.";+ t.category = "live-trading";+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("order_id", "Broker order ID to cancel").required()+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString order_id = args["order_id"].toString().trimmed();+ if (order_id.isEmpty())+ return ToolResult::fail("Missing 'order_id'");++ auto resp = UnifiedTrading::instance().cancel_order(account_id, order_id);+ if (!resp.success)+ return ToolResult::fail(resp.message.isEmpty() ? "Cancel failed" : resp.message);++ LOG_INFO(TAG, QString("Live order cancelled: %1 (%2)").arg(order_id, account_id));+ return ToolResult::ok("Order cancelled", QJsonObject{{"order_id", order_id},+ {"account_id", account_id},+ {"message", resp.message}});+ };+ tools.push_back(std::move(t));+ }++ // ── live_cancel_all_orders ─────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_cancel_all_orders";+ t.description = "Cancel ALL open LIVE orders for an account. Requires confirmation.";+ t.category = "live-trading";+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ auto resp = UnifiedTrading::instance().cancel_all_orders(account_id);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Cancel-all failed" : resp.error);++ const auto& r = resp.data.value();+ QJsonArray canceled;+ for (const auto& id : r.canceled_order_ids)+ canceled.append(id);+ QJsonArray failed;+ for (const auto& f : r.failed)+ failed.append(QJsonObject{{"order_id", f.first}, {"error", f.second}});++ LOG_INFO(TAG, QString("Live cancel-all: %1/%2 cancelled (%3)")+ .arg(canceled.size()).arg(r.total_attempted).arg(account_id));+ return ToolResult::ok("Cancel-all complete", QJsonObject{{"account_id", account_id},+ {"total_attempted", r.total_attempted},+ {"canceled_count", canceled.size()},+ {"failed_count", failed.size()},+ {"canceled_order_ids", canceled},+ {"failed", failed}});+ };+ tools.push_back(std::move(t));+ }++ // ── live_close_position ────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_close_position";+ t.description = "Close a single LIVE position by symbol/exchange (places a "+ "market counter-order). Requires confirmation.";+ t.category = "live-trading";+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("symbol", "Symbol of the position to close").required().length(1, 64)+ .string("exchange", "Exchange of the position").required()+ .string("product", "Product type filter (optional: MIS/CNC/NRML)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString symbol = args["symbol"].toString().trimmed();+ QString exchange = args["exchange"].toString().trimmed();+ QString product = args["product"].toString().trimmed();+ if (symbol.isEmpty() || exchange.isEmpty())+ return ToolResult::fail("Missing required: symbol, exchange");++ auto resp = UnifiedTrading::instance().close_position(account_id, symbol, exchange, product);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Close position failed" : resp.error);++ const auto& r = resp.data.value();+ LOG_INFO(TAG, QString("Live position closed: %1 %2 -> %3").arg(symbol, exchange, r.order_id));+ return ToolResult::ok("Position closed", QJsonObject{{"account_id", account_id},+ {"symbol", symbol},+ {"exchange", exchange},+ {"order_id", r.order_id}});+ };+ tools.push_back(std::move(t));+ }++ // ── live_close_all_positions ───────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_close_all_positions";+ t.description = "Square off ALL open LIVE positions for an account (market "+ "counter-orders). Requires confirmation.";+ t.category = "live-trading";+ t.auth_required = AuthLevel::Authenticated;+ t.is_destructive = true;+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ auto resp = UnifiedTrading::instance().close_all_positions(account_id);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Close-all failed" : resp.error);++ const auto& r = resp.data.value();+ QJsonArray closed;+ for (const auto& s : r.closed_symbols)+ closed.append(s);+ QJsonArray failed;+ for (const auto& f : r.failed)+ failed.append(QJsonObject{{"symbol", f.first}, {"error", f.second}});++ LOG_INFO(TAG, QString("Live close-all: %1/%2 closed (%3)")+ .arg(closed.size()).arg(r.total_positions).arg(account_id));+ return ToolResult::ok("Close-all complete", QJsonObject{{"account_id", account_id},+ {"total_positions", r.total_positions},+ {"closed_count", closed.size()},+ {"failed_count", failed.size()},+ {"closed_symbols", closed},+ {"failed", failed}});+ };+ tools.push_back(std::move(t));+ }++ // ════════════════════════════════════════════════════════════════════+ // Account state (read-only — is_destructive = false)+ // ════════════════════════════════════════════════════════════════════++ // ── live_get_positions ─────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_positions";+ t.description = "Get current open positions for a live broker account.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ if (!resolve_broker(account_id, broker, creds, err))+ return ToolResult::fail(err);++ auto resp = broker->get_positions(creds);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch positions" : resp.error);++ QJsonArray result;+ for (const auto& p : resp.data.value_or(QVector<BrokerPosition>{})) {+ result.append(QJsonObject{{"symbol", p.symbol},+ {"exchange", p.exchange},+ {"product_type", p.product_type},+ {"quantity", p.quantity},+ {"avg_price", p.avg_price},+ {"ltp", p.ltp},+ {"pnl", p.pnl},+ {"pnl_pct", p.pnl_pct},+ {"day_pnl", p.day_pnl},+ {"side", p.side}});+ }+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_holdings ──────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_holdings";+ t.description = "Get long-term holdings (demat) for a live broker account.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ if (!resolve_broker(account_id, broker, creds, err))+ return ToolResult::fail(err);++ auto resp = broker->get_holdings(creds);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch holdings" : resp.error);++ QJsonArray result;+ for (const auto& h : resp.data.value_or(QVector<BrokerHolding>{})) {+ result.append(QJsonObject{{"symbol", h.symbol},+ {"exchange", h.exchange},+ {"quantity", h.quantity},+ {"avg_price", h.avg_price},+ {"ltp", h.ltp},+ {"pnl", h.pnl},+ {"pnl_pct", h.pnl_pct},+ {"invested_value", h.invested_value},+ {"current_value", h.current_value}});+ }+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_orders ────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_orders";+ t.description = "Get the order book (all orders for the day) for a live broker account.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ if (!resolve_broker(account_id, broker, creds, err))+ return ToolResult::fail(err);++ auto resp = broker->get_orders(creds);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch orders" : resp.error);++ QJsonArray result;+ for (const auto& o : resp.data.value_or(QVector<BrokerOrderInfo>{}))+ result.append(order_info_to_json(o));+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_trades ────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_trades";+ t.description = "Get the trade book (executed fills) for a live broker account.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ if (!resolve_broker(account_id, broker, creds, err))+ return ToolResult::fail(err);++ auto resp = broker->get_trade_book(creds);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch trades" : resp.error);++ // Trade book is broker-specific JSON — pass through raw.+ return ToolResult::ok_data(resp.data.value_or(QJsonObject{}));+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_funds ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_funds";+ t.description = "Get available balance, used margin, and total balance for a live broker account.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ if (!resolve_broker(account_id, broker, creds, err))+ return ToolResult::fail(err);++ auto resp = broker->get_funds(creds);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch funds" : resp.error);++ const auto& f = resp.data.value();+ return ToolResult::ok_data(QJsonObject{{"available_balance", f.available_balance},+ {"used_margin", f.used_margin},+ {"total_balance", f.total_balance},+ {"collateral", f.collateral}});+ };+ tools.push_back(std::move(t));+ }++ // ════════════════════════════════════════════════════════════════════+ // Market data (read-only — is_destructive = false)+ // ════════════════════════════════════════════════════════════════════++ // ── live_get_quote ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_quote";+ t.description = "Get a single live quote (LTP, bid/ask, OHLC, volume, OI) for a symbol.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("symbol", "Trading symbol").required().length(1, 64)+ .string("exchange", "Exchange (e.g. NSE, NFO)").required()+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString symbol = args["symbol"].toString().trimmed();+ QString exchange = args["exchange"].toString().trimmed();+ if (symbol.isEmpty() || exchange.isEmpty())+ return ToolResult::fail("Missing required: symbol, exchange");++ auto resp = UnifiedTrading::instance().get_multi_quotes(account_id, {{symbol, exchange}});+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch quote" : resp.error);++ const auto& quotes = resp.data.value();+ if (quotes.isEmpty())+ return ToolResult::fail("No quote returned for " + symbol);+ return ToolResult::ok_data(quote_to_json(quotes.first()));+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_multi_quotes ──────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_multi_quotes";+ t.description = "Get live quotes for multiple symbols in one call. Each entry "+ "is \"EXCHANGE:SYMBOL\" (e.g. NSE:SBIN) or just SYMBOL.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .array("symbols", "Symbols as \"EXCHANGE:SYMBOL\" or \"SYMBOL\"",+ QJsonObject{{"type", "string"}}).required()+ .string("exchange", "Default exchange for entries without an EXCHANGE: prefix")+ .default_str("NSE")+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString default_exchange = args["exchange"].toString("NSE").trimmed();+ QVector<QPair<QString, QString>> pairs;+ for (const auto& v : args["symbols"].toArray()) {+ QString entry = v.toString().trimmed();+ if (entry.isEmpty())+ continue;+ int colon = entry.indexOf(':');+ if (colon > 0)+ pairs.append({entry.mid(colon + 1).trimmed(), entry.left(colon).trimmed()});+ else+ pairs.append({entry, default_exchange});+ }+ if (pairs.isEmpty())+ return ToolResult::fail("Missing or empty 'symbols'");++ auto resp = UnifiedTrading::instance().get_multi_quotes(account_id, pairs);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch quotes" : resp.error);++ QJsonArray result;+ for (const auto& q : resp.data.value())+ result.append(quote_to_json(q));+ return ToolResult::ok_data(result);+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_depth ─────────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_depth";+ t.description = "Get Level-2 market depth (bid/ask ladder) for a symbol.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("symbol", "Trading symbol").required().length(1, 64)+ .string("exchange", "Exchange (e.g. NSE, NFO)").required()+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString symbol = args["symbol"].toString().trimmed();+ QString exchange = args["exchange"].toString().trimmed();+ if (symbol.isEmpty() || exchange.isEmpty())+ return ToolResult::fail("Missing required: symbol, exchange");++ auto resp = UnifiedTrading::instance().get_market_depth(account_id, symbol, exchange);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch depth" : resp.error);++ const auto& d = resp.data.value();+ QJsonArray bids, asks;+ for (const auto& lvl : d.bids)+ bids.append(QJsonObject{{"price", lvl.price}, {"quantity", lvl.quantity}, {"orders", lvl.orders}});+ for (const auto& lvl : d.asks)+ asks.append(QJsonObject{{"price", lvl.price}, {"quantity", lvl.quantity}, {"orders", lvl.orders}});++ return ToolResult::ok_data(QJsonObject{{"symbol", d.symbol},+ {"exchange", d.exchange},+ {"ltp", d.ltp},+ {"volume", d.volume},+ {"oi", d.oi},+ {"bids", bids},+ {"asks", asks}});+ };+ tools.push_back(std::move(t));+ }++ // ── live_get_option_chain ──────────────────────────────────────────+ {+ ToolDef t;+ t.name = "live_get_option_chain";+ t.description = "Get the option chain (CE/PE quotes per strike) for an underlying and expiry.";+ t.category = "live-trading";+ t.input_schema = ToolSchemaBuilder()+ .string("account_id", "Broker account ID (optional if exactly one active account)")+ .string("underlying", "Underlying symbol (e.g. NIFTY, BANKNIFTY)").required().length(1, 64)+ .string("exchange", "Exchange (e.g. NFO, BFO)").required()+ .string("expiry", "Expiry date (broker format, e.g. 2026-05-29)").required()+ .integer("strike_count", "Number of strikes around ATM (0 = broker default)")+ .default_int(0).min(0.0)+ .build();+ t.handler = [](const QJsonObject& args) -> ToolResult {+ QString account_id, err;+ if (!resolve_account(args["account_id"].toString(), account_id, err))+ return ToolResult::fail(err);++ QString underlying = args["underlying"].toString().trimmed();+ QString exchange = args["exchange"].toString().trimmed();+ QString expiry = args["expiry"].toString().trimmed();+ int strike_count = args["strike_count"].toInt(0);+ if (underlying.isEmpty() || exchange.isEmpty() || expiry.isEmpty())+ return ToolResult::fail("Missing required: underlying, exchange, expiry");++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ if (!resolve_broker(account_id, broker, creds, err))+ return ToolResult::fail(err);++ auto resp = broker->get_option_chain(creds, underlying, exchange, expiry, strike_count);+ if (!resp.success)+ return ToolResult::fail(resp.error.isEmpty() ? "Failed to fetch option chain" : resp.error);++ QJsonArray result;+ for (const auto& e : resp.data.value_or(QVector<OptionChainEntry>{})) {+ result.append(QJsonObject{{"strike_price", e.strike_price},+ {"label", e.label},+ {"ce_symbol", e.ce_symbol},+ {"ce_quote", quote_to_json(e.ce_quote)},+ {"pe_symbol", e.pe_symbol},+ {"pe_quote", quote_to_json(e.pe_quote)}});+ }+ return ToolResult::ok_data(QJsonObject{{"underlying", underlying},+ {"exchange", exchange},+ {"expiry", expiry},+ {"chain", result}});+ };+ tools.push_back(std::move(t));+ }++ return tools;+}++} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/LiveTradingTools.h b/fincept-qt/src/mcp/tools/LiveTradingTools.hnew file mode 100644index 000000000..fee4f6d8c--- /dev/null+++ b/fincept-qt/src/mcp/tools/LiveTradingTools.h@@ -0,0 +1,8 @@+#pragma once+#include "mcp/McpTypes.h"++#include <vector>++namespace fincept::mcp::tools {+std::vector<ToolDef> get_live_trading_tools();+} // namespace fincept::mcp::toolsdiff --git a/fincept-qt/src/mcp/tools/SystemTools.cpp b/fincept-qt/src/mcp/tools/SystemTools.cppindex fdd527766..10445d1dd 100644--- a/fincept-qt/src/mcp/tools/SystemTools.cpp+++ b/fincept-qt/src/mcp/tools/SystemTools.cpp@@ -3,6 +3,7 @@#include "mcp/tools/SystemTools.h"#include "auth/AuthManager.h"+#include "core/HealthMonitor.h"#include "core/logging/Logger.h"#include "mcp/McpProvider.h"#include "python/PythonRunner.h"@@ -93,6 +94,20 @@ std::vector<ToolDef> get_system_tools() {tools.push_back(std::move(t));}+ // ── system_health_check ────────────────────────────────────────────+ {+ ToolDef t;+ t.name = "system_health_check";+ t.description = "Run local subsystem health checks (broker connections, "+ "WebSocket streams, Python pool, DataHub) and return a "+ "snapshot with an overall all_ok flag and per-check details.";+ t.category = "system";+ t.handler = [](const QJsonObject&) -> ToolResult {+ return ToolResult::ok_data(HealthMonitor::instance().check().to_json());+ };+ tools.push_back(std::move(t));+ }+return tools;}diff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cppindex dd3667e4d..61235c39a 100644--- a/fincept-qt/src/python/PythonRunner.cpp+++ b/fincept-qt/src/python/PythonRunner.cpp@@ -109,7 +109,25 @@ static bool route_yfinance_to_daemon(const QStringList& args,}PythonResult r;r.success = true;- r.output = QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Compact));+ // PythonWorker wraps non-object results (e.g. the bare JSON array+ // that historical_period/historical/batch_sparklines return) under+ // "_value" so its object-callback API always hands back an object.+ // The string-output path callers (e.g. EquityResearchService) expect+ // the same raw JSON the subprocess path prints — a bare array, not a+ // {"_value":[...]} wrapper. Unwrap so both paths are byte-identical.+ if (result.size() == 1 && result.contains(QLatin1String("_value"))) {+ const QJsonValue v = result.value(QLatin1String("_value"));+ QJsonDocument doc;+ if (v.isArray())+ doc.setArray(v.toArray());+ else if (v.isObject())+ doc.setObject(v.toObject());+ else+ doc = QJsonDocument::fromVariant(v.toVariant());+ r.output = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));+ } else {+ r.output = QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Compact));+ }r.exit_code = 0;cb(r);});diff --git a/fincept-qt/src/screens/action_center/ActionCenterScreen.cpp b/fincept-qt/src/screens/action_center/ActionCenterScreen.cppnew file mode 100644index 000000000..d746263f8--- /dev/null+++ b/fincept-qt/src/screens/action_center/ActionCenterScreen.cpp@@ -0,0 +1,369 @@+// ActionCenterScreen.cpp — semi-auto order approval UI (Phase 3 §2).+#include "screens/action_center/ActionCenterScreen.h"++#include "trading/AccountManager.h"+#include "ui/theme/Theme.h"++#include <QHBoxLayout>+#include <QHeaderView>+#include <QInputDialog>+#include <QLineEdit>+#include <QMessageBox>+#include <QPushButton>+#include <QSignalBlocker>+#include <QVBoxLayout>++namespace fincept::screens {++using fincept::trading::ActionCenter;+using fincept::trading::OrderMode;+using fincept::trading::PendingOrder;++namespace {+constexpr int kColTime = 0;+constexpr int kColAccount = 1;+constexpr int kColType = 2;+constexpr int kColSymbol = 3;+constexpr int kColSide = 4;+constexpr int kColQty = 5;+constexpr int kColPriceType = 6;+constexpr int kColStatus = 7;+constexpr int kColActions = 8;+constexpr int kColCount = 9;+} // namespace++ActionCenterScreen::ActionCenterScreen(QWidget* parent) : QWidget(parent) {+ setObjectName("actionCenterScreen");+ build_ui();+}++void ActionCenterScreen::build_ui() {+ auto* root = new QVBoxLayout(this);+ root->setContentsMargins(0, 0, 0, 0);+ root->setSpacing(0);++ // Global stylesheet via descendant selectors (P7) — amber #d97706 accents.+ setStyleSheet(QString(+ "#actionCenterScreen{background:%1;}"+ "#acHeader{background:%2;border-bottom:1px solid %3;}"+ "#acTitle{color:%4;font-size:14px;font-weight:700;letter-spacing:0.5px;}"+ "#acStatsBar{background:%2;border-bottom:1px solid %3;}"+ "#acStatCaption{color:%5;font-size:10px;letter-spacing:0.5px;}"+ "#acStatValue{color:%6;font-size:15px;font-weight:700;}"+ "#acTable{background:%1;color:%6;gridline-color:%3;border:none;}"+ "#acTable::item{padding:2px 6px;}"+ "QHeaderView::section{background:%2;color:%5;border:none;border-bottom:1px solid %3;"+ "padding:4px 6px;font-size:10px;font-weight:700;letter-spacing:0.5px;}"+ "#acCombo{background:%2;color:%6;border:1px solid %3;padding:3px 8px;font-size:11px;}"+ "#acApproveAll{background:rgba(34,197,94,0.14);color:%7;border:1px solid %7;"+ "padding:5px 16px;font-size:11px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"+ "#acApproveAll:hover{background:rgba(34,197,94,0.28);}"+ "#acRejectAll{background:rgba(220,38,38,0.12);color:%8;border:1px solid %8;"+ "padding:5px 16px;font-size:11px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"+ "#acRejectAll:hover{background:rgba(220,38,38,0.25);}")+ .arg(fincept::ui::colors::DARK(), fincept::ui::colors::PANEL(),+ fincept::ui::colors::BORDER(), fincept::ui::colors::AMBER(),+ fincept::ui::colors::TEXT_SECONDARY(), fincept::ui::colors::TEXT_PRIMARY(),+ fincept::ui::colors::POSITIVE(), fincept::ui::colors::NEGATIVE()));++ // ── Header: title + account selector + status filter + mode toggle ────────+ auto* header = new QWidget;+ header->setObjectName("acHeader");+ auto* hlay = new QHBoxLayout(header);+ hlay->setContentsMargins(14, 8, 14, 8);+ hlay->setSpacing(12);++ auto* title = new QLabel("ACTION CENTER");+ title->setObjectName("acTitle");+ hlay->addWidget(title);+ hlay->addSpacing(16);++ hlay->addWidget(new QLabel("Account:"));+ account_combo_ = new QComboBox;+ account_combo_->setObjectName("acCombo");+ account_combo_->setMinimumWidth(180);+ hlay->addWidget(account_combo_);++ hlay->addWidget(new QLabel("Show:"));+ status_filter_ = new QComboBox;+ status_filter_->setObjectName("acCombo");+ status_filter_->addItem("Pending", "pending");+ status_filter_->addItem("Approved", "approved");+ status_filter_->addItem("Rejected", "rejected");+ status_filter_->addItem("All", "all");+ hlay->addWidget(status_filter_);++ hlay->addStretch(1);++ hlay->addWidget(new QLabel("Mode:"));+ mode_combo_ = new QComboBox;+ mode_combo_->setObjectName("acCombo");+ mode_combo_->addItem("Auto", "auto");+ mode_combo_->addItem("Semi-Auto", "semi_auto");+ hlay->addWidget(mode_combo_);++ root->addWidget(header);++ // ── Stats bar ─────────────────────────────────────────────────────────────+ auto* stats = new QWidget;+ stats->setObjectName("acStatsBar");+ auto* slay = new QHBoxLayout(stats);+ slay->setContentsMargins(14, 6, 14, 6);+ slay->setSpacing(28);++ auto make_stat = [&](const QString& caption, QLabel*& out) {+ auto* cell = new QWidget;+ auto* cv = new QVBoxLayout(cell);+ cv->setContentsMargins(0, 0, 0, 0);+ cv->setSpacing(1);+ auto* cap = new QLabel(caption);+ cap->setObjectName("acStatCaption");+ out = new QLabel("0");+ out->setObjectName("acStatValue");+ cv->addWidget(cap);+ cv->addWidget(out);+ slay->addWidget(cell);+ };+ make_stat("PENDING", stat_pending_);+ make_stat("APPROVED", stat_approved_);+ make_stat("REJECTED", stat_rejected_);+ make_stat("BUY", stat_buy_);+ make_stat("SELL", stat_sell_);+ slay->addStretch(1);++ approve_all_btn_ = new QPushButton("APPROVE ALL");+ approve_all_btn_->setObjectName("acApproveAll");+ approve_all_btn_->setCursor(Qt::PointingHandCursor);+ slay->addWidget(approve_all_btn_);++ reject_all_btn_ = new QPushButton("REJECT ALL");+ reject_all_btn_->setObjectName("acRejectAll");+ reject_all_btn_->setCursor(Qt::PointingHandCursor);+ slay->addWidget(reject_all_btn_);++ root->addWidget(stats);++ // ── Table ─────────────────────────────────────────────────────────────────+ table_ = new QTableWidget;+ table_->setObjectName("acTable");+ table_->setColumnCount(kColCount);+ table_->setHorizontalHeaderLabels(+ {"Time", "Account", "Type", "Symbol", "Side", "Qty", "Price Type", "Status", "Actions"});+ table_->verticalHeader()->setVisible(false);+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ table_->setShowGrid(false);+ table_->verticalHeader()->setDefaultSectionSize(28);+ table_->horizontalHeader()->setStretchLastSection(false);+ table_->horizontalHeader()->setSectionResizeMode(kColSymbol, QHeaderView::Stretch);+ table_->setColumnWidth(kColActions, 170);+ root->addWidget(table_, 1);++ // ── Wiring ────────────────────────────────────────────────────────────────+ connect(account_combo_, &QComboBox::currentIndexChanged, this, [this](int) {+ // Reflect the selected account's persisted mode, then reload.+ const QString acct = selected_account();+ if (!acct.isEmpty()) {+ const auto mode = ActionCenter::instance().get_order_mode(acct);+ const int idx = mode_combo_->findData(fincept::trading::order_mode_str(mode));+ if (idx >= 0) {+ QSignalBlocker b(mode_combo_);+ mode_combo_->setCurrentIndex(idx);+ }+ mode_combo_->setEnabled(true);+ } else {+ mode_combo_->setEnabled(false); // can't set a mode for "all accounts"+ }+ refresh();+ });+ connect(status_filter_, &QComboBox::currentIndexChanged, this, [this](int) { refresh(); });+ connect(mode_combo_, &QComboBox::currentIndexChanged, this, [this](int) {+ const QString acct = selected_account();+ if (acct.isEmpty())+ return;+ ActionCenter::instance().set_order_mode(+ acct, fincept::trading::parse_order_mode(mode_combo_->currentData().toString()));+ });+ connect(approve_all_btn_, &QPushButton::clicked, this, [this]() {+ const QString acct = selected_account();+ auto ans = QMessageBox::question(this, "Approve All",+ "Execute ALL pending orders now?",+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (ans != QMessageBox::Yes)+ return;+ ActionCenter::instance().approve_all_pending(acct);+ });+ connect(reject_all_btn_, &QPushButton::clicked, this, [this]() {+ const QString acct = selected_account();+ if (acct.isEmpty()) {+ QMessageBox::information(this, "Reject All",+ "Select a specific account to reject all its pending orders.");+ return;+ }+ bool ok = false;+ const QString reason = QInputDialog::getText(this, "Reject All",+ "Rejection reason:", QLineEdit::Normal,+ "Rejected by user", &ok);+ if (!ok)+ return;+ ActionCenter::instance().reject_all_pending(acct, reason);+ });+}++QString ActionCenterScreen::selected_account() const {+ return account_combo_ ? account_combo_->currentData().toString() : QString();+}++void ActionCenterScreen::reload_accounts() {+ const QString prev = selected_account();+ QSignalBlocker b(account_combo_);+ account_combo_->clear();+ account_combo_->addItem("All Accounts", QString());+ for (const auto& acct : trading::AccountManager::instance().list_accounts()) {+ const QString label = acct.display_name.isEmpty() ? acct.account_id : acct.display_name;+ account_combo_->addItem(label, acct.account_id);+ }+ const int idx = account_combo_->findData(prev);+ account_combo_->setCurrentIndex(idx >= 0 ? idx : 0);+ mode_combo_->setEnabled(!selected_account().isEmpty());+}++void ActionCenterScreen::refresh() {+ const QString acct = selected_account();+ const QString status = status_filter_->currentData().toString();++ QVector<PendingOrder> orders = ActionCenter::instance().get_all_orders(acct, 200);+ if (status != "all") {+ QVector<PendingOrder> filtered;+ for (const auto& o : orders)+ if (o.status == status)+ filtered.append(o);+ orders = filtered;+ }++ table_->setRowCount(0);+ table_->setRowCount(orders.size());+ for (int row = 0; row < orders.size(); ++row) {+ const PendingOrder& o = orders[row];++ auto set = [&](int col, const QString& text) {+ auto* item = new QTableWidgetItem(text);+ item->setForeground(QColor(fincept::ui::colors::TEXT_PRIMARY()));+ table_->setItem(row, col, item);+ };+ set(kColTime, o.created_at.toString("HH:mm:ss"));+ // Resolve account display name.+ const auto acct_meta = trading::AccountManager::instance().get_account(o.account_id);+ set(kColAccount, acct_meta.display_name.isEmpty() ? o.account_id : acct_meta.display_name);+ set(kColType, o.order_type);+ set(kColSymbol, o.symbol);++ auto* side_item = new QTableWidgetItem(o.action);+ const QString actUp = o.action.toUpper();+ side_item->setForeground(actUp == "BUY" ? QColor(fincept::ui::colors::POSITIVE())+ : actUp == "SELL" ? QColor(fincept::ui::colors::NEGATIVE())+ : QColor(fincept::ui::colors::TEXT_PRIMARY()));+ table_->setItem(row, kColSide, side_item);++ set(kColQty, o.quantity);+ set(kColPriceType, o.price_type);++ auto* status_item = new QTableWidgetItem(o.status.toUpper());+ status_item->setForeground(o.status == "approved" ? QColor(fincept::ui::colors::POSITIVE())+ : o.status == "rejected" ? QColor(fincept::ui::colors::NEGATIVE())+ : QColor(fincept::ui::colors::AMBER()));+ table_->setItem(row, kColStatus, status_item);++ // Per-row Approve / Reject buttons (only for pending rows).+ if (o.status == "pending") {+ auto* cell = new QWidget;+ auto* cl = new QHBoxLayout(cell);+ cl->setContentsMargins(4, 2, 4, 2);+ cl->setSpacing(6);+ auto* approve = new QPushButton("Approve");+ approve->setCursor(Qt::PointingHandCursor);+ approve->setStyleSheet(QString("QPushButton{background:rgba(34,197,94,0.14);color:%1;"+ "border:1px solid %1;padding:2px 10px;font-size:10px;"+ "font-weight:700;border-radius:2px;}"+ "QPushButton:hover{background:rgba(34,197,94,0.28);}")+ .arg(fincept::ui::colors::POSITIVE()));+ auto* reject = new QPushButton("Reject");+ reject->setCursor(Qt::PointingHandCursor);+ reject->setStyleSheet(QString("QPushButton{background:rgba(220,38,38,0.12);color:%1;"+ "border:1px solid %1;padding:2px 10px;font-size:10px;"+ "font-weight:700;border-radius:2px;}"+ "QPushButton:hover{background:rgba(220,38,38,0.25);}")+ .arg(fincept::ui::colors::NEGATIVE()));+ const QString id = o.id;+ connect(approve, &QPushButton::clicked, this, [this, id]() { approve_row(id); });+ connect(reject, &QPushButton::clicked, this, [this, id]() { reject_row(id); });+ cl->addWidget(approve);+ cl->addWidget(reject);+ cl->addStretch(1);+ table_->setCellWidget(row, kColActions, cell);+ } else if (!o.broker_order_id.isEmpty()) {+ set(kColActions, "→ " + o.broker_order_id);+ } else if (!o.rejection_reason.isEmpty()) {+ set(kColActions, o.rejection_reason);+ }+ }++ refresh_stats();+}++void ActionCenterScreen::refresh_stats() {+ const auto s = ActionCenter::instance().get_stats(selected_account());+ stat_pending_->setText(QString::number(s.total_pending));+ stat_approved_->setText(QString::number(s.total_approved));+ stat_rejected_->setText(QString::number(s.total_rejected));+ stat_buy_->setText(QString::number(s.total_buy));+ stat_sell_->setText(QString::number(s.total_sell));+}++void ActionCenterScreen::approve_row(const QString& pending_id) {+ ActionCenter::instance().approve_order(pending_id);+}++void ActionCenterScreen::reject_row(const QString& pending_id) {+ bool ok = false;+ const QString reason = QInputDialog::getText(this, "Reject Order", "Rejection reason:",+ QLineEdit::Normal, "Rejected by user", &ok);+ if (!ok)+ return;+ ActionCenter::instance().reject_order(pending_id, reason);+}++// ── ActionCenter signal slots ───────────────────────────────────────────────++void ActionCenterScreen::on_pending_created(const PendingOrder&) { refresh(); }+void ActionCenterScreen::on_order_approved(const QString&, const QString&) { refresh(); }+void ActionCenterScreen::on_order_rejected(const QString&, const QString&) { refresh(); }+void ActionCenterScreen::on_stats_updated(const QString&) { refresh_stats(); }++// ── Visibility lifecycle (P3) ───────────────────────────────────────────────++void ActionCenterScreen::showEvent(QShowEvent* e) {+ QWidget::showEvent(e);+ if (!wired_) {+ wired_ = true;+ auto& ac = ActionCenter::instance();+ connect(&ac, &ActionCenter::pending_order_created, this,+ &ActionCenterScreen::on_pending_created);+ connect(&ac, &ActionCenter::order_approved, this, &ActionCenterScreen::on_order_approved);+ connect(&ac, &ActionCenter::order_rejected, this, &ActionCenterScreen::on_order_rejected);+ connect(&ac, &ActionCenter::stats_updated, this, &ActionCenterScreen::on_stats_updated);+ // Refresh the account list when accounts change.+ connect(&trading::AccountManager::instance(), &trading::AccountManager::account_added, this,+ [this](const QString&) { reload_accounts(); });+ connect(&trading::AccountManager::instance(), &trading::AccountManager::account_removed,+ this, [this](const QString&) { reload_accounts(); });+ connect(&trading::AccountManager::instance(), &trading::AccountManager::account_updated,+ this, [this](const QString&) { reload_accounts(); });+ }+ reload_accounts();+ refresh();+}++void ActionCenterScreen::hideEvent(QHideEvent* e) { QWidget::hideEvent(e); }++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/action_center/ActionCenterScreen.h b/fincept-qt/src/screens/action_center/ActionCenterScreen.hnew file mode 100644index 000000000..852ba169f--- /dev/null+++ b/fincept-qt/src/screens/action_center/ActionCenterScreen.h@@ -0,0 +1,73 @@+#pragma once+// Action Center Screen — semi-auto order approval UI (Phase 3 §2).+//+// Renders the pending/approved/rejected orders queued by ActionCenter and lets+// the user Approve / Reject them (per-row and in bulk). A per-account Auto ↔+// Semi-Auto mode toggle controls whether new orders are queued. The screen is+// a pure view (P6): it reads from and calls ActionCenter (the service); it+// never spawns Python, makes HTTP calls, or owns business logic.+//+// Live updates: subscribes to ActionCenter signals (pending_order_created,+// order_approved, order_rejected, stats_updated) to refresh the table and+// stats bar without polling — no QTimer is needed (D3).++#include "trading/ActionCenter.h"++#include <QComboBox>+#include <QHideEvent>+#include <QLabel>+#include <QShowEvent>+#include <QString>+#include <QTableWidget>+#include <QWidget>++class QPushButton;++namespace fincept::screens {++class ActionCenterScreen : public QWidget {+ Q_OBJECT+ public:+ explicit ActionCenterScreen(QWidget* parent = nullptr);++ protected:+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;++ private:+ void build_ui();+ void reload_accounts(); // refresh the account selector from AccountManager+ void refresh(); // reload table + stats for the active filter+ void refresh_stats();+ QString selected_account() const; // empty == all accounts++ // Slots wired to ActionCenter signals.+ void on_pending_created(const fincept::trading::PendingOrder& po);+ void on_order_approved(const QString& pending_id, const QString& broker_order_id);+ void on_order_rejected(const QString& pending_id, const QString& reason);+ void on_stats_updated(const QString& account_id);++ // Row actions.+ void approve_row(const QString& pending_id);+ void reject_row(const QString& pending_id);++ // ── Widgets ──────────────────────────────────────────────────────────────+ QComboBox* account_combo_ = nullptr;+ QComboBox* status_filter_ = nullptr;+ QComboBox* mode_combo_ = nullptr;++ QLabel* stat_pending_ = nullptr;+ QLabel* stat_approved_ = nullptr;+ QLabel* stat_rejected_ = nullptr;+ QLabel* stat_buy_ = nullptr;+ QLabel* stat_sell_ = nullptr;++ QTableWidget* table_ = nullptr;++ QPushButton* approve_all_btn_ = nullptr;+ QPushButton* reject_all_btn_ = nullptr;++ bool wired_ = false; // guard so we connect ActionCenter signals once+};++} // namespace fincept::screensdiff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cppindex 1405af492..4ba062385 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.cpp@@ -28,6 +28,7 @@#include <QHBoxLayout>#include <QHeaderView>#include <QJsonObject>+#include <QMessageBox>#include <QPushButton>#include <QStackedWidget>#include <QVBoxLayout>@@ -221,8 +222,46 @@ void CryptoBottomPanel::setup_positions_tab() {{"P&L", ColMode::Numeric, 11, 0, Qt::AlignRight | Qt::AlignVCenter},{"Lev", ColMode::Compact},});- auto* host = wrap_with_empty_state(positions_table_, positions_stack_, "No open positions.");- tabs_->addTab(host, "POSITIONS");++ // Wrap table + action bar in a container+ auto* container = new QWidget;+ auto* vlay = new QVBoxLayout(container);+ vlay->setContentsMargins(0, 0, 0, 0);+ vlay->setSpacing(0);++ // Action bar with Square Off All button+ auto* action_bar = new QWidget;+ action_bar->setObjectName("cryptoPositionsActionBar");+ auto* bar_layout = new QHBoxLayout(action_bar);+ bar_layout->setContentsMargins(10, 3, 10, 3);+ bar_layout->setSpacing(8);+ bar_layout->addStretch(1);++ close_all_btn_ = new QPushButton("SQUARE OFF ALL");+ close_all_btn_->setObjectName("cryptoCloseAllBtn");+ close_all_btn_->setCursor(Qt::PointingHandCursor);+ close_all_btn_->setStyleSheet(+ QString("QPushButton{background:rgba(220,38,38,0.12);color:%1;border:1px solid %2;"+ "padding:3px 12px;font-size:10px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"+ "QPushButton:hover{background:rgba(220,38,38,0.25);}")+ .arg(colors::NEGATIVE(), colors::NEGATIVE_DIM()));+ connect(close_all_btn_, &QPushButton::clicked, this, [this]() {+ if (account_id_.isEmpty())+ return;+ auto answer = QMessageBox::warning(this, "Square Off All Positions",+ "This will close ALL open positions.\n\nAre you sure?",+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (answer != QMessageBox::Yes)+ return;+ emit close_all_positions_requested(account_id_);+ });+ bar_layout->addWidget(close_all_btn_);+ vlay->addWidget(action_bar);++ auto* stack_host = wrap_with_empty_state(positions_table_, positions_stack_, "No open positions.");+ vlay->addWidget(stack_host, 1);++ tabs_->addTab(container, "POSITIONS");}void CryptoBottomPanel::setup_orders_tab() {@@ -235,8 +274,46 @@ void CryptoBottomPanel::setup_orders_tab() {{"Status", ColMode::Compact},{"", ColMode::Action, 0, 36}, // cancel button column});- auto* host = wrap_with_empty_state(orders_table_, orders_stack_, "No active orders.");- tabs_->addTab(host, "ORDERS");++ // Wrap table + action bar in a container+ auto* container = new QWidget;+ auto* vlay = new QVBoxLayout(container);+ vlay->setContentsMargins(0, 0, 0, 0);+ vlay->setSpacing(0);++ // Action bar with Cancel All button+ auto* action_bar = new QWidget;+ action_bar->setObjectName("cryptoOrdersActionBar");+ auto* bar_layout = new QHBoxLayout(action_bar);+ bar_layout->setContentsMargins(10, 3, 10, 3);+ bar_layout->setSpacing(8);+ bar_layout->addStretch(1);++ cancel_all_btn_ = new QPushButton("CANCEL ALL ORDERS");+ cancel_all_btn_->setObjectName("cryptoCancelAllBtn");+ cancel_all_btn_->setCursor(Qt::PointingHandCursor);+ cancel_all_btn_->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.12);color:%1;border:1px solid %2;"+ "padding:3px 12px;font-size:10px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"+ "QPushButton:hover{background:rgba(217,119,6,0.25);}")+ .arg(colors::AMBER(), colors::AMBER_DIM()));+ connect(cancel_all_btn_, &QPushButton::clicked, this, [this]() {+ if (account_id_.isEmpty())+ return;+ auto answer = QMessageBox::warning(this, "Cancel All Orders",+ "This will cancel ALL pending orders.\n\nAre you sure?",+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (answer != QMessageBox::Yes)+ return;+ emit cancel_all_orders_requested(account_id_);+ });+ bar_layout->addWidget(cancel_all_btn_);+ vlay->addWidget(action_bar);++ auto* stack_host = wrap_with_empty_state(orders_table_, orders_stack_, "No active orders.");+ vlay->addWidget(stack_host, 1);++ tabs_->addTab(container, "ORDERS");}void CryptoBottomPanel::setup_trades_tab() {@@ -580,6 +657,10 @@ void CryptoBottomPanel::set_mode(bool is_paper) {is_paper_ = is_paper;}+void CryptoBottomPanel::set_account_id(const QString& account_id) {+ account_id_ = account_id;+}+void CryptoBottomPanel::set_live_positions(const QJsonArray& positions) {const int n = positions.size();positions_table_->setUpdatesEnabled(false);diff --git a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.hindex dd0350930..fa99ef3ca 100644--- a/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h+++ b/fincept-qt/src/screens/crypto_trading/CryptoBottomPanel.h@@ -50,9 +50,13 @@ class CryptoBottomPanel : public QWidget {/// Call at every WS flush tick.void update_position_prices(const QHash<QString, double>& last_prices);+ void set_account_id(const QString& account_id);+signals:void cancel_order_requested(const QString& order_id);void close_position_requested(const QString& symbol);+ void cancel_all_orders_requested(const QString& account_id);+ void close_all_positions_requested(const QString& account_id);private:void setup_positions_tab();@@ -99,10 +103,15 @@ class CryptoBottomPanel : public QWidget {QLabel* live_equity_label_ = nullptr;QLabel* live_margin_label_ = nullptr;+ // Bulk action buttons+ class QPushButton* cancel_all_btn_ = nullptr;+ class QPushButton* close_all_btn_ = nullptr;+// New widgetsCryptoTimeSales* time_sales_ = nullptr;CryptoDepthChart* depth_chart_ = nullptr;+ QString account_id_;bool is_paper_ = true;};diff --git a/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp b/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cppindex 55d74aabe..9308c9dd9 100644--- a/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp+++ b/fincept-qt/src/screens/dashboard/canvas/WidgetRegistry.cpp@@ -5,6 +5,7 @@#include "screens/dashboard/widgets/CommoditiesWidget.h"#include "screens/dashboard/widgets/CryptoTickerWidget.h"#include "screens/dashboard/widgets/CryptoWidget.h"+#include "screens/dashboard/widgets/DashboardCandleWidget.h"#include "screens/dashboard/widgets/EconomicCalendarWidget.h"#include "screens/dashboard/widgets/ForexWidget.h"#include "screens/dashboard/widgets/GeopoliticsEventsWidget.h"@@ -84,6 +85,9 @@ WidgetRegistry::WidgetRegistry() {return new widgets::StockQuoteWidget(sym);}});+ register_widget({"candle_chart", QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Candle Chart"), QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Research"), QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Candlestick chart for a single ticker — set symbol via gear icon"), 5, 5, 3, 4,+ [](const QJsonObject& cfg) { return new widgets::DashboardCandleWidget(cfg); }});+register_widget({"screener", QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Stock Screener"), QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Research"), QT_TRANSLATE_NOOP("fincept::screens::WidgetRegistry", "Filter stocks by fundamentals and technicals"), 6, 5, 3,4, [](const QJsonObject&) { return new widgets::ScreenerWidget; }});diff --git a/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cppnew file mode 100644index 000000000..a4b7df1c3--- /dev/null+++ b/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.cpp@@ -0,0 +1,298 @@+#include "screens/dashboard/widgets/DashboardCandleWidget.h"++#include "datahub/DataHub.h"+#include "datahub/DataHubMetaTypes.h"+#include "ui/theme/Theme.h"++#include <QDateTime>+#include <QDialog>+#include <QDialogButtonBox>+#include <QFontMetrics>+#include <QFormLayout>+#include <QLineEdit>+#include <QPainter>++#include <algorithm>++namespace fincept::screens::widgets {++// ══════════════════════════════════════════════════════════════════════════════+// CandleCanvas — QPainter candlestick chart (candles + price axis + time axis)+// ══════════════════════════════════════════════════════════════════════════════++CandleCanvas::CandleCanvas(QWidget* parent) : QWidget(parent) {+ setMinimumHeight(120);+ setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);+}++void CandleCanvas::set_candles(const QVector<services::HistoryPoint>& candles) {+ candles_ = candles;+ dirty_ = true;+ update();+}++void CandleCanvas::clear() {+ candles_.clear();+ dirty_ = true;+ update();+}++void CandleCanvas::resizeEvent(QResizeEvent* e) {+ QWidget::resizeEvent(e);+ dirty_ = true;+}++void CandleCanvas::changeEvent(QEvent* event) {+ if (event->type() == QEvent::LanguageChange) {+ dirty_ = true;+ update();+ }+ QWidget::changeEvent(event);+}++void CandleCanvas::paintEvent(QPaintEvent*) {+ if (dirty_) {+ rebuild_cache();+ dirty_ = false;+ }+ 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(QColor(ui::colors::BG_BASE()));++ QPainter p(&cache_);+ p.setRenderHint(QPainter::Antialiasing, false);++ const int total = candles_.size();+ if (total == 0) {+ p.setPen(QColor(ui::colors::TEXT_SECONDARY()));+ p.setFont(QFont("Consolas", 10));+ p.drawText(cache_.rect(), Qt::AlignCenter, tr("Waiting for data..."));+ return;+ }++ const int start = qMax(0, total - MAX_VISIBLE);+ const int count = total - start;++ // Price range over the visible window.+ 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);+ }+ if (lo >= hi)+ return;++ const double margin = (hi - lo) * 0.06;+ lo -= margin;+ hi += margin;++ const int plot_w = W - PRICE_AXIS_W;+ const int plot_h = H - TIME_AXIS_H;+ if (plot_w <= 0 || plot_h <= 0)+ return;++ auto py = [&](double price) -> int {+ return static_cast<int>(plot_h - (price - lo) / (hi - lo) * plot_h);+ };++ // Grid lines.+ p.setPen(QPen(QColor(ui::colors::BORDER_DIM()), 1, Qt::DotLine));+ for (int g = 1; g < 6; ++g) {+ int gy = plot_h * g / 6;+ p.drawLine(0, gy, plot_w, gy);+ }++ // Candles.+ const double slot_w = static_cast<double>(plot_w) / count;+ const int body_w = qMax(1, static_cast<int>(slot_w * 0.65));+ const int half = body_w / 2;++ const QColor bull_color(ui::colors::POSITIVE.get());+ const QColor bear_color(ui::colors::NEGATIVE.get());+ const QColor wick_bull("#2a9d5c");+ const QColor wick_bear("#b83a3a");++ for (int i = 0; i < count; ++i) {+ const auto& c = candles_[start + i];+ const int cx = static_cast<int>((i + 0.5) * slot_w);+ const bool bull = c.close >= c.open;+ const QColor& col = bull ? bull_color : bear_color;+ const QColor& wcol = bull ? wick_bull : wick_bear;++ 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);++ p.setPen(QPen(wcol, 1));+ p.drawLine(cx, high_y, cx, body_top);+ p.drawLine(cx, body_bot, cx, low_y);++ p.fillRect(cx - half, body_top, body_w, body_h, col);+ }++ // Price axis (right).+ p.setPen(QPen(QColor(ui::colors::BORDER_DIM.get()), 1));+ p.drawLine(plot_w, 0, plot_w, plot_h);++ QFont lbl_font("Consolas", 8);+ p.setFont(lbl_font);+ QFontMetrics fm(lbl_font);+ p.setPen(QColor(ui::colors::TEXT_SECONDARY.get()));++ const bool is_large = hi > 1000;+ for (int g = 0; g <= 6; ++g) {+ double price = lo + (hi - lo) * g / 6.0;+ int gy = py(price);+ QString txt = is_large ? QString::number(price, 'f', 0) : QString::number(price, 'f', 2);+ p.drawText(plot_w + 4, gy + fm.ascent() / 2, txt);+ }++ // Time axis (bottom).+ p.setPen(QPen(QColor(ui::colors::BORDER_DIM.get()), 1));+ p.drawLine(0, plot_h, plot_w, plot_h);++ p.setPen(QColor(ui::colors::TEXT_SECONDARY.get()));+ const qint64 span_sec = candles_.last().timestamp - candles_.first().timestamp;+ const int label_step = qMax(1, count / 6);++ for (int i = 0; i < count; i += label_step) {+ const auto& c = candles_[start + i];+ QDateTime dt = QDateTime::fromSecsSinceEpoch(c.timestamp);+ QString label = span_sec > 365LL * 86400 ? dt.toString("MMM yy") : dt.toString("dd MMM");++ int lx = static_cast<int>((i + 0.5) * slot_w);+ int tw = fm.horizontalAdvance(label);+ if (lx - tw / 2 > 0 && lx + tw / 2 < plot_w)+ p.drawText(lx - tw / 2, plot_h + TIME_AXIS_H - 4, label);+ }++ // Last close reference line.+ double last_close = candles_.last().close;+ int ly = py(last_close);+ p.setPen(QPen(QColor(ui::colors::AMBER.get()), 1, Qt::DashLine));+ p.drawLine(0, ly, plot_w, ly);+}++// ══════════════════════════════════════════════════════════════════════════════+// DashboardCandleWidget+// ══════════════════════════════════════════════════════════════════════════════++namespace {+QString normalize_symbol(const QString& s) {+ const QString t = s.trimmed().toUpper();+ return t.isEmpty() ? QStringLiteral("AAPL") : t;+}+} // namespace++DashboardCandleWidget::DashboardCandleWidget(const QJsonObject& cfg, QWidget* parent)+ : BaseWidget(tr("CANDLE \xc2\xb7 %1").arg(normalize_symbol(cfg.value("symbol").toString())), parent),+ symbol_(normalize_symbol(cfg.value("symbol").toString())) {+ auto* vl = content_layout();+ vl->setContentsMargins(6, 4, 6, 4);+ vl->setSpacing(0);++ canvas_ = new CandleCanvas(this);+ vl->addWidget(canvas_, 1);++ set_configurable(true);+ connect(this, &BaseWidget::refresh_requested, this, &DashboardCandleWidget::refresh_data);++ set_loading(true);+}++QString DashboardCandleWidget::history_topic() const {+ return QStringLiteral("market:history:") + symbol_ + QStringLiteral(":1y:1d");+}++QJsonObject DashboardCandleWidget::config() const {+ QJsonObject o;+ o.insert("symbol", symbol_);+ return o;+}++void DashboardCandleWidget::apply_config(const QJsonObject& cfg) {+ const QString next = normalize_symbol(cfg.value("symbol").toString());+ if (next == symbol_)+ return;+ symbol_ = next;+ set_title(tr("CANDLE \xc2\xb7 %1").arg(symbol_));+ canvas_->clear();+ if (isVisible()) {+ set_loading(true);+ hub_resubscribe();+ }+}++QDialog* DashboardCandleWidget::make_config_dialog(QWidget* parent) {+ auto* dlg = new QDialog(parent);+ dlg->setWindowTitle(tr("Configure \xe2\x80\x94 Candle Chart"));+ auto* form = new QFormLayout(dlg);++ auto* edit = new QLineEdit(dlg);+ edit->setText(symbol_);+ edit->setPlaceholderText(tr("e.g. AAPL"));+ form->addRow(tr("Symbol"), edit);++ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dlg);+ form->addRow(buttons);++ connect(buttons, &QDialogButtonBox::accepted, dlg, [this, dlg, edit]() {+ QJsonObject cfg;+ cfg.insert("symbol", normalize_symbol(edit->text()));+ apply_config(cfg);+ emit config_changed(cfg);+ dlg->accept();+ });+ connect(buttons, &QDialogButtonBox::rejected, dlg, &QDialog::reject);+ return dlg;+}++void DashboardCandleWidget::showEvent(QShowEvent* e) {+ BaseWidget::showEvent(e);+ if (!hub_active_)+ hub_resubscribe();+}++void DashboardCandleWidget::hideEvent(QHideEvent* e) {+ BaseWidget::hideEvent(e);+ if (hub_active_) {+ datahub::DataHub::instance().unsubscribe(this);+ hub_active_ = false;+ }+}++void DashboardCandleWidget::hub_resubscribe() {+ auto& hub = datahub::DataHub::instance();+ hub.unsubscribe(this);+ hub.subscribe<QVector<services::HistoryPoint>>(+ this, history_topic(), [this](const QVector<services::HistoryPoint>& pts) {+ set_loading(false);+ canvas_->set_candles(pts);+ });+ hub_active_ = true;+}++void DashboardCandleWidget::refresh_data() {+ datahub::DataHub::instance().request(history_topic(), /*force=*/true);+}++void DashboardCandleWidget::retranslateUi() {+ BaseWidget::retranslateUi();+ set_title(tr("CANDLE \xc2\xb7 %1").arg(symbol_));+}++} // namespace fincept::screens::widgetsdiff --git a/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.h b/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.hnew file mode 100644index 000000000..3d2b04aab--- /dev/null+++ b/fincept-qt/src/screens/dashboard/widgets/DashboardCandleWidget.h@@ -0,0 +1,69 @@+#pragma once+#include "screens/dashboard/widgets/BaseWidget.h"+#include "services/markets/MarketDataService.h"++#include <QPixmap>+#include <QVector>++namespace fincept::screens::widgets {++/// Lightweight QPainter candlestick canvas — candles + price axis + time axis.+/// Ported from ResearchCandleCanvas (equity_research) but consumes+/// `services::HistoryPoint` directly and lives in the dashboard widgets+/// namespace so DashboardCandleWidget stays self-contained. Caches its render+/// to a QPixmap and only rebuilds on set_candles()/resize (CLAUDE.md P9).+class CandleCanvas : public QWidget {+ Q_OBJECT+ public:+ explicit CandleCanvas(QWidget* parent = nullptr);+ void set_candles(const QVector<services::HistoryPoint>& candles);+ void clear();++ protected:+ void paintEvent(QPaintEvent*) override;+ void resizeEvent(QResizeEvent*) override;+ void changeEvent(QEvent* event) override;++ private:+ void rebuild_cache();++ QVector<services::HistoryPoint> candles_;+ QPixmap cache_;+ bool dirty_ = true;++ static constexpr int MAX_VISIBLE = 260;+ static constexpr int PRICE_AXIS_W = 64;+ static constexpr int TIME_AXIS_H = 20;+};++/// Dashboard tile showing a candlestick chart for a single ticker.+///+/// Pure DataHub consumer: subscribes to+/// `market:history:<symbol_>:1y:1d` (produced by MarketDataService). Symbol is+/// user-configurable via the gear-icon dialog and persists with the layout.+/// Visibility-driven subscribe/unsubscribe per CLAUDE.md P3 / D3.+class DashboardCandleWidget : public BaseWidget {+ Q_OBJECT+ public:+ explicit DashboardCandleWidget(const QJsonObject& cfg = {}, QWidget* parent = nullptr);++ QJsonObject config() const override;+ void apply_config(const QJsonObject& cfg) override;++ protected:+ QDialog* make_config_dialog(QWidget* parent) override;+ void showEvent(QShowEvent* e) override;+ void hideEvent(QHideEvent* e) override;+ void retranslateUi() override;++ private:+ QString history_topic() const;+ void hub_resubscribe();+ void refresh_data();++ QString symbol_;+ CandleCanvas* canvas_ = nullptr;+ bool hub_active_ = false;+};++} // namespace fincept::screens::widgetsdiff --git a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cppindex fbb032f75..698415262 100644--- a/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp+++ b/fincept-qt/src/screens/equity_research/EquityOverviewTab.cpp@@ -743,21 +743,6 @@ void EquityOverviewTab::rebuild_chart(const QVector<services::equity::Candle>& cobj[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;}diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cppindex 7ed012705..95781ba91 100644--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp@@ -9,9 +9,12 @@#include <QHBoxLayout>#include <QHeaderView>#include <QLineEdit>+#include <QMessageBox>+#include <QPointer>#include <QPushButton>#include <QScrollBar>#include <QVBoxLayout>+#include <QtConcurrent>namespace fincept::screens::equity {@@ -51,6 +54,41 @@ QTableWidgetItem* EquityBottomPanel::ensure_item(QTableWidget* table, int row, i// ── Positions Tab ──────────────────────────────────────────────────────────void EquityBottomPanel::setup_positions_tab() {+ auto* container = new QWidget;+ auto* vlay = new QVBoxLayout(container);+ vlay->setContentsMargins(0, 0, 0, 0);+ vlay->setSpacing(0);++ // Action bar with Square Off All button+ auto* action_bar = new QWidget;+ action_bar->setObjectName("eqPositionsActionBar");+ action_bar->setStyleSheet(QString("#eqPositionsActionBar{background:%1;border-bottom:1px solid %2;}")+ .arg(fincept::ui::colors::PANEL(), fincept::ui::colors::BORDER()));+ auto* bar_layout = new QHBoxLayout(action_bar);+ bar_layout->setContentsMargins(12, 4, 12, 4);+ bar_layout->setSpacing(8);+ bar_layout->addStretch(1);++ close_all_btn_ = new QPushButton("SQUARE OFF ALL");+ close_all_btn_->setCursor(Qt::PointingHandCursor);+ close_all_btn_->setStyleSheet(+ QString("QPushButton{background:rgba(220,38,38,0.12);color:%1;border:1px solid %2;"+ "padding:4px 14px;font-size:11px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"+ "QPushButton:hover{background:rgba(220,38,38,0.25);}")+ .arg(fincept::ui::colors::NEGATIVE(), fincept::ui::colors::NEGATIVE_DIM()));+ connect(close_all_btn_, &QPushButton::clicked, this, [this]() {+ if (account_id_.isEmpty())+ return;+ auto answer = QMessageBox::warning(this, "Square Off All Positions",+ "This will close ALL open positions.\n\nAre you sure?",+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (answer != QMessageBox::Yes)+ return;+ emit close_all_positions_requested(account_id_);+ });+ bar_layout->addWidget(close_all_btn_);+ vlay->addWidget(action_bar);+positions_table_ = new QTableWidget;positions_table_->setObjectName("eqTable");positions_table_->setColumnCount(8);@@ -62,7 +100,9 @@ void EquityBottomPanel::setup_positions_tab() {positions_table_->setShowGrid(false);positions_table_->horizontalHeader()->setStretchLastSection(true);positions_table_->verticalHeader()->setDefaultSectionSize(22);- tabs_->addTab(positions_table_, "POSITIONS");+ vlay->addWidget(positions_table_, 1);++ tabs_->addTab(container, "POSITIONS");}// ── Holdings Tab ───────────────────────────────────────────────────────────@@ -150,6 +190,41 @@ void EquityBottomPanel::setup_holdings_tab() {// ── Orders Tab ─────────────────────────────────────────────────────────────void EquityBottomPanel::setup_orders_tab() {+ auto* container = new QWidget;+ auto* vlay = new QVBoxLayout(container);+ vlay->setContentsMargins(0, 0, 0, 0);+ vlay->setSpacing(0);++ // Action bar with Cancel All button+ auto* action_bar = new QWidget;+ action_bar->setObjectName("eqOrdersActionBar");+ action_bar->setStyleSheet(QString("#eqOrdersActionBar{background:%1;border-bottom:1px solid %2;}")+ .arg(fincept::ui::colors::PANEL(), fincept::ui::colors::BORDER()));+ auto* bar_layout = new QHBoxLayout(action_bar);+ bar_layout->setContentsMargins(12, 4, 12, 4);+ bar_layout->setSpacing(8);+ bar_layout->addStretch(1);++ cancel_all_btn_ = new QPushButton("CANCEL ALL ORDERS");+ cancel_all_btn_->setCursor(Qt::PointingHandCursor);+ cancel_all_btn_->setStyleSheet(+ QString("QPushButton{background:rgba(217,119,6,0.12);color:%1;border:1px solid %2;"+ "padding:4px 14px;font-size:11px;font-weight:700;letter-spacing:0.5px;border-radius:2px;}"+ "QPushButton:hover{background:rgba(217,119,6,0.25);}")+ .arg(fincept::ui::colors::AMBER(), fincept::ui::colors::AMBER_DIM()));+ connect(cancel_all_btn_, &QPushButton::clicked, this, [this]() {+ if (account_id_.isEmpty())+ return;+ auto answer = QMessageBox::warning(this, "Cancel All Orders",+ "This will cancel ALL pending orders.\n\nAre you sure?",+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);+ if (answer != QMessageBox::Yes)+ return;+ emit cancel_all_orders_requested(account_id_);+ });+ bar_layout->addWidget(cancel_all_btn_);+ vlay->addWidget(action_bar);+orders_table_ = new QTableWidget;orders_table_->setObjectName("eqTable");orders_table_->setColumnCount(9);@@ -161,7 +236,9 @@ void EquityBottomPanel::setup_orders_tab() {orders_table_->setShowGrid(false);orders_table_->horizontalHeader()->setStretchLastSection(true);orders_table_->verticalHeader()->setDefaultSectionSize(22);- tabs_->addTab(orders_table_, "ORDERS");+ vlay->addWidget(orders_table_, 1);++ tabs_->addTab(container, "ORDERS");}// ── Funds Tab ──────────────────────────────────────────────────────────────@@ -227,6 +304,10 @@ void EquityBottomPanel::set_mode(bool is_paper) {is_paper_ = is_paper;}+void EquityBottomPanel::set_account_id(const QString& account_id) {+ account_id_ = account_id;+}+void EquityBottomPanel::set_paper_positions(const QVector<trading::PtPosition>& positions) {positions_table_->setRowCount(positions.size());for (int i = 0; i < positions.size(); ++i) {diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.hindex 889a731ee..b812ea637 100644--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.h@@ -39,10 +39,14 @@ class EquityBottomPanel : public QWidget {void set_mode(bool is_paper);+ void set_account_id(const QString& account_id);+signals:void cancel_order_requested(const QString& order_id);void modify_order_requested(const QString& order_id, double new_qty, double new_price);void import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);+ void cancel_all_orders_requested(const QString& account_id);+ void close_all_positions_requested(const QString& account_id);private:void setup_positions_tab();@@ -87,6 +91,11 @@ class EquityBottomPanel : public QWidget {// Stats labelsQLabel* stat_values_[5] = {};+ // Bulk action buttons+ class QPushButton* cancel_all_btn_ = nullptr;+ class QPushButton* close_all_btn_ = nullptr;++ QString account_id_;bool is_paper_ = true;};diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cppindex b4c589c55..528bbaeff 100644--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp@@ -4,6 +4,7 @@#include "core/logging/Logger.h"#include "screens/equity_trading/EquityTypes.h"#include "trading/BrokerRegistry.h"+#include "trading/OptionsStrategyBuilder.h"#include "ui/theme/Theme.h"#include <QHBoxLayout>@@ -206,6 +207,101 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {advanced_toggle_->setText(show ? "- ADVANCED" : "+ ADVANCED");});+ // ---- Options Strategy section (collapsible, mirrors advanced_section_) ----+ strategy_toggle_ = new QPushButton("+ OPTIONS STRATEGY");+ strategy_toggle_->setObjectName("eqAdvToggle");+ strategy_toggle_->setCursor(Qt::PointingHandCursor);+ strategy_toggle_->setFixedHeight(18);+ form->addWidget(strategy_toggle_);++ strategy_section_ = new QWidget(this);+ strategy_section_->setVisible(false);+ auto* strat_layout = new QVBoxLayout(strategy_section_);+ strat_layout->setContentsMargins(0, 0, 0, 0);+ strat_layout->setSpacing(4);++ auto* strat_lbl = new QLabel("STRATEGY");+ strat_lbl->setObjectName("eqOeLabel");+ strat_layout->addWidget(strat_lbl);++ strategy_combo_ = new QComboBox;+ strategy_combo_->setObjectName("eqOeCombo");+ strategy_combo_->addItems({"None", "Long Straddle", "Short Straddle", "Long Strangle", "Iron Condor",+ "Bull Call Spread", "Bear Put Spread"});+ strategy_combo_->setFixedHeight(26);+ strat_layout->addWidget(strategy_combo_);++ auto* strat_strike_lbl = new QLabel("ATM STRIKE");+ strat_strike_lbl->setObjectName("eqOeLabel");+ strat_layout->addWidget(strat_strike_lbl);+ strat_strike_edit_ = new QLineEdit;+ strat_strike_edit_->setObjectName("eqOeInput");+ strat_strike_edit_->setPlaceholderText("e.g. 22500");+ strat_strike_edit_->setFixedHeight(26);+ strat_layout->addWidget(strat_strike_edit_);++ auto* strat_expiry_lbl = new QLabel("EXPIRY (YYYY-MM-DD)");+ strat_expiry_lbl->setObjectName("eqOeLabel");+ strat_layout->addWidget(strat_expiry_lbl);+ strat_expiry_edit_ = new QLineEdit;+ strat_expiry_edit_->setObjectName("eqOeInput");+ strat_expiry_edit_->setPlaceholderText("2025-03-28");+ strat_expiry_edit_->setFixedHeight(26);+ strat_layout->addWidget(strat_expiry_edit_);++ auto* strat_lot_lbl = new QLabel("LOT SIZE");+ strat_lot_lbl->setObjectName("eqOeLabel");+ strat_layout->addWidget(strat_lot_lbl);+ strat_lot_edit_ = new QLineEdit;+ strat_lot_edit_->setObjectName("eqOeInput");+ strat_lot_edit_->setText("1");+ strat_lot_edit_->setPlaceholderText("1");+ strat_lot_edit_->setFixedHeight(26);+ strat_layout->addWidget(strat_lot_edit_);++ auto* strat_width_lbl = new QLabel("WIDTH (strangle / condor / spreads)");+ strat_width_lbl->setObjectName("eqOeLabel");+ strat_layout->addWidget(strat_width_lbl);+ strat_width_edit_ = new QLineEdit;+ strat_width_edit_->setObjectName("eqOeInput");+ strat_width_edit_->setPlaceholderText("e.g. 200");+ strat_width_edit_->setFixedHeight(26);+ strat_layout->addWidget(strat_width_edit_);++ auto* preview_lbl = new QLabel("LEGS");+ preview_lbl->setObjectName("eqOeLabel");+ strat_layout->addWidget(preview_lbl);++ strategy_preview_ = new QLabel("Select a strategy");+ strategy_preview_->setObjectName("eqOeBrokerage");+ strategy_preview_->setStyleSheet(QString("color: %1; font-size: 10px;").arg(colors::TEXT_TERTIARY()));+ strategy_preview_->setWordWrap(true);+ strategy_preview_->setTextInteractionFlags(Qt::TextSelectableByMouse);+ strat_layout->addWidget(strategy_preview_);++ place_strategy_btn_ = new QPushButton("PLACE STRATEGY");+ place_strategy_btn_->setObjectName("eqBuySubmit");+ place_strategy_btn_->setFixedHeight(30);+ place_strategy_btn_->setCursor(Qt::PointingHandCursor);+ connect(place_strategy_btn_, &QPushButton::clicked, this, &EquityOrderEntry::on_place_strategy);+ strat_layout->addWidget(place_strategy_btn_);++ form->addWidget(strategy_section_);++ connect(strategy_toggle_, &QPushButton::clicked, this, [this]() {+ const bool show = !strategy_section_->isVisible();+ strategy_section_->setVisible(show);+ strategy_toggle_->setText(show ? "- OPTIONS STRATEGY" : "+ OPTIONS STRATEGY");+ });++ // Recompute preview whenever the strategy or any input changes+ connect(strategy_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,+ [this]() { refresh_strategy_preview(); });+ connect(strat_strike_edit_, &QLineEdit::textChanged, this, [this]() { refresh_strategy_preview(); });+ connect(strat_expiry_edit_, &QLineEdit::textChanged, this, [this]() { refresh_strategy_preview(); });+ connect(strat_lot_edit_, &QLineEdit::textChanged, this, [this]() { refresh_strategy_preview(); });+ connect(strat_width_edit_, &QLineEdit::textChanged, this, [this]() { refresh_strategy_preview(); });+// Cost previewcost_label_ = new QLabel("Est: --");cost_label_->setObjectName("eqOeCost");@@ -510,4 +606,117 @@ void EquityOrderEntry::fetch_margin_async() {});}+bool EquityOrderEntry::build_strategy(trading::OptionsStrategy& out) const {+ const int idx = strategy_combo_ ? strategy_combo_->currentIndex() : 0;+ if (idx <= 0) // "None"+ return false;++ const QString underlying = current_symbol_;+ const QString expiry = strat_expiry_edit_->text().trimmed();+ const double atm = strat_strike_edit_->text().toDouble();+ double lot = strat_lot_edit_->text().toDouble();+ if (lot <= 0)+ lot = 1;+ const double width = strat_width_edit_->text().toDouble();++ if (expiry.isEmpty() || atm <= 0)+ return false;++ using B = trading::OptionsStrategyBuilder;+ using Side = trading::OrderSide;++ switch (idx) {+ case 1: // Long Straddle+ out = B::straddle(underlying, expiry, atm, lot, Side::Buy);+ return true;+ case 2: // Short Straddle+ out = B::straddle(underlying, expiry, atm, lot, Side::Sell);+ return true;+ case 3: // Long Strangle+ if (width <= 0)+ return false;+ out = B::strangle(underlying, expiry, atm, width, lot, Side::Buy);+ return true;+ case 4: // Iron Condor — near_width = width, far_width = 2 * width+ if (width <= 0)+ return false;+ out = B::iron_condor(underlying, expiry, atm, width, width * 2.0, lot);+ return true;+ case 5: // Bull Call Spread — buy ATM CE, sell (ATM + width) CE+ if (width <= 0)+ return false;+ out = B::bull_call_spread(underlying, expiry, atm, atm + width, lot);+ return true;+ case 6: // Bear Put Spread — buy ATM PE, sell (ATM - width) PE+ if (width <= 0)+ return false;+ out = B::bear_put_spread(underlying, expiry, atm, atm - width, lot);+ return true;+ default:+ return false;+ }+}++void EquityOrderEntry::refresh_strategy_preview() {+ if (!strategy_preview_)+ return;++ const int idx = strategy_combo_ ? strategy_combo_->currentIndex() : 0;+ if (idx <= 0) {+ strategy_preview_->setText("Select a strategy");+ return;+ }++ trading::OptionsStrategy strat;+ if (!build_strategy(strat)) {+ strategy_preview_->setText("Enter expiry, ATM strike (and width where required).");+ return;+ }++ QStringList lines;+ if (!strat.name.isEmpty())+ lines << strat.name;+ for (const auto& leg : strat.legs) {+ // SIDE qty SYMBOL @strike type+ lines << QString("%1 %2 %3 @%4 %5")+ .arg(QString(trading::order_side_str(leg.side)).toUpper())+ .arg(leg.quantity, 0, 'f', 0)+ .arg(leg.symbol)+ .arg(leg.strike, 0, 'f', 0)+ .arg(leg.option_type);+ }++ QStringList metrics;+ if (strat.max_profit != 0.0)+ metrics << QString("Max P: %1").arg(strat.max_profit, 0, 'f', 2);+ if (strat.max_loss != 0.0)+ metrics << QString("Max L: %1").arg(strat.max_loss, 0, 'f', 2);+ if (strat.breakeven_lower != 0.0)+ metrics << QString("BE-: %1").arg(strat.breakeven_lower, 0, 'f', 2);+ if (strat.breakeven_upper != 0.0)+ metrics << QString("BE+: %1").arg(strat.breakeven_upper, 0, 'f', 2);+ if (!metrics.isEmpty())+ lines << metrics.join(" ");++ strategy_preview_->setText(lines.join("\n"));+}++void EquityOrderEntry::on_place_strategy() {+ trading::OptionsStrategy strat;+ if (!build_strategy(strat)) {+ status_label_->setText("Select a strategy and enter valid expiry / strike / width");+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));+ return;+ }++ // Product type from profile-driven combo (same mapping as on_submit)+ trading::ProductType product = trading::ProductType::Intraday;+ const int prod_idx = product_combo_->currentIndex();+ if (!product_types_.isEmpty() && prod_idx >= 0 && prod_idx < product_types_.size())+ product = product_types_[prod_idx].value;++ trading::BasketOrderRequest basket = trading::OptionsStrategyBuilder::to_basket_order(strat, product);+ emit strategy_order_submitted(basket);+}+} // namespace fincept::screens::equitydiff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.hindex 37ee686f3..2a0d1b081 100644--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h@@ -2,6 +2,7 @@// Equity Order Entry — BUY/SELL form configurable per broker profile#include "trading/BrokerInterface.h"+#include "trading/OptionsStrategyBuilder.h"#include "trading/TradingTypes.h"#include <QComboBox>@@ -34,15 +35,21 @@ class EquityOrderEntry : public QWidget {signals:void order_submitted(const trading::UnifiedOrder& order);void broadcast_requested(const trading::UnifiedOrder& order);+ void strategy_order_submitted(const trading::BasketOrderRequest& basket);private slots:void on_submit();+ void on_place_strategy();private:void update_cost_preview();void set_buy_side(bool is_buy);void set_order_type(int idx);+ // Options strategy helpers+ bool build_strategy(trading::OptionsStrategy& out) const; // returns false when strategy == None or inputs invalid+ void refresh_strategy_preview();+// Side tabsQPushButton* buy_tab_ = nullptr;QPushButton* sell_tab_ = nullptr;@@ -71,6 +78,17 @@ class EquityOrderEntry : public QWidget {QWidget* advanced_section_ = nullptr;QPushButton* advanced_toggle_ = nullptr;+ // Options strategy section (collapsible, like advanced_section_)+ QPushButton* strategy_toggle_ = nullptr;+ QWidget* strategy_section_ = nullptr;+ QComboBox* strategy_combo_ = nullptr;+ QLineEdit* strat_strike_edit_ = nullptr; // ATM strike+ QLineEdit* strat_expiry_edit_ = nullptr; // YYYY-MM-DD+ QLineEdit* strat_lot_edit_ = nullptr; // lot size (default 1)+ QLineEdit* strat_width_edit_ = nullptr; // width for strangle/condor/spreads+ QLabel* strategy_preview_ = nullptr;+ QPushButton* place_strategy_btn_ = nullptr;+// LabelsQLabel* balance_label_ = nullptr;QLabel* market_price_label_ = nullptr;diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cppindex 30fa9f7dd..48e0ba4c0 100644--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp@@ -23,6 +23,7 @@#include "services/portfolio/PortfolioService.h"#include "storage/repositories/SettingsRepository.h"#include "trading/AccountManager.h"+#include "trading/ActionCenter.h"#include "trading/BrokerRegistry.h"#include "trading/DataStreamManager.h"#include "trading/OrderMatcher.h"@@ -390,6 +391,22 @@ void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {// Route to live broker via account-aware UnifiedTrading// Safety: capture account_id by value at click time (immutable per order lifecycle)const QString acct_id = focused_account_id_;++ // Action Center pre-gate (Phase 3 §2): in Semi-Auto mode, queue the+ // order for manual approval instead of sending it to the broker. The+ // queue decision lives here in the caller/screen layer — place_order()+ // itself never consults ActionCenter (no recursion on approval).+ if (ActionCenter::instance().should_queue(acct_id, "placeorder")) {+ const QString pending_id = ActionCenter::instance().queue_order(+ acct_id, "placeorder", ActionCenter::serialize_unified_order(order));+ if (!pending_id.isEmpty())+ order_entry_->show_order_status(+ QStringLiteral("Order queued for approval in Action Center"), true);+ else+ order_entry_->show_order_status(QStringLiteral("Failed to queue order"), false);+ return;+ }+QPointer<EquityTradingScreen> self = this;auto order_copy = order;(void)QtConcurrent::run([self, acct_id, order_copy]() {diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen.cppindex ab71f6f04..dee29a027 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen.cpp+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.cpp@@ -9,6 +9,7 @@#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"+#include "services/maritime/GeocodingService.h"#include "services/maritime/MaritimeService.h"#include "services/maritime/PortsCatalog.h"#include "ui/theme/Theme.h"@@ -101,6 +102,10 @@ void MaritimeScreen::connect_service() {auto& ports = PortsCatalog::instance();connect(&ports, &PortsCatalog::ports_found, this, &MaritimeScreen::on_ports_found);connect(&ports, &PortsCatalog::error_occurred, this, &MaritimeScreen::on_ports_error);++ auto& geo = GeocodingService::instance();+ connect(&geo, &GeocodingService::places_found, this, &MaritimeScreen::on_places_found);+ connect(&geo, &GeocodingService::error_occurred, this, &MaritimeScreen::on_places_error);}// ── Theme apply (called on construction + theme_changed) ─────────────────────diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen.h b/fincept-qt/src/screens/maritime/MaritimeScreen.hindex ec2987443..6edd62d48 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen.h+++ b/fincept-qt/src/screens/maritime/MaritimeScreen.h@@ -1,6 +1,7 @@// src/screens/maritime/MaritimeScreen.h#pragma once#include "screens/common/IStatefulScreen.h"+#include "services/maritime/GeocodingTypes.h"#include "services/maritime/MaritimePortTypes.h"#include "services/maritime/MaritimeTypes.h"#include "ui/theme/Theme.h"@@ -52,6 +53,8 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {void on_route_selected(int row);void on_ports_found(QVector<services::maritime::PortRecord> ports, QString context);void on_ports_error(const QString& context, const QString& message);+ void on_places_found(QVector<services::maritime::GeoPlace> places, QString context);+ void on_places_error(const QString& context, const QString& message);private:void build_ui();@@ -72,6 +75,17 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {/// so the map fans out instead of clustering on whatever bbox the user/// last typed.void load_global_sample();+ /// Fill the area-search spinners from a bbox and issue a vessel+ /// area-search for it. Shared by the place-search selection, the raw+ /// bbox button, and (later) the map-draw tool so they all funnel through+ /// one path.+ void run_area_search(double min_lat, double max_lat, double min_lng, double max_lng,+ bool filter_to_shapes = false);+ /// Called when the user finalizes / clears drawn shapes on the map.+ /// Computes the union bbox of all shapes and loads vessels for it;+ /// on_vessels_loaded then filters the result to vessels actually inside+ /// any drawn shape. No shapes left = no-op.+ void on_shapes_changed();void show_map_loading(const QString& msg);void hide_map_loading();@@ -110,7 +124,17 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {QLabel* sr_from_ = nullptr;QLabel* sr_to_ = nullptr;- // Right panel - area search+ // Right panel - place search (Nominatim geocoder). Primary area-input UX:+ // user types a place name, picks a suggestion, its bbox fills the spinners+ // and triggers a vessel area-search.+ QLineEdit* place_query_edit_ = nullptr;+ QTableWidget* place_table_ = nullptr;+ QLabel* place_status_ = nullptr;+ QVector<services::maritime::GeoPlace> place_results_;++ // Right panel - area search (raw lat/long). Kept behind an "Advanced"+ // expander; place search / map-draw are the primary inputs now.+ QWidget* advanced_area_box_ = nullptr;QDoubleSpinBox* area_min_lat_ = nullptr;QDoubleSpinBox* area_max_lat_ = nullptr;QDoubleSpinBox* area_min_lng_ = nullptr;@@ -141,6 +165,9 @@ class MaritimeScreen : public QWidget, public IStatefulScreen {/// Set by load_global_sample(); consumed by on_vessels_loaded so that/// the next batch is spatially downsampled to ~200 globally-spread pins.bool pending_global_sample_ = false;+ /// Set by on_shapes_changed(); consumed by on_vessels_loaded so the next+ /// batch is filtered to vessels lying inside the user's drawn shapes.+ bool filter_to_shapes_ = false;// DataQVector<services::maritime::TradeRoute> routes_;diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cppindex 085f4fa5e..4d6239da8 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_Handlers.cpp@@ -38,37 +38,122 @@ using namespace fincept::screens::maritime_internal;void MaritimeScreen::load_global_sample() {// World bbox — the API caps at ±90 lat / ±180 lng, but stays well-behaved- // with these slightly inset values. Returns ~45k vessels worldwide today;- // the per-cell downsampler in on_vessels_loaded reduces that to ~200 pins- // distributed across a 10x10 lat/lng grid so the map fills out instead of- // clumping in the busiest shipping lanes.+ // with these slightly inset values. Worldwide this matches ~45k vessels;+ // we ask the server for a bounded slice (`limit`) instead of transferring+ // them all, then the per-cell downsampler in on_vessels_loaded reduces+ // that to ~100 pins across a 10x10 lat/lng grid so the map fills out+ // instead of clumping in the busiest shipping lanes.AreaSearchParams params;params.min_lat = -89.0;params.max_lat = 89.0;params.min_lng = -179.0;params.max_lng = 179.0;+ // Request more than the 100 we ultimately show so the grid downsampler has+ // a geographically diverse pool to spread across — the API returns busy+ // lanes first, so a tight server cap would cluster. ~22x less than 45k.+ params.limit = 2000;set_status("LOADING GLOBAL...", ui::colors::WARNING);pending_global_sample_ = true;+ filter_to_shapes_ = false; // global view is never shape-filteredshow_map_loading(QStringLiteral("LOADING GLOBAL VESSELS"));MaritimeService::instance().search_vessels_by_area(params);}void MaritimeScreen::on_load_vessels() {- AreaSearchParams params;- if (area_min_lat_) params.min_lat = area_min_lat_->value();- if (area_max_lat_) params.max_lat = area_max_lat_->value();- if (area_min_lng_) params.min_lng = area_min_lng_->value();- if (area_max_lng_) params.max_lng = area_max_lng_->value();- if (params.max_lat <= params.min_lat || params.max_lng <= params.min_lng) {+ if (!area_min_lat_ || !area_max_lat_ || !area_min_lng_ || !area_max_lng_)+ return;+ run_area_search(area_min_lat_->value(), area_max_lat_->value(),+ area_min_lng_->value(), area_max_lng_->value());+}++void MaritimeScreen::run_area_search(double min_lat, double max_lat, double min_lng, double max_lng,+ bool filter_to_shapes) {+ if (max_lat <= min_lat || max_lng <= min_lng) {set_status("INVALID BBOX", ui::colors::WARNING);return;}- set_status("LOADING...", ui::colors::WARNING);- pending_global_sample_ = false; // explicit bbox load — show as-is- show_map_loading(QStringLiteral("LOADING VESSELS"));+ // Filter the next result to drawn shapes only when this search was driven+ // by the draw tool; place / bbox searches show the whole bbox.+ filter_to_shapes_ = filter_to_shapes;+ // Reflect the bbox in the advanced spinners so the user can see / tweak+ // what a place / draw selection resolved to.+ if (area_min_lat_) area_min_lat_->setValue(min_lat);+ if (area_max_lat_) area_max_lat_->setValue(max_lat);+ if (area_min_lng_) area_min_lng_->setValue(min_lng);+ if (area_max_lng_) area_max_lng_->setValue(max_lng);++ AreaSearchParams params;+ params.min_lat = min_lat;+ params.max_lat = max_lat;+ params.min_lng = min_lng;+ params.max_lng = max_lng;+ // Cap the working set like the global view does — a large place bbox+ // (e.g. an ocean) can still match thousands of vessels.+ params.limit = 2000;+ set_status("SEARCHING...", ui::colors::WARNING);+ pending_global_sample_ = false;+ show_map_loading(QStringLiteral("SEARCHING AREA"));MaritimeService::instance().search_vessels_by_area(params);}+void MaritimeScreen::on_places_found(QVector<services::maritime::GeoPlace> places, QString context) {+ Q_UNUSED(context);+ place_results_ = places;+ if (!place_table_) return;++ place_table_->setSortingEnabled(false);+ place_table_->setRowCount(places.size());+ for (int i = 0; i < places.size(); ++i) {+ const auto& p = places[i];+ auto* name = new QTableWidgetItem(p.display_name);+ name->setToolTip(QString("%1\nbbox: %2,%3 → %4,%5")+ .arg(p.display_name)+ .arg(p.min_lat, 0, 'f', 3).arg(p.min_lng, 0, 'f', 3)+ .arg(p.max_lat, 0, 'f', 3).arg(p.max_lng, 0, 'f', 3));+ place_table_->setItem(i, 0, name);+ place_table_->setItem(i, 1, new QTableWidgetItem(p.type));+ }+ place_table_->setSortingEnabled(true);+ place_table_->resizeColumnsToContents();++ if (place_status_) {+ if (places.isEmpty())+ place_status_->setText("No places found.");+ else+ place_status_->setText(QString("%1 result%2 — click a row to load vessels.")+ .arg(places.size())+ .arg(places.size() == 1 ? "" : "s"));+ }+}++void MaritimeScreen::on_shapes_changed() {+ if (!map_widget_) return;+ const auto& shapes = map_widget_->shapes();+ if (shapes.isEmpty()) {+ // All shapes cleared — drop the shape filter. Leave the current+ // vessel set as-is (don't auto-reload); user can pick another action.+ filter_to_shapes_ = false;+ return;+ }+ // Union bbox over all drawn shapes (each shape carries its own bbox,+ // including circles which store their bounding box).+ double mn_lat = 90.0, mx_lat = -90.0, mn_lng = 180.0, mx_lng = -180.0;+ for (const auto& s : shapes) {+ mn_lat = std::min(mn_lat, s.min_lat);+ mx_lat = std::max(mx_lat, s.max_lat);+ mn_lng = std::min(mn_lng, s.min_lng);+ mx_lng = std::max(mx_lng, s.max_lng);+ }+ run_area_search(mn_lat, mx_lat, mn_lng, mx_lng, /*filter_to_shapes=*/true);+}++void MaritimeScreen::on_places_error(const QString& context, const QString& message) {+ Q_UNUSED(context);+ LOG_WARN("Maritime", QString("Place search failed: %1").arg(message));+ if (place_status_)+ place_status_->setText("Search failed: " + message);+}+void MaritimeScreen::on_search_vessel() {auto imo = imo_edit_->text().trimmed();if (imo.isEmpty())@@ -90,7 +175,7 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {pending_global_sample_ = false;constexpr int kBins = 10;constexpr int kPerCell = 2;- constexpr int kTargetCount = 200;+ constexpr int kTargetCount = 100;QHash<int, QVector<int>> by_cell; // cell index → vessel indicesfor (int i = 0; i < page.vessels.size(); ++i) {const auto& v = page.vessels[i];@@ -113,10 +198,30 @@ void MaritimeScreen::on_vessels_loaded(VesselsPage page) {page.total_count = picked.size();}- // Render limit — area-search can return 14k+ rows. Pin/render the top- // (newest-first) batch to keep the UI responsive; full count still- // shown in the status badge.- static constexpr int kRenderLimit = 500;+ // Shape filter — when the user drew areas, the API was queried with the+ // union bbox; narrow the result to vessels actually inside one of the+ // drawn shapes (true circle / multi-shape selection). total_count is reset+ // to the in-shape count so the badge reflects what's shown.+ if (filter_to_shapes_ && map_widget_ && !map_widget_->shapes().isEmpty()) {+ const auto& shapes = map_widget_->shapes();+ QVector<VesselData> in_shape;+ in_shape.reserve(page.vessels.size());+ for (const auto& v : page.vessels) {+ for (const auto& s : shapes) {+ if (s.contains(v.latitude, v.longitude)) {+ in_shape.append(v);+ break;+ }+ }+ }+ page.vessels = in_shape;+ page.total_count = in_shape.size();+ }++ // Render limit — area-search can still return a large set for a tight+ // user bbox. Pin/render the top (newest-first) batch to keep the UI+ // responsive; full count still shown in the status badge.+ static constexpr int kRenderLimit = 100;const int render_n = qMin(page.vessels.size(), kRenderLimit);vessels_table_->setSortingEnabled(false);@@ -294,7 +399,7 @@ void MaritimeScreen::update_intelligence(int vessel_count) {if (stat_vessels_)stat_vessels_->setText(count_str);if (stat_displayed_)- stat_displayed_->setText(QString::number(qMin(vessel_count, 500)));+ stat_displayed_->setText(QString::number(qMin(vessel_count, 100)));if (stat_routes_)stat_routes_->setText(QString::number(routes_.size()));}diff --git a/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp b/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cppindex 8c0771e2d..16421e603 100644--- a/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp+++ b/fincept-qt/src/screens/maritime/MaritimeScreen_Layout.cpp@@ -10,6 +10,7 @@#include "core/logging/Logger.h"#include "core/session/ScreenStateManager.h"+#include "services/maritime/GeocodingService.h"#include "services/maritime/MaritimeService.h"#include "services/maritime/PortsCatalog.h"#include "ui/theme/Theme.h"@@ -109,6 +110,56 @@ QWidget* MaritimeScreen::build_left_panel() {connect(load_btn, &QPushButton::clicked, this, &MaritimeScreen::on_load_vessels);vl->addWidget(load_btn);+ // ── Draw-on-map toolbar ─────────────────────────────────────────────────+ //+ // Square / Circle draw tools + Clear. The user can drop multiple shapes;+ // each finalized shape triggers on_shapes_changed which loads the union+ // bbox and filters returned vessels to those inside any drawn shape.+ auto* draw_title = new QLabel("DRAW AREA ON MAP", panel);+ draw_title->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;")+ .arg(ui::colors::AMBER())+ .arg(ui::fonts::DATA_FAMILY));+ vl->addWidget(draw_title);++ auto* draw_row = new QHBoxLayout;+ draw_row->setSpacing(6);+ auto* sq_btn = new QPushButton("◻ SQUARE", panel);+ auto* ci_btn = new QPushButton("◯ CIRCLE", panel);+ auto* clr_btn = new QPushButton("✕ CLEAR", panel);+ for (auto* b : {sq_btn, ci_btn, clr_btn}) {+ b->setCursor(Qt::PointingHandCursor);+ b->setStyleSheet(btn_outline_ss());+ }+ sq_btn->setCheckable(true);+ ci_btn->setCheckable(true);+ draw_row->addWidget(sq_btn);+ draw_row->addWidget(ci_btn);+ draw_row->addWidget(clr_btn);+ vl->addLayout(draw_row);++ // Square / Circle are mutually exclusive toggles; toggling one off (or the+ // other on) returns the map to normal pan/zoom or switches tool.+ connect(sq_btn, &QPushButton::toggled, this, [this, ci_btn](bool on) {+ if (!map_widget_) return;+ if (on) ci_btn->setChecked(false);+ map_widget_->set_draw_mode(on ? fincept::ui::MapDrawMode::Rectangle+ : fincept::ui::MapDrawMode::None);+ });+ connect(ci_btn, &QPushButton::toggled, this, [this, sq_btn](bool on) {+ if (!map_widget_) return;+ if (on) sq_btn->setChecked(false);+ map_widget_->set_draw_mode(on ? fincept::ui::MapDrawMode::Circle+ : fincept::ui::MapDrawMode::None);+ });+ connect(clr_btn, &QPushButton::clicked, this, [this, sq_btn, ci_btn]() {+ sq_btn->setChecked(false);+ ci_btn->setChecked(false);+ if (map_widget_) {+ map_widget_->set_draw_mode(fincept::ui::MapDrawMode::None);+ map_widget_->clear_shapes();+ }+ });+auto* intel_title = new QLabel("INTELLIGENCE", panel);intel_title->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;").arg(ui::colors::AMBER())@@ -215,6 +266,11 @@ QWidget* MaritimeScreen::build_center_panel() {// events while visible so the user can't pan a half-loaded map.map_loader_ = new fincept::ui::LoadingOverlay(map_widget_);+ // Drawn-shape changes → load vessels for the union bbox and filter to+ // those inside the shapes.+ connect(map_widget_, &fincept::ui::WorldMapWidget::shapes_changed, this,+ &MaritimeScreen::on_shapes_changed);+// Pin click → populate the right-panel SELECTED VESSEL card with the// record we cached in update_map. Clicks during a stale map (cached set// emptied) silently no-op.@@ -355,22 +411,88 @@ QWidget* MaritimeScreen::build_right_panel() {search_result_label_->setVisible(false);vl->addWidget(search_result_label_);- // ── Area Search ────────────────────────────────────────────────────────+ // ── Place Search ──────────────────────────────────────────────────────+ //+ // Primary area-input: type a place name, hit Search, pick a suggestion.+ // The selected result's bounding box fills the AREA SEARCH spinners and+ // immediately loads vessels in that area — no manual lat/long needed.+ // Geocoding via OpenStreetMap Nominatim (GeocodingService).vl->addSpacing(8);- auto* area_title = new QLabel("AREA SEARCH", content);- area_title->setStyleSheet(section_label_ss());- vl->addWidget(area_title);+ auto* place_title = new QLabel("PLACE SEARCH", content);+ place_title->setStyleSheet(section_label_ss());+ vl->addWidget(place_title);++ auto* place_lbl = new QLabel("PLACE NAME", content);+ place_lbl->setStyleSheet(tiny_label_ss());+ vl->addWidget(place_lbl);++ place_query_edit_ = new QLineEdit(content);+ place_query_edit_->setPlaceholderText("e.g. Strait of Malacca");+ place_query_edit_->setStyleSheet(input_ss());+ auto run_place_search = [this]() {+ const QString q = place_query_edit_->text().trimmed();+ if (q.isEmpty()) return;+ if (place_status_) place_status_->setText("Searching…");+ services::maritime::GeocodingService::instance().search(q);+ };+ connect(place_query_edit_, &QLineEdit::returnPressed, this, run_place_search);+ vl->addWidget(place_query_edit_);++ auto* place_btn = new QPushButton("SEARCH PLACES", content);+ place_btn->setCursor(Qt::PointingHandCursor);+ place_btn->setStyleSheet(btn_primary_ss());+ connect(place_btn, &QPushButton::clicked, this, run_place_search);+ vl->addWidget(place_btn);++ place_status_ = new QLabel(content);+ place_status_->setStyleSheet(QString("color:%1; font-size:9px; font-family:%2;")+ .arg(ui::colors::TEXT_TERTIARY())+ .arg(ui::fonts::DATA_FAMILY));+ vl->addWidget(place_status_);++ place_table_ = new QTableWidget(content);+ place_table_->setColumnCount(2);+ place_table_->setHorizontalHeaderLabels({"Place", "Type"});+ place_table_->setEditTriggers(QAbstractItemView::NoEditTriggers);+ place_table_->setSelectionBehavior(QAbstractItemView::SelectRows);+ place_table_->setSelectionMode(QAbstractItemView::SingleSelection);+ place_table_->verticalHeader()->setVisible(false);+ place_table_->horizontalHeader()->setStretchLastSection(true);+ place_table_->setMinimumHeight(120);+ place_table_->setStyleSheet(table_ss());+ // Click a suggestion → fill bbox + load vessels in that area.+ connect(place_table_, &QTableWidget::currentCellChanged, this,+ [this](int row, int, int, int) {+ if (row < 0 || row >= place_results_.size()) return;+ const auto& p = place_results_[row];+ run_area_search(p.min_lat, p.max_lat, p.min_lng, p.max_lng);+ });+ vl->addWidget(place_table_);++ // ── Area Search (Advanced — raw lat/long) ───────────────────────────────+ vl->addSpacing(8);+ auto* area_toggle = new QPushButton("▸ ADVANCED: RAW BBOX", content);+ area_toggle->setCursor(Qt::PointingHandCursor);+ area_toggle->setCheckable(true);+ area_toggle->setStyleSheet(btn_outline_ss());+ vl->addWidget(area_toggle);++ advanced_area_box_ = new QWidget(content);+ advanced_area_box_->setVisible(false);+ auto* area_vl = new QVBoxLayout(advanced_area_box_);+ area_vl->setContentsMargins(0, 4, 0, 0);+ area_vl->setSpacing(8);auto make_coord = [&](const QString& label, double def_val) {- auto* lbl = new QLabel(label, content);+ auto* lbl = new QLabel(label, advanced_area_box_);lbl->setStyleSheet(tiny_label_ss());- vl->addWidget(lbl);- auto* spin = new QDoubleSpinBox(content);+ area_vl->addWidget(lbl);+ auto* spin = new QDoubleSpinBox(advanced_area_box_);spin->setRange(-180, 180);spin->setDecimals(4);spin->setValue(def_val);spin->setStyleSheet(input_ss());- vl->addWidget(spin);+ area_vl->addWidget(spin);return spin;};@@ -381,21 +503,21 @@ QWidget* MaritimeScreen::build_right_panel() {area_min_lng_ = make_coord("MIN LONGITUDE", 0.0);area_max_lng_ = make_coord("MAX LONGITUDE", 0.0);- auto* area_btn = new QPushButton("SEARCH AREA", content);+ auto* area_btn = new QPushButton("SEARCH AREA", advanced_area_box_);area_btn->setCursor(Qt::PointingHandCursor);area_btn->setStyleSheet(btn_primary_ss());connect(area_btn, &QPushButton::clicked, this, [this]() {- AreaSearchParams params;- params.min_lat = area_min_lat_->value();- params.max_lat = area_max_lat_->value();- params.min_lng = area_min_lng_->value();- params.max_lng = area_max_lng_->value();- set_status("SEARCHING...", ui::colors::WARNING);- pending_global_sample_ = false;- show_map_loading(QStringLiteral("SEARCHING AREA"));- MaritimeService::instance().search_vessels_by_area(params);+ run_area_search(area_min_lat_->value(), area_max_lat_->value(),+ area_min_lng_->value(), area_max_lng_->value());});- vl->addWidget(area_btn);+ area_vl->addWidget(area_btn);++ connect(area_toggle, &QPushButton::toggled, this, [this, area_toggle](bool on) {+ advanced_area_box_->setVisible(on);+ area_toggle->setText(on ? "▾ ADVANCED: RAW BBOX" : "▸ ADVANCED: RAW BBOX");+ });++ vl->addWidget(advanced_area_box_);// ── Ports Search ────────────────────────────────────────────────────────//diff --git a/fincept-qt/src/screens/news/NewsDetailPanel.cpp b/fincept-qt/src/screens/news/NewsDetailPanel.cppindex 39e3e5e16..38fea23b8 100644--- a/fincept-qt/src/screens/news/NewsDetailPanel.cpp+++ b/fincept-qt/src/screens/news/NewsDetailPanel.cpp@@ -12,8 +12,10 @@#include <QDesktopServices>#include <QFile>#include <QFileInfo>+#include <QGridLayout>#include <QRegularExpression>#include <QScrollArea>+#include <QSizePolicy>#include <QTextStream>#include <QTimer>#include <QUrl>@@ -150,49 +152,51 @@ QWidget* NewsDetailPanel::build_content_view() {tickers_label_->setObjectName("newsDetailTickers");layout->addWidget(tickers_label_);- // Action buttons — arranged in a flow+ // Action buttons — a 3-column grid so the row wraps within the fixed+ // 420px panel width instead of forcing a horizontal scrollbar.auto* actions = new QWidget(content);- auto* action_layout = new QHBoxLayout(actions);+ auto* action_layout = new QGridLayout(actions);action_layout->setContentsMargins(0, 4, 0, 4);- action_layout->setSpacing(6);+ action_layout->setHorizontalSpacing(6);+ action_layout->setVerticalSpacing(6);open_btn_ = new QPushButton("OPEN", content);open_btn_->setObjectName("newsDetailOpenBtn");- open_btn_->setFixedHeight(24);copy_btn_ = new QPushButton("COPY URL", content);copy_btn_->setObjectName("newsDetailCopyBtn");- copy_btn_->setFixedHeight(24);copy_title_btn_ = new QPushButton("COPY TITLE", content);copy_title_btn_->setObjectName("newsDetailCopyTitleBtn");- copy_title_btn_->setFixedHeight(24);- copy_title_btn_->setFixedWidth(copy_title_btn_->fontMetrics().horizontalAdvance("COPY TITLE") + 20);copy_title_btn_->setToolTip("Copy article headline to clipboard");analyze_btn_ = new QPushButton("ANALYZE", content);analyze_btn_->setObjectName("newsDetailAnalyzeBtn");- analyze_btn_->setFixedHeight(24);save_btn_ = new QPushButton("SAVE", content);save_btn_->setObjectName("newsDetailSaveBtn");- save_btn_->setFixedHeight(24);save_btn_->setToolTip("Save article to File Manager");bookmark_btn_ = new QPushButton("BOOKMARK", content);bookmark_btn_->setObjectName("newsDetailSaveBtn");- bookmark_btn_->setFixedHeight(24);bookmark_btn_->setToolTip("Bookmark article");bookmark_btn_->setCheckable(true);// Translate buttontranslate_btn_ = new QPushButton("TRANSLATE", content);translate_btn_->setObjectName("newsDetailOpenBtn");- translate_btn_->setFixedHeight(24);-- action_layout->addWidget(open_btn_);- action_layout->addWidget(copy_btn_);- action_layout->addWidget(copy_title_btn_); // new- action_layout->addWidget(analyze_btn_);- action_layout->addWidget(save_btn_);- action_layout->addWidget(bookmark_btn_);- action_layout->addWidget(translate_btn_);++ // All action buttons share a uniform height and expand to fill their grid+ // cell — no fixed widths, so nothing can overflow the panel.+ for (QPushButton* b :+ {open_btn_, copy_btn_, copy_title_btn_, analyze_btn_, save_btn_, bookmark_btn_, translate_btn_}) {+ b->setFixedHeight(24);+ b->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);+ }++ QPushButton* action_btns[] = {open_btn_, copy_btn_, copy_title_btn_, analyze_btn_,+ save_btn_, bookmark_btn_, translate_btn_};+ constexpr int kCols = 3;+ for (int i = 0; i < 7; ++i)+ action_layout->addWidget(action_btns[i], i / kCols, i % kCols);+ for (int c = 0; c < kCols; ++c)+ action_layout->setColumnStretch(c, 1);layout->addWidget(actions);connect(open_btn_, &QPushButton::clicked, this, [this]() {@@ -288,25 +292,44 @@ QWidget* NewsDetailPanel::build_content_view() {ai_title->setObjectName("newsDetailSectionTitle");analysis_layout->addWidget(ai_title);+ // Fetch-note banner — shown only when the publisher blocked content and+ // the analysis is metadata-only, so the numbers aren't read as gospel.+ ai_fetch_note_ = new QLabel(analysis_section_);+ ai_fetch_note_->setObjectName("newsDetailAiFetchNote");+ ai_fetch_note_->setWordWrap(true);+ ai_fetch_note_->hide();+ analysis_layout->addWidget(ai_fetch_note_);+ai_summary_ = new QLabel(analysis_section_);ai_summary_->setObjectName("newsDetailAiSummary");ai_summary_->setWordWrap(true);analysis_layout->addWidget(ai_summary_);+ // Metric pills — laid out in a wrapping 2-column grid so a long urgency /+ // prediction string can never push past the panel's fixed width.auto* ai_row = new QWidget(analysis_section_);- auto* ai_row_layout = new QHBoxLayout(ai_row);+ auto* ai_row_layout = new QGridLayout(ai_row);ai_row_layout->setContentsMargins(0, 0, 0, 0);- ai_row_layout->setSpacing(8);+ ai_row_layout->setHorizontalSpacing(6);+ ai_row_layout->setVerticalSpacing(4);ai_sentiment_ = new QLabel(analysis_section_);ai_sentiment_->setObjectName("newsDetailAiSentiment");+ ai_sentiment_->setWordWrap(true);ai_urgency_ = new QLabel(analysis_section_);ai_urgency_->setObjectName("newsDetailAiUrgency");+ ai_urgency_->setWordWrap(true);+ ai_prediction_ = new QLabel(analysis_section_);+ ai_prediction_->setObjectName("newsDetailAiUrgency");+ ai_prediction_->setWordWrap(true);ai_confidence_ = new QLabel(analysis_section_);ai_confidence_->setObjectName("newsDetailAiConfidence");- ai_row_layout->addWidget(ai_sentiment_);- ai_row_layout->addWidget(ai_urgency_);- ai_row_layout->addWidget(ai_confidence_);- ai_row_layout->addStretch();+ ai_confidence_->setWordWrap(true);+ ai_row_layout->addWidget(ai_sentiment_, 0, 0);+ ai_row_layout->addWidget(ai_confidence_, 0, 1);+ ai_row_layout->addWidget(ai_urgency_, 1, 0);+ ai_row_layout->addWidget(ai_prediction_, 1, 1);+ ai_row_layout->setColumnStretch(0, 1);+ ai_row_layout->setColumnStretch(1, 1);analysis_layout->addWidget(ai_row);// Keywords row (populated in show_analysis).@@ -346,6 +369,18 @@ QWidget* NewsDetailPanel::build_content_view() {topics_layout_->setSpacing(2);analysis_layout->addWidget(topics_container);+ // Entities extracted by the analyze endpoint (orgs / people / locations).+ // Title hides itself when there are no entities (handled in show_analysis).+ ai_entities_title_ = new QLabel("ENTITIES", analysis_section_);+ ai_entities_title_->setObjectName("newsDetailSubTitle");+ analysis_layout->addWidget(ai_entities_title_);++ auto* ai_ent_container = new QWidget(analysis_section_);+ ai_entities_layout_ = new QVBoxLayout(ai_ent_container);+ ai_entities_layout_->setContentsMargins(0, 0, 0, 0);+ ai_entities_layout_->setSpacing(2);+ analysis_layout->addWidget(ai_ent_container);+// Credits footer (e.g. "Credits used: 1 / remaining: 9").ai_credits_ = new QLabel(analysis_section_);ai_credits_->setObjectName("newsDetailAiCredits");@@ -541,21 +576,42 @@ void NewsDetailPanel::show_analysis(const services::NewsAnalysis& analysis) {analyze_btn_->setEnabled(true);analyze_timeout_->stop();+ // Fetch-note banner — flag when the analysis is metadata-only.+ if (!analysis.content.fetch_note.isEmpty()) {+ ai_fetch_note_->setText("⚠ " + analysis.content.fetch_note);+ ai_fetch_note_->show();+ } else {+ ai_fetch_note_->hide();+ }+ai_summary_->setText(analysis.summary.isEmpty() ? "No AI summary available." : analysis.summary);double score = std::clamp(analysis.sentiment.score, -1.0, 1.0);QString sent_color =score > 0.1 ? ui::colors::POSITIVE : (score < -0.1 ? ui::colors::NEGATIVE : ui::colors::WARNING);- ai_sentiment_->setText(QString("Sentiment: %1%2 • int %3")+ ai_sentiment_->setText(QString("Sentiment %1%2 • int %3").arg(score >= 0 ? "+" : "").arg(score, 0, 'f', 2).arg(analysis.sentiment.intensity, 0, 'f', 2));- ai_sentiment_->setStyleSheet(QString("color: %1;").arg(sent_color));-- ai_urgency_->setText(QString("Urgency: %1").arg(analysis.market_impact.urgency));+ ai_sentiment_->setStyleSheet(QString("color: %1; font-weight: 700;").arg(sent_color));++ // Urgency pill — color tracks severity.+ const QString urg = analysis.market_impact.urgency.toUpper();+ QString urg_color = urg == "HIGH" ? ui::colors::NEGATIVE+ : (urg == "MEDIUM" ? ui::colors::WARNING : ui::colors::POSITIVE);+ ai_urgency_->setText(QString("Urgency: %1").arg(urg.isEmpty() ? "—" : urg));+ ai_urgency_->setStyleSheet(QString("color: %1;").arg(urg_color));++ // Prediction pill — directional market impact.+ const QString pred = analysis.market_impact.prediction;+ QString pred_color = pred.contains("positive") ? ui::colors::POSITIVE+ : (pred.contains("negative") ? ui::colors::NEGATIVE+ : ui::colors::WARNING);+ ai_prediction_->setText(QString("Outlook: %1").arg(pred.isEmpty() ? "neutral" : pred));+ ai_prediction_->setStyleSheet(QString("color: %1;").arg(pred_color));ai_confidence_->setText(- QString("Conf: %1%").arg(static_cast<int>(analysis.sentiment.confidence * 100)));+ QString("Confidence: %1%").arg(static_cast<int>(analysis.sentiment.confidence * 100)));// Key pointswhile (key_points_layout_->count() > 0) {@@ -565,50 +621,108 @@ void NewsDetailPanel::show_analysis(const services::NewsAnalysis& analysis) {delete item;}for (const auto& point : analysis.key_points) {- auto* lbl = new QLabel(QString("- %1").arg(point), analysis_section_);+ auto* lbl = new QLabel(QString("• %1").arg(point), analysis_section_);lbl->setObjectName("newsDetailKeyPoint");lbl->setWordWrap(true);key_points_layout_->addWidget(lbl);}- // Risk signals+ // Risk signals — each shows level (color-coded) plus the detail text+ // inline (was tooltip-only before), wrapped so it never overflows.while (risk_layout_->count() > 0) {auto* item = risk_layout_->takeAt(0);if (item->widget())item->widget()->deleteLater();delete item;}+ auto risk_color = [](const QString& level) -> QString {+ const QString l = level.toLower();+ if (l == "critical" || l == "high")+ return ui::colors::NEGATIVE;+ if (l == "medium" || l == "moderate")+ return ui::colors::WARNING;+ if (l == "low")+ return ui::colors::POSITIVE;+ return ui::colors::TEXT_TERTIARY; // "none" / unknown+ };auto add_risk = [&](const QString& name, const services::RiskSignal& sig) {- if (sig.level.isEmpty() || sig.level == "none")+ if (sig.level.isEmpty() || sig.level.compare("none", Qt::CaseInsensitive) == 0)return;- auto* lbl = new QLabel(QString("%1: %2").arg(name, sig.level), analysis_section_);- lbl->setObjectName("newsDetailRisk");- lbl->setToolTip(sig.details);- risk_layout_->addWidget(lbl);+ auto* row = new QWidget(analysis_section_);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0);+ rl->setSpacing(0);+ auto* head = new QLabel(QString("%1 — %2").arg(name, sig.level.toUpper()), row);+ head->setObjectName("newsDetailRisk");+ head->setStyleSheet(QString("color: %1; font-weight: 700;").arg(risk_color(sig.level)));+ rl->addWidget(head);+ if (!sig.details.isEmpty()) {+ auto* det = new QLabel(sig.details, row);+ det->setObjectName("newsDetailRiskDetail");+ det->setWordWrap(true);+ rl->addWidget(det);+ }+ risk_layout_->addWidget(row);};add_risk("Regulatory", analysis.regulatory);add_risk("Geopolitical", analysis.geopolitical);add_risk("Operational", analysis.operational);add_risk("Market", analysis.market);- // Topics+ // Topics — wrapping grid of badges (a QHBoxLayout would overflow the+ // panel's fixed width with no way to wrap).while (topics_layout_->count() > 0) {auto* item = topics_layout_->takeAt(0);if (item->widget())item->widget()->deleteLater();delete item;}- auto* topics_row = new QWidget(analysis_section_);- auto* topics_flow = new QHBoxLayout(topics_row);- topics_flow->setContentsMargins(0, 0, 0, 0);- topics_flow->setSpacing(4);- for (const auto& topic : analysis.topics) {- auto* badge = new QLabel(topic, analysis_section_);- badge->setObjectName("newsDetailTopicBadge");- topics_flow->addWidget(badge);+ if (!analysis.topics.isEmpty()) {+ auto* topics_row = new QWidget(analysis_section_);+ auto* topics_grid = new QGridLayout(topics_row);+ topics_grid->setContentsMargins(0, 0, 0, 0);+ topics_grid->setHorizontalSpacing(4);+ topics_grid->setVerticalSpacing(4);+ constexpr int kTopicCols = 3;+ for (int i = 0; i < analysis.topics.size(); ++i) {+ auto* badge = new QLabel(analysis.topics[i], topics_row);+ badge->setObjectName("newsDetailTopicBadge");+ badge->setAlignment(Qt::AlignCenter);+ topics_grid->addWidget(badge, i / kTopicCols, i % kTopicCols);+ }+ for (int c = 0; c < kTopicCols; ++c)+ topics_grid->setColumnStretch(c, 1);+ topics_layout_->addWidget(topics_row);+ }++ // Entities — organizations (with ticker/sector), people, locations.+ while (ai_entities_layout_->count() > 0) {+ auto* item = ai_entities_layout_->takeAt(0);+ if (item->widget())+ item->widget()->deleteLater();+ delete item;}- topics_flow->addStretch();- topics_layout_->addWidget(topics_row);+ auto add_entity = [&](const QString& prefix, const services::AnalysisEntity& e) {+ QString text = prefix + e.name;+ if (!e.detail.isEmpty())+ text += QString(" (%1)").arg(e.detail);+ if (!e.sector.isEmpty())+ text += QString(" · %1").arg(e.sector);+ auto* lbl = new QLabel(text, analysis_section_);+ lbl->setObjectName("newsDetailEntity");+ lbl->setWordWrap(true);+ ai_entities_layout_->addWidget(lbl);+ };+ for (const auto& o : analysis.organizations)+ add_entity("ORG ", o);+ for (const auto& p : analysis.people)+ add_entity("PER ", p);+ for (const auto& l : analysis.locations)+ add_entity("LOC ", l);+ const bool has_entities =+ !analysis.organizations.isEmpty() || !analysis.people.isEmpty() || !analysis.locations.isEmpty();+ ai_entities_title_->setVisible(has_entities);+ ai_entities_layout_->parentWidget()->setVisible(has_entities);// Keywords — show as a single hashtagged line under topics.if (!analysis.keywords.isEmpty()) {diff --git a/fincept-qt/src/screens/news/NewsDetailPanel.h b/fincept-qt/src/screens/news/NewsDetailPanel.hindex d54394a05..ccd40aad3 100644--- a/fincept-qt/src/screens/news/NewsDetailPanel.h+++ b/fincept-qt/src/screens/news/NewsDetailPanel.h@@ -59,15 +59,19 @@ class NewsDetailPanel : public QWidget {// AI analysis sectionQWidget* analysis_section_ = nullptr;+ QLabel* ai_fetch_note_ = nullptr; // publisher-block / metadata-only bannerQLabel* ai_summary_ = nullptr;QLabel* ai_sentiment_ = nullptr;QLabel* ai_urgency_ = nullptr;+ QLabel* ai_prediction_ = nullptr;QLabel* ai_confidence_ = nullptr;QLabel* ai_keywords_ = nullptr;QLabel* ai_credits_ = nullptr;QVBoxLayout* key_points_layout_ = nullptr;QVBoxLayout* risk_layout_ = nullptr;QVBoxLayout* topics_layout_ = nullptr;+ QLabel* ai_entities_title_ = nullptr;+ QVBoxLayout* ai_entities_layout_ = nullptr;QPushButton* analyze_btn_ = nullptr;QTimer* analyze_timeout_ = nullptr;diff --git a/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp b/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cppindex 3332169d2..269247aa9 100644--- a/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp+++ b/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp@@ -16,6 +16,8 @@#include <QPointer>#include <QtConcurrent/QtConcurrent>+#include <memory>+namespace fincept::workflow {static QString input_style() {@@ -454,7 +456,7 @@ QWidget* ParameterWidgetFactory::create(const ParamDef& param, const QJsonValue&// Load all saved connections of this provider type asynchronously(void)QtConcurrent::run([p_combo, provider, current_value]() {- auto res = DataSourceRepository::instance().list_all();+ auto res = std::make_shared<Result<QVector<DataSource>>>(DataSourceRepository::instance().list_all());// Post results back to combo box on the UI threadQMetaObject::invokeMethod(p_combo.data(), [p_combo, provider, current_value, res]() {@@ -464,8 +466,8 @@ QWidget* ParameterWidgetFactory::create(const ParamDef& param, const QJsonValue&p_combo->clear();p_combo->addItem("— select connection —", QString());- if (res.is_ok()) {- for (const auto& ds : res.value()) {+ if (res->is_ok()) {+ for (const auto& ds : res->value()) {if (ds.provider == provider && ds.enabled) {QString display = ds.display_name + " [" + ds.alias + "]";p_combo->addItem(display, ds.id);@@ -488,10 +490,6 @@ QWidget* ParameterWidgetFactory::create(const ParamDef& param, const QJsonValue&refresh_btn->setObjectName("datasource_connection_refresh");refresh_btn->setFixedSize(24, 24);refresh_btn->setToolTip("Refresh connection list");- refresh_btn->setStyleSheet(QString("QPushButton { background:%1; color:%2;"- " border:1px solid %1; font-size:13px; }"- "QPushButton:hover { background:%3; }")- .arg(ui::colors::BORDER_MED(), ui::colors::AMBER(), ui::colors::TEXT_DIM()));rl->addWidget(refresh_btn);layout->addWidget(row);diff --git a/fincept-qt/src/services/agents/AgentService.cpp b/fincept-qt/src/services/agents/AgentService.cppindex 8b9493300..0e2aaa66b 100644--- a/fincept-qt/src/services/agents/AgentService.cpp+++ b/fincept-qt/src/services/agents/AgentService.cpp@@ -328,12 +328,16 @@ void AgentService::run_python_light(const QString& action, const QJsonObject& paon_result(false, QJsonObject{{"error", pr.error}});return;}+ LOG_INFO("AgentService", QString("%1: raw output length=%2, first 300 chars: %3")+ .arg(action).arg(pr.output.size()).arg(pr.output.left(300)));QJsonDocument doc = QJsonDocument::fromJson(pr.output.toUtf8());if (doc.isNull()) {LOG_ERROR("AgentService", QString("%1: invalid JSON response").arg(action));on_result(false, QJsonObject{{"error", "Invalid JSON response from Python"}});return;}+ LOG_INFO("AgentService", QString("%1: parsed JSON keys: %2")+ .arg(action, QStringList(doc.object().keys()).join(", ")));on_result(true, doc.object());});}diff --git a/fincept-qt/src/services/agents/AgentService_Discovery.cpp b/fincept-qt/src/services/agents/AgentService_Discovery.cppindex 92d17ef46..3a5f34067 100644--- a/fincept-qt/src/services/agents/AgentService_Discovery.cpp+++ b/fincept-qt/src/services/agents/AgentService_Discovery.cpp@@ -39,8 +39,12 @@ void AgentService::discover_agents() {{const QVariant cv = fincept::CacheManager::instance().get("agents:list");if (!cv.isNull()) {- LOG_DEBUG("AgentService", "agents: serving from cache");const QJsonObject root = QJsonDocument::fromJson(cv.toString().toUtf8()).object();+ if (root["agents"].toArray().isEmpty()) {+ fincept::CacheManager::instance().remove("agents:list");+ LOG_INFO("AgentService", "Discarding empty agents cache — re-discovering");+ } else {+ LOG_DEBUG("AgentService", "agents: serving from cache");QVector<AgentInfo> agents;for (const auto& v : root["agents"].toArray()) {const QJsonObject o = v.toObject();@@ -63,6 +67,7 @@ void AgentService::discover_agents() {}emit agents_discovered(agents, categories);return;+ }}}diff --git a/fincept-qt/src/services/maritime/GeocodingService.cpp b/fincept-qt/src/services/maritime/GeocodingService.cppnew file mode 100644index 000000000..7b8f4524b--- /dev/null+++ b/fincept-qt/src/services/maritime/GeocodingService.cpp@@ -0,0 +1,178 @@+// src/services/maritime/GeocodingService.cpp+#include "services/maritime/GeocodingService.h"++#include "core/logging/Logger.h"+#include "storage/cache/CacheManager.h"++#include <QCryptographicHash>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QPointer>+#include <QUrl>+#include <QUrlQuery>++namespace fincept::services::maritime {++namespace {++// NOTE: unity builds merge this TU with PortsCatalog.cpp, whose anonymous+// namespace defines identically-named helpers (kUserAgent, kCacheTtlSec,+// from_json, deserialize_results, ...). Anonymous namespaces don't isolate+// across a unity merge, so every symbol here is prefixed `geo_` to avoid the+// ODR collision (same reason PortsCatalog renamed its publish helper).+constexpr const char* kNominatimEndpoint = "https://nominatim.openstreetmap.org/search";++// Nominatim's usage policy mandates a valid identifying User-Agent with+// contact info; anonymous/library-default UAs are blocked. Matches the+// convention already used by PortsCatalog for Wikidata.+constexpr const char* kGeoUserAgent = "FinceptTerminal/4.0 (https://fincept.in; [email protected])";++// Place geometry is stable; a week keeps repeat searches instant across+// launches without going stale. Mirrors PortsCatalog's cache horizon.+constexpr int kGeoCacheTtlSec = 7 * 24 * 60 * 60;++QString geo_cache_key_for(const QString& query, int limit) {+ const QString payload = QStringLiteral("%1|%2").arg(query.toLower().trimmed()).arg(limit);+ const auto hash = QCryptographicHash::hash(payload.toUtf8(), QCryptographicHash::Sha1).toHex().left(12);+ return QStringLiteral("maritime:geocode:%1").arg(QString::fromLatin1(hash));+}++// ── GeoPlace ↔ JSON (cache round-trip) ───────────────────────────────────────+QJsonObject geo_to_json(const GeoPlace& p) {+ QJsonObject o;+ o["display_name"] = p.display_name;+ o["type"] = p.type;+ o["lat"] = p.latitude;+ o["lng"] = p.longitude;+ o["min_lat"] = p.min_lat;+ o["max_lat"] = p.max_lat;+ o["min_lng"] = p.min_lng;+ o["max_lng"] = p.max_lng;+ return o;+}++GeoPlace geo_from_json(const QJsonObject& o) {+ GeoPlace p;+ p.display_name = o["display_name"].toString();+ p.type = o["type"].toString();+ p.latitude = o["lat"].toDouble();+ p.longitude = o["lng"].toDouble();+ p.min_lat = o["min_lat"].toDouble();+ p.max_lat = o["max_lat"].toDouble();+ p.min_lng = o["min_lng"].toDouble();+ p.max_lng = o["max_lng"].toDouble();+ return p;+}++QByteArray geo_serialize_results(const QVector<GeoPlace>& rows) {+ QJsonArray arr;+ for (const auto& p : rows) arr.append(geo_to_json(p));+ return QJsonDocument(arr).toJson(QJsonDocument::Compact);+}++QVector<GeoPlace> geo_deserialize_results(const QByteArray& blob) {+ QVector<GeoPlace> out;+ const auto arr = QJsonDocument::fromJson(blob).array();+ out.reserve(arr.size());+ for (const auto& v : arr) out.append(geo_from_json(v.toObject()));+ return out;+}++// Parse one Nominatim result object into a GeoPlace. `boundingbox` is an array+// of 4 strings: [min_lat, max_lat, min_lng, max_lng]. When absent (rare), fall+// back to a small box around the point so area-search still has an extent.+GeoPlace parse_nominatim(const QJsonObject& o) {+ GeoPlace p;+ p.display_name = o["display_name"].toString();+ p.type = o["type"].toString();+ p.latitude = o["lat"].toString().toDouble();+ p.longitude = o["lon"].toString().toDouble();++ const QJsonArray bb = o["boundingbox"].toArray();+ if (bb.size() == 4) {+ p.min_lat = bb[0].toString().toDouble();+ p.max_lat = bb[1].toString().toDouble();+ p.min_lng = bb[2].toString().toDouble();+ p.max_lng = bb[3].toString().toDouble();+ } else {+ constexpr double kPad = 0.25; // ~25-30 km half-extent fallback+ p.min_lat = p.latitude - kPad;+ p.max_lat = p.latitude + kPad;+ p.min_lng = p.longitude - kPad;+ p.max_lng = p.longitude + kPad;+ }+ return p;+}++} // namespace++// ── Singleton ────────────────────────────────────────────────────────────────+GeocodingService& GeocodingService::instance() {+ static GeocodingService inst;+ return inst;+}++GeocodingService::GeocodingService(QObject* parent) : QObject(parent) {+ nam_ = new QNetworkAccessManager(this);+}++// ── Place search ─────────────────────────────────────────────────────────────+void GeocodingService::search(const QString& query, int limit) {+ const QString q = query.trimmed();+ if (q.isEmpty())+ return;++ const QString context = q;+ const QString cache_key = geo_cache_key_for(q, limit);++ const QVariant cached = fincept::CacheManager::instance().get(cache_key);+ if (!cached.isNull()) {+ emit places_found(geo_deserialize_results(cached.toString().toUtf8()), context);+ return;+ }++ QUrl url(QString::fromLatin1(kNominatimEndpoint));+ QUrlQuery params;+ params.addQueryItem("format", "jsonv2");+ params.addQueryItem("addressdetails", "0");+ params.addQueryItem("limit", QString::number(limit));+ params.addQueryItem("q", q);+ url.setQuery(params);++ QNetworkRequest req(url);+ req.setRawHeader("User-Agent", kGeoUserAgent);+ req.setRawHeader("Accept", "application/json");++ QPointer<GeocodingService> self = this;+ QNetworkReply* reply = nam_->get(req);+ connect(reply, &QNetworkReply::finished, this, [self, reply, context, cache_key]() {+ reply->deleteLater();+ if (!self)+ return;+ if (reply->error() != QNetworkReply::NoError) {+ LOG_WARN("Geocoding", QString("Nominatim [%1]: %2").arg(context, reply->errorString()));+ emit self->error_occurred(context, reply->errorString());+ return;+ }+ const QByteArray body = reply->readAll();+ const QJsonArray arr = QJsonDocument::fromJson(body).array();++ QVector<GeoPlace> places;+ places.reserve(arr.size());+ for (const auto& v : arr)+ places.append(parse_nominatim(v.toObject()));++ fincept::CacheManager::instance().put(+ cache_key, QVariant(QString::fromUtf8(geo_serialize_results(places))),+ kGeoCacheTtlSec, "maritime");++ LOG_INFO("Geocoding", QString("Place search '%1': %2 result(s)").arg(context).arg(places.size()));+ emit self->places_found(places, context);+ });+}++} // namespace fincept::services::maritimediff --git a/fincept-qt/src/services/maritime/GeocodingService.h b/fincept-qt/src/services/maritime/GeocodingService.hnew file mode 100644index 000000000..1ca073760--- /dev/null+++ b/fincept-qt/src/services/maritime/GeocodingService.h@@ -0,0 +1,44 @@+// src/services/maritime/GeocodingService.h+#pragma once+#include "services/maritime/GeocodingTypes.h"++#include <QObject>+#include <QString>+#include <QVector>++class QNetworkAccessManager;++namespace fincept::services::maritime {++/// Singleton place-name geocoder backed by OpenStreetMap Nominatim.+///+/// One-shot, user-initiated lookup (not a stream): the user types a place+/// name, presses Search, and picks a result whose bounding box drives the+/// maritime area-search. Per the DataHub D4 rule, one-shot catalog-style+/// lookups stay as callback/signal fetches rather than hub topics.+///+/// Mirrors PortsCatalog: async HTTP via its own QNetworkAccessManager, results+/// posted back through `places_found(results, context)` where `context` echoes+/// the original query so concurrent searches can be disambiguated.+class GeocodingService : public QObject {+ Q_OBJECT+ public:+ static GeocodingService& instance();++ /// Free-text place search. `limit` caps the number of suggestions.+ void search(const QString& query, int limit = 8);++ signals:+ /// `context` is the original query string so handlers can match results+ /// back to the search that triggered them.+ void places_found(QVector<fincept::services::maritime::GeoPlace> places, QString context);+ void error_occurred(QString context, QString message);++ private:+ explicit GeocodingService(QObject* parent = nullptr);+ Q_DISABLE_COPY(GeocodingService)++ QNetworkAccessManager* nam_ = nullptr;+};++} // namespace fincept::services::maritimediff --git a/fincept-qt/src/services/maritime/GeocodingTypes.h b/fincept-qt/src/services/maritime/GeocodingTypes.hnew file mode 100644index 000000000..1ecba5938--- /dev/null+++ b/fincept-qt/src/services/maritime/GeocodingTypes.h@@ -0,0 +1,27 @@+// src/services/maritime/GeocodingTypes.h+#pragma once+#include <QMetaType>+#include <QString>+#include <QVector>++namespace fincept::services::maritime {++/// One geocoding result from a place-name search. `bbox` is the suggested+/// area extent (min/max lat/lng) that the maritime area-search uses to load+/// vessels. Nominatim returns this as its `boundingbox` field; for points+/// without a real extent it is a small box centred on (latitude, longitude).+struct GeoPlace {+ QString display_name; // human-readable, e.g. "Singapore Strait, Singapore"+ QString type; // OSM class/type hint, e.g. "strait", "bay", "city"+ double latitude = 0.0;+ double longitude = 0.0;+ double min_lat = 0.0;+ double max_lat = 0.0;+ double min_lng = 0.0;+ double max_lng = 0.0;+};++} // namespace fincept::services::maritime++Q_DECLARE_METATYPE(fincept::services::maritime::GeoPlace)+Q_DECLARE_METATYPE(QVector<fincept::services::maritime::GeoPlace>)diff --git a/fincept-qt/src/services/maritime/MaritimeService.cpp b/fincept-qt/src/services/maritime/MaritimeService.cppindex 9f06489a5..b7be0d13f 100644--- a/fincept-qt/src/services/maritime/MaritimeService.cpp+++ b/fincept-qt/src/services/maritime/MaritimeService.cpp@@ -77,11 +77,18 @@ void MaritimeService::search_vessels_by_area(const AreaSearchParams& params) {body["max_lng"] = params.max_lng;if (params.days_ago > 0)body["days_ago"] = params.days_ago;+ if (params.limit > 0)+ body["limit"] = params.limit;- const QString cache_key = QString("maritime:area:%1:%2:%3:%4:%5")+ const QString cache_key = QString("maritime:area:%1:%2:%3:%4:%5:%6").arg(params.min_lat).arg(params.max_lat).arg(params.min_lng).arg(params.max_lng)- .arg(params.days_ago);+ .arg(params.days_ago).arg(params.limit);++ // Client-side safety net: if the API ignores `limit` and returns the full+ // unbounded set, cap the working set before we parse/sort/re-serialize so+ // the UI thread never chews through tens of thousands of vessels.+ const int hard_cap = params.limit > 0 ? params.limit : 0;const QVariant cached = fincept::CacheManager::instance().get(cache_key);if (!cached.isNull()) {const QJsonObject root = QJsonDocument::fromJson(cached.toString().toUtf8()).object();@@ -100,7 +107,7 @@ void MaritimeService::search_vessels_by_area(const AreaSearchParams& params) {QPointer<MaritimeService> self = this;HttpClient::instance().post(QString(kMarineBase) + "/vessel/area-search", body,- [self, cache_key](Result<QJsonDocument> result) {+ [self, cache_key, hard_cap](Result<QJsonDocument> result) {if (!self)return;if (!result.is_ok()) {@@ -111,10 +118,16 @@ void MaritimeService::search_vessels_by_area(const AreaSearchParams& params) {const auto data = unwrap(result.value().object());const auto vessels_arr = data["vessels"].toArray();+ // Parse at most `hard_cap` vessels (0 = unbounded). Caps the+ // per-vessel parse + downstream sort/re-serialize work when the+ // server returns the full unbounded set despite the limit param.+ const int parse_n = (hard_cap > 0)+ ? std::min<int>(hard_cap, vessels_arr.size())+ : vessels_arr.size();VesselsPage page;- page.vessels.reserve(vessels_arr.size());- for (const auto& v : vessels_arr)- page.vessels.append(self->parse_vessel(v.toObject()));+ page.vessels.reserve(parse_n);+ for (int i = 0; i < parse_n; ++i)+ page.vessels.append(self->parse_vessel(vessels_arr[i].toObject()));// Newest position first — last_pos_updated_at is ISO-8601 so plain// string compare gives correct lexicographic ordering.diff --git a/fincept-qt/src/services/maritime/MaritimeTypes.h b/fincept-qt/src/services/maritime/MaritimeTypes.hindex e851b6282..20612ba2d 100644--- a/fincept-qt/src/services/maritime/MaritimeTypes.h+++ b/fincept-qt/src/services/maritime/MaritimeTypes.h@@ -83,6 +83,7 @@ struct AreaSearchParams {double min_lng = 0;double max_lng = 0;int days_ago = 0;+ int limit = 0; // server-side result cap; 0 = no limit (omitted from request)};} // namespace fincept::services::maritimediff --git a/fincept-qt/src/services/news/NewsService.cpp b/fincept-qt/src/services/news/NewsService.cppindex 8e31013af..08b81b136 100644--- a/fincept-qt/src/services/news/NewsService.cpp+++ b/fincept-qt/src/services/news/NewsService.cpp@@ -419,6 +419,29 @@ void NewsService::analyze_article(const QString& url, AnalysisCallback cb) {analysis.operational = {ops["level"].toString(), ops["details"].toString()};analysis.market = {mkt["level"].toString(), mkt["details"].toString()};+ // Entities — organizations carry ticker/sector/sentiment; locations+ // carry a country code; people are name-only.+ auto ent = a["entities"].toObject();+ for (const auto& v : ent["organizations"].toArray()) {+ auto o = v.toObject();+ analysis.organizations.push_back(+ {o["name"].toString(), o["ticker"].toString(), o["sector"].toString(), o["sentiment"].toDouble()});+ }+ for (const auto& v : ent["people"].toArray()) {+ auto p = v.toObject();+ analysis.people.push_back({p["name"].toString(), {}, {}, 0});+ }+ for (const auto& v : ent["locations"].toArray()) {+ auto l = v.toObject();+ analysis.locations.push_back({l["name"].toString(), l["country_code"].toString(), {}, 0});+ }++ // Content fetch metadata — surfaces publisher-block notices.+ auto content = data["content"].toObject();+ analysis.content.headline = content["headline"].toString();+ analysis.content.word_count = content["word_count"].toInt();+ analysis.content.fetch_note = content["fetch_note"].toString();+cb(true, analysis);}, this);}diff --git a/fincept-qt/src/services/news/NewsService.h b/fincept-qt/src/services/news/NewsService.hindex a2ae0c101..ca275d5ab 100644--- a/fincept-qt/src/services/news/NewsService.h+++ b/fincept-qt/src/services/news/NewsService.h@@ -75,6 +75,24 @@ struct RiskSignal {QString details;};+/// Named entity surfaced by the /news/analyze endpoint. `kind` is one of+/// "organization" / "person" / "location"; `detail` carries the secondary+/// field (ticker for orgs, country_code for locations) when present.+struct AnalysisEntity {+ QString name;+ QString detail; // ticker (orgs) or country code (locations); may be empty+ QString sector; // orgs only+ double sentiment = 0; // orgs only+};++/// Article fetch metadata reported by the analyze endpoint — lets the UI+/// warn when the publisher blocked content and the analysis is metadata-only.+struct AnalysisContent {+ QString headline;+ int word_count = 0;+ QString fetch_note; // e.g. "Article content blocked by publisher (HTTP 401)..."+};+struct NewsAnalysis {SentimentAnalysis sentiment;MarketImpactData market_impact;@@ -86,6 +104,10 @@ struct NewsAnalysis {RiskSignal geopolitical;RiskSignal operational;RiskSignal market;+ QVector<AnalysisEntity> organizations;+ QVector<AnalysisEntity> people;+ QVector<AnalysisEntity> locations;+ AnalysisContent content;int credits_used = 0;int credits_remaining = 0;};diff --git a/fincept-qt/src/services/workflow/NodeRegistry.cpp b/fincept-qt/src/services/workflow/NodeRegistry.cppindex 8fe2fc112..924704db8 100644--- a/fincept-qt/src/services/workflow/NodeRegistry.cpp+++ b/fincept-qt/src/services/workflow/NodeRegistry.cpp@@ -17,13 +17,6 @@#include "services/workflow/nodes/DataSourceNodes.h"#include <QRegularExpression>-#include <QDir>-#include <QFile>-#include <QFileInfo>-#include <QTcpSocket>-#include <QDateTime>-#include <QUrl>-#include <QtConcurrent/QtConcurrent>namespace fincept::workflow {diff --git a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cppindex 02befaab7..e5164d293 100644--- a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp+++ b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp@@ -4,6 +4,7 @@#include "mcp/McpService.h"#include "network/http/HttpClient.h"#include "python/PythonRunner.h"+#include "services/notifications/NotificationService.h"#include "services/workflow/AuditLogger.h"#include "services/workflow/ConfirmationService.h"#include "services/workflow/NodeRegistry.h"@@ -114,6 +115,30 @@ static QString ensure_paper_portfolio() {return p.id;}+// Resolve an account_id for a trading node: prefer the explicit account_id param,+// otherwise fall back to the first active account for the given broker. Returns+// empty when neither resolves (caller reports a friendly "no account" error).+static QString resolve_account_id(const QString& account_id_param, const QString& broker_id) {+ using namespace fincept::trading;+ QString aid = account_id_param.trimmed();+ if (!aid.isEmpty() && AccountManager::instance().has_account(aid))+ return aid;+ return find_account_for_broker(broker_id);+}++// Map a product param string ("MIS"/"CNC"/"NRML" or "intraday"/"delivery"/...) to ProductType.+static fincept::trading::ProductType parse_product(const QString& p) {+ using namespace fincept::trading;+ QString s = p.toLower();+ if (s == "mis" || s == "intraday")+ return ProductType::Intraday;+ if (s == "nrml" || s == "margin")+ return ProductType::Margin;+ if (s == "mtf")+ return ProductType::MTF;+ return ProductType::Delivery; // "cnc" / "delivery" / default+}+void wire_trading_bridges(NodeRegistry& registry) {using namespace fincept::trading;@@ -905,7 +930,280 @@ void wire_trading_bridges(NodeRegistry& registry) {};}- LOG_INFO("ServiceBridges", "Trading bridges wired (11 nodes)");+ // ── Phase 3 §6: Get Quote ─────────────────────────────────────+ auto* quote_def = const_cast<NodeTypeDef*>(registry.find("trading.get_quote"));+ if (quote_def) {+ quote_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,+ std::function<void(bool, QJsonValue, QString)> cb) {+ QString account_id_param = params.value("account_id").toString();+ QString broker = params.value("broker").toString("fyers");+ QString symbol = params.value("symbol").toString();+ QString exchange = params.value("exchange").toString("NSE");+ if (symbol.isEmpty()) {+ cb(false, {}, "Symbol is required");+ return;+ }++ (void)QtConcurrent::run([cb, account_id_param, broker, symbol, exchange]() {+ QString account_id = resolve_account_id(account_id_param, broker);+ if (account_id.isEmpty()) {+ cb(false, {}, QString("No account configured for broker: %1").arg(broker));+ return;+ }++ QVector<QPair<QString, QString>> syms{{symbol, exchange}};+ auto resp = UnifiedTrading::instance().get_multi_quotes(account_id, syms);+ if (!resp.success || !resp.data.has_value() || resp.data->isEmpty()) {+ cb(false, {}, resp.error.isEmpty() ? QString("No quote for %1").arg(symbol) : resp.error);+ return;+ }++ const BrokerQuote& q = resp.data->first();+ QJsonObject out;+ out["symbol"] = symbol;+ out["exchange"] = exchange;+ out["ltp"] = q.ltp;+ out["bid"] = q.bid;+ out["ask"] = q.ask;+ out["volume"] = q.volume;+ out["oi"] = static_cast<double>(q.oi);+ out["open"] = q.open;+ out["high"] = q.high;+ out["low"] = q.low;+ out["close"] = q.close;+ out["change"] = q.change;+ out["change_pct"] = q.change_pct;+ cb(true, out, {});+ });+ };+ }++ // ── Phase 3 §6: Get Position (single symbol) ──────────────────+ auto* single_pos_def = const_cast<NodeTypeDef*>(registry.find("trading.get_position"));+ if (single_pos_def) {+ single_pos_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,+ std::function<void(bool, QJsonValue, QString)> cb) {+ QString account_id_param = params.value("account_id").toString();+ QString broker = params.value("broker").toString("fyers");+ QString symbol = params.value("symbol").toString();+ QString product = params.value("product").toString();+ if (symbol.isEmpty()) {+ cb(false, {}, "Symbol is required");+ return;+ }++ (void)QtConcurrent::run([cb, account_id_param, broker, symbol, product]() {+ QString account_id = resolve_account_id(account_id_param, broker);+ if (account_id.isEmpty()) {+ cb(false, {}, QString("No account configured for broker: %1").arg(broker));+ return;+ }++ auto creds = AccountManager::instance().load_credentials(account_id);+ auto* ibk = AccountManager::instance().broker_for(account_id);+ if (!ibk) {+ cb(false, {}, "Broker not found in registry");+ return;+ }++ auto result = ibk->get_positions(creds);+ if (!result.success) {+ cb(false, {}, result.error);+ return;+ }++ for (const auto& p : result.data.value()) {+ if (!p.symbol.contains(symbol, Qt::CaseInsensitive))+ continue;+ if (!product.isEmpty() && !p.product_type.contains(product, Qt::CaseInsensitive))+ continue;+ QJsonObject out;+ out["symbol"] = p.symbol;+ out["exchange"] = p.exchange;+ out["product"] = p.product_type;+ out["quantity"] = p.quantity;+ out["avg_price"] = p.avg_price;+ out["ltp"] = p.ltp;+ out["pnl"] = p.pnl;+ out["pnl_pct"] = p.pnl_pct;+ out["side"] = p.side;+ cb(true, out, {});+ return;+ }++ // No matching position — return a flat (zero) position rather than error.+ QJsonObject out;+ out["symbol"] = symbol;+ out["quantity"] = 0.0;+ out["avg_price"] = 0.0;+ out["pnl"] = 0.0;+ cb(true, out, {});+ });+ };+ }++ // ── Phase 3 §6: Smart Order ───────────────────────────────────+ auto* smart_def = const_cast<NodeTypeDef*>(registry.find("trading.smart_order"));+ if (smart_def) {+ smart_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,+ std::function<void(bool, QJsonValue, QString)> cb) {+ QString account_id_param = params.value("account_id").toString();+ QString broker = params.value("broker").toString("fyers");+ QString symbol = params.value("symbol").toString();+ QString exchange = params.value("exchange").toString("NSE");+ double position_size = params.value("position_size").toDouble(0);+ QString order_type_str = params.value("order_type").toString("market");+ double price = params.value("price").toDouble(0);+ QString product = params.value("product").toString("intraday");+ if (symbol.isEmpty()) {+ cb(false, {}, "Symbol is required");+ return;+ }++ (void)QtConcurrent::run([cb, account_id_param, broker, symbol, exchange, position_size, order_type_str,+ price, product]() {+ QString account_id = resolve_account_id(account_id_param, broker);+ if (account_id.isEmpty()) {+ cb(false, {}, QString("No account configured for broker: %1").arg(broker));+ return;+ }++ SmartOrder so;+ so.symbol = symbol;+ so.exchange = exchange;+ so.position_size = position_size;+ so.action = position_size >= 0 ? OrderSide::Buy : OrderSide::Sell;+ so.order_type = (order_type_str == "limit") ? OrderType::Limit : OrderType::Market;+ so.price = price;+ so.product_type = parse_product(product);++ auto resp = UnifiedTrading::instance().place_smart_order(account_id, so);+ if (!resp.success || !resp.data.has_value()) {+ cb(false, {}, resp.error.isEmpty() ? "Smart order failed" : resp.error);+ return;+ }++ const SmartOrderResult& r = resp.data.value();+ QJsonObject out;+ out["symbol"] = symbol;+ out["exchange"] = exchange;+ out["order_id"] = r.order_id;+ out["action_taken"] = r.action_taken;+ out["executed_action"] = QString(order_side_str(r.executed_action));+ out["executed_quantity"] = r.executed_quantity;+ out["message"] = r.message;+ out["broker"] = broker;+ cb(true, out, {});+ });+ };+ }++ // ── Phase 3 §6: Cancel All Orders ─────────────────────────────+ auto* cancel_all_def = const_cast<NodeTypeDef*>(registry.find("trading.cancel_all"));+ if (cancel_all_def) {+ cancel_all_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,+ std::function<void(bool, QJsonValue, QString)> cb) {+ QString account_id_param = params.value("account_id").toString();+ QString broker = params.value("broker").toString("fyers");++ (void)QtConcurrent::run([cb, account_id_param, broker]() {+ QString account_id = resolve_account_id(account_id_param, broker);+ if (account_id.isEmpty()) {+ cb(false, {}, QString("No account configured for broker: %1").arg(broker));+ return;+ }++ auto resp = UnifiedTrading::instance().cancel_all_orders(account_id);+ if (!resp.success || !resp.data.has_value()) {+ cb(false, {}, resp.error.isEmpty() ? "Cancel all failed" : resp.error);+ return;+ }++ const CancelAllResult& r = resp.data.value();+ QJsonObject out;+ out["canceled_count"] = r.canceled_order_ids.size();+ out["failed_count"] = r.failed.size();+ out["total_attempted"] = r.total_attempted;+ QJsonArray ids;+ for (const auto& id : r.canceled_order_ids)+ ids.append(id);+ out["canceled_ids"] = ids;+ out["broker"] = broker;+ cb(true, out, {});+ });+ };+ }++ // ── Phase 3 §6: Close All Positions ───────────────────────────+ auto* close_all_def = const_cast<NodeTypeDef*>(registry.find("trading.close_all"));+ if (close_all_def) {+ close_all_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,+ std::function<void(bool, QJsonValue, QString)> cb) {+ QString account_id_param = params.value("account_id").toString();+ QString broker = params.value("broker").toString("fyers");++ (void)QtConcurrent::run([cb, account_id_param, broker]() {+ QString account_id = resolve_account_id(account_id_param, broker);+ if (account_id.isEmpty()) {+ cb(false, {}, QString("No account configured for broker: %1").arg(broker));+ return;+ }++ auto resp = UnifiedTrading::instance().close_all_positions(account_id);+ if (!resp.success || !resp.data.has_value()) {+ cb(false, {}, resp.error.isEmpty() ? "Close all failed" : resp.error);+ return;+ }++ const CloseAllResult& r = resp.data.value();+ QJsonObject out;+ out["closed_count"] = r.closed_symbols.size();+ out["failed_count"] = r.failed.size();+ out["total_positions"] = r.total_positions;+ QJsonArray syms;+ for (const auto& s : r.closed_symbols)+ syms.append(s);+ out["closed_symbols"] = syms;+ out["broker"] = broker;+ cb(true, out, {});+ });+ };+ }++ // ── Phase 3 §6: Trading Alert ─────────────────────────────────+ auto* alert_def = const_cast<NodeTypeDef*>(registry.find("trading.alert"));+ if (alert_def) {+ alert_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,+ std::function<void(bool, QJsonValue, QString)> cb) {+ using namespace fincept::notifications;+ QString message = params.value("message").toString();+ QString channel = params.value("channel").toString("notification");+ if (message.isEmpty() && !inputs.isEmpty() && inputs[0].isObject())+ message = inputs[0].toObject().value("message").toString();+ if (message.isEmpty()) {+ cb(false, {}, "Alert message is required");+ return;+ }++ const QJsonValue pass_through = inputs.isEmpty() ? QJsonValue{} : inputs[0];++ if (channel == "log") {+ LOG_INFO("TradingAlert", message);+ cb(true, pass_through, {});+ return;+ }++ NotificationRequest req;+ req.title = "Trading Alert";+ req.message = message;+ req.level = NotifLevel::Alert;+ req.trigger = NotifTrigger::WorkflowNode;+ NotificationService::instance().send(req);+ cb(true, pass_through, {});+ };+ }++ LOG_INFO("ServiceBridges", "Trading bridges wired (17 nodes)");}// ── Agent Bridge ───────────────────────────────────────────────────────diff --git a/fincept-qt/src/services/workflow/nodes/TradingNodes.cpp b/fincept-qt/src/services/workflow/nodes/TradingNodes.cppindex 0ef1229db..22376a938 100644--- a/fincept-qt/src/services/workflow/nodes/TradingNodes.cpp+++ b/fincept-qt/src/services/workflow/nodes/TradingNodes.cpp@@ -241,6 +241,135 @@ void register_trading_nodes(NodeRegistry& registry) {},.execute = nullptr,});++ // ── Phase 3 §6: OpenAlgo-parity live trading nodes ─────────────+ // Definitions only — execution is wired in ServiceBridges.cpp+ // (wire_trading_bridges) against UnifiedTrading / the active broker.++ // Data: Get Quote — live LTP/bid/ask/volume/OI for a single symbol.+ registry.register_type({+ .type_id = "trading.get_quote",+ .display_name = "Get Quote",+ .category = "Trading",+ .description = "Fetch a live broker quote (LTP, bid, ask, volume, OI) for a symbol",+ .icon_text = "T",+ .accent_color = "#16a34a",+ .version = 1,+ .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},+ .outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::MarketData}},+ .parameters =+ {+ {"account_id", "Account ID", "string", "", {}, "Leave blank to use active account for broker"},+ {"broker", "Broker", "select", "fyers", {"fyers", "zerodha", "alpaca", "ibkr", "upstox", "dhan"}, ""},+ {"symbol", "Symbol", "string", "", {}, "Ticker symbol", true},+ {"exchange", "Exchange", "select", "NSE", {"NSE", "BSE", "NFO", "MCX", "CDS", "NASDAQ", "NYSE"}, ""},+ },+ .execute = nullptr,+ });++ // Data: Get Position — quantity/avg_price/pnl for a single symbol.+ registry.register_type({+ .type_id = "trading.get_position",+ .display_name = "Get Position",+ .category = "Trading",+ .description = "Fetch the open position (qty, avg price, P&L) for a single symbol",+ .icon_text = "T",+ .accent_color = "#16a34a",+ .version = 1,+ .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},+ .outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::PortfolioData}},+ .parameters =+ {+ {"account_id", "Account ID", "string", "", {}, "Leave blank to use active account for broker"},+ {"broker", "Broker", "select", "fyers", {"fyers", "zerodha", "alpaca", "ibkr", "upstox", "dhan"}, ""},+ {"symbol", "Symbol", "string", "", {}, "Ticker symbol", true},+ {"exchange", "Exchange", "select", "NSE", {"NSE", "BSE", "NFO", "MCX", "CDS", "NASDAQ", "NYSE"}, ""},+ {"product", "Product", "select", "", {"", "MIS", "CNC", "NRML"}, "Optional product filter"},+ },+ .execute = nullptr,+ });++ // Order: Smart Order — position-aware order (targets a net position size).+ registry.register_type({+ .type_id = "trading.smart_order",+ .display_name = "Smart Order",+ .category = "Trading",+ .description = "Position-aware order — buys/sells the delta needed to reach a target position size",+ .icon_text = "T",+ .accent_color = "#16a34a",+ .version = 1,+ .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},+ .outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::Main}},+ .parameters =+ {+ {"account_id", "Account ID", "string", "", {}, "Leave blank to use active account for broker"},+ {"broker", "Broker", "select", "fyers", {"fyers", "zerodha", "alpaca", "ibkr", "upstox", "dhan"}, ""},+ {"symbol", "Symbol", "string", "", {}, "Ticker symbol", true},+ {"exchange", "Exchange", "select", "NSE", {"NSE", "BSE", "NFO", "MCX", "CDS", "NASDAQ", "NYSE"}, ""},+ {"position_size", "Position Size", "number", 0, {}, "Target net position (+long / -short / 0=flatten)", true},+ {"order_type", "Order Type", "select", "market", {"market", "limit"}, ""},+ {"price", "Limit Price", "number", 0, {}, "Price for limit orders"},+ {"product", "Product", "select", "intraday", {"delivery", "intraday", "margin", "mtf"}, ""},+ },+ .execute = nullptr,+ });++ // Order: Cancel All — cancel every open order on the account.+ registry.register_type({+ .type_id = "trading.cancel_all",+ .display_name = "Cancel All Orders",+ .category = "Trading",+ .description = "Cancel all open orders on the account",+ .icon_text = "T",+ .accent_color = "#16a34a",+ .version = 1,+ .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},+ .outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::Main}},+ .parameters =+ {+ {"account_id", "Account ID", "string", "", {}, "Leave blank to use active account for broker"},+ {"broker", "Broker", "select", "fyers", {"fyers", "zerodha", "alpaca", "ibkr", "upstox", "dhan"}, ""},+ },+ .execute = nullptr,+ });++ // Order: Close All — square off every open position on the account.+ registry.register_type({+ .type_id = "trading.close_all",+ .display_name = "Close All Positions",+ .category = "Trading",+ .description = "Square off all open positions on the account",+ .icon_text = "T",+ .accent_color = "#16a34a",+ .version = 1,+ .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},+ .outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::Main}},+ .parameters =+ {+ {"account_id", "Account ID", "string", "", {}, "Leave blank to use active account for broker"},+ {"broker", "Broker", "select", "fyers", {"fyers", "zerodha", "alpaca", "ibkr", "upstox", "dhan"}, ""},+ },+ .execute = nullptr,+ });++ // Alert: Trading Alert — fire a workflow notification (no outputs).+ registry.register_type({+ .type_id = "trading.alert",+ .display_name = "Trading Alert",+ .category = "Trading",+ .description = "Send a trading alert via the notification system or log",+ .icon_text = "T",+ .accent_color = "#16a34a",+ .version = 1,+ .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},+ .outputs = {},+ .parameters =+ {+ {"message", "Message", "string", "", {}, "Alert message", true},+ {"channel", "Channel", "select", "notification", {"notification", "log"}, "Where to deliver the alert"},+ },+ .execute = nullptr,+ });}} // namespace fincept::workflowdiff --git a/fincept-qt/src/storage/HistoricalDataStore.cpp b/fincept-qt/src/storage/HistoricalDataStore.cppnew file mode 100644index 000000000..c46400749--- /dev/null+++ b/fincept-qt/src/storage/HistoricalDataStore.cpp@@ -0,0 +1,353 @@+#include "storage/HistoricalDataStore.h"++#include "core/logging/Logger.h"+#include "storage/sqlite/Database.h"++#include <QDateTime>+#include <QFile>+#include <QSqlError>+#include <QSqlQuery>+#include <QTextStream>+#include <QTimeZone>+#include <QVariantList>++#include <algorithm>++namespace fincept::storage {++namespace {++Database& db() { return Database::instance(); }++// Map a SELECT row (timestamp_ms, open, high, low, close, volume, oi) to a candle.+trading::BrokerCandle map_candle(QSqlQuery& q) {+ trading::BrokerCandle c;+ c.timestamp = q.value(0).toLongLong();+ c.open = q.value(1).toDouble();+ c.high = q.value(2).toDouble();+ c.low = q.value(3).toDouble();+ c.close = q.value(4).toDouble();+ c.volume = q.value(5).toDouble();+ c.oi = q.value(6).toDouble();+ return c;+}++// Resample plan: which stored base interval a target is computed from, and the+// fixed bucket width in ms for time-aligned targets (4h/8h). Calendar targets+// (1w/1mo) bucket by date boundaries instead — see bucket_key_*.+struct ResamplePlan {+ QString base_interval; // "1h" or "1d"+ qint64 fixed_bucket_ms = 0; // >0 for 4h/8h; 0 = calendar bucketing+ bool calendar_week = false;+ bool calendar_month = false;+};++// Returns a plan for the supported resample targets, or std::nullopt if the+// target is not one we resample (caller should fall back to get_candles).+std::optional<ResamplePlan> plan_for(const QString& target_interval) {+ const QString t = target_interval.trimmed().toLower();+ constexpr qint64 hour_ms = 3600LL * 1000;+ if (t == "4h")+ return ResamplePlan{"1h", 4 * hour_ms, false, false};+ if (t == "8h")+ return ResamplePlan{"1h", 8 * hour_ms, false, false};+ if (t == "1w" || t == "1wk" || t == "1week")+ return ResamplePlan{"1d", 0, true, false};+ if (t == "1mo" || t == "1month" || t == "1mon")+ return ResamplePlan{"1d", 0, false, true};+ return std::nullopt;+}++// Bucket key for a fixed-width (4h/8h) target: floor(ts / width) * width gives+// the candle's epoch-ms start, aligned to the epoch.+qint64 fixed_bucket_start(qint64 ts_ms, qint64 width_ms) {+ if (width_ms <= 0)+ return ts_ms;+ return (ts_ms / width_ms) * width_ms;+}++// Bucket start (epoch ms) for a weekly candle: 00:00:00 UTC of the Monday of+// the candle's ISO week.+qint64 week_bucket_start(qint64 ts_ms) {+ QDateTime dt = QDateTime::fromMSecsSinceEpoch(ts_ms, QTimeZone::utc());+ QDate d = dt.date();+ // Qt: dayOfWeek() Monday=1 .. Sunday=7. Roll back to Monday.+ int back = d.dayOfWeek() - 1;+ QDate monday = d.addDays(-back);+ return QDateTime(monday, QTime(0, 0, 0), QTimeZone::utc()).toMSecsSinceEpoch();+}++// Bucket start (epoch ms) for a monthly candle: 00:00:00 UTC of the 1st of the+// candle's calendar month.+qint64 month_bucket_start(qint64 ts_ms) {+ QDateTime dt = QDateTime::fromMSecsSinceEpoch(ts_ms, QTimeZone::utc());+ QDate d = dt.date();+ QDate first(d.year(), d.month(), 1);+ return QDateTime(first, QTime(0, 0, 0), QTimeZone::utc()).toMSecsSinceEpoch();+}++} // anonymous namespace++HistoricalDataStore& HistoricalDataStore::instance() {+ static HistoricalDataStore s;+ return s;+}++// ── OHLCV storage ──────────────────────────────────────────────────────────────++bool HistoricalDataStore::store_candles(const QString& symbol, const QString& exchange,+ const QString& interval,+ const QVector<trading::BrokerCandle>& candles) {+ if (candles.isEmpty())+ return true;++ auto begin = db().begin_transaction();+ const bool in_tx = begin.is_ok();+ if (!in_tx)+ LOG_WARN("Historify", "transaction begin failed; storing without batch transaction");++ const QString sql = QStringLiteral(+ "INSERT OR REPLACE INTO market_data "+ "(symbol, exchange, interval, timestamp_ms, open, high, low, close, volume, oi) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");++ const QString sym = symbol.toUpper();+ const QString exc = exchange.toUpper();++ for (const auto& c : candles) {+ auto r = db().execute(sql, {sym, exc, interval, static_cast<qint64>(c.timestamp), c.open, c.high,+ c.low, c.close, c.volume, c.oi});+ if (r.is_err()) {+ LOG_ERROR("Historify", QString("store_candles failed for %1:%2:%3 — %4")+ .arg(sym, exc, interval, QString::fromStdString(r.error())));+ if (in_tx)+ db().rollback();+ return false;+ }+ }++ if (in_tx) {+ auto c = db().commit();+ if (c.is_err()) {+ LOG_ERROR("Historify", QString("commit failed — %1").arg(QString::fromStdString(c.error())));+ return false;+ }+ }+ LOG_INFO("Historify", QString("Stored %1 candles for %2:%3:%4")+ .arg(candles.size())+ .arg(sym, exc, interval));+ return true;+}++QVector<trading::BrokerCandle> HistoricalDataStore::get_candles(const QString& symbol,+ const QString& exchange,+ const QString& interval, qint64 from_ms,+ qint64 to_ms) const {+ QString sql = QStringLiteral(+ "SELECT timestamp_ms, open, high, low, close, volume, oi FROM market_data "+ "WHERE symbol = ? AND exchange = ? AND interval = ?");+ QVariantList params{symbol.toUpper(), exchange.toUpper(), interval};++ if (from_ms > 0) {+ sql += " AND timestamp_ms >= ?";+ params.append(from_ms);+ }+ if (to_ms > 0) {+ sql += " AND timestamp_ms <= ?";+ params.append(to_ms);+ }+ sql += " ORDER BY timestamp_ms ASC";++ QVector<trading::BrokerCandle> out;+ auto r = db().execute(sql, params);+ if (r.is_err()) {+ LOG_ERROR("Historify", QString("get_candles failed — %1").arg(QString::fromStdString(r.error())));+ return out;+ }+ auto& q = r.value();+ while (q.next())+ out.append(map_candle(q));+ return out;+}++QVector<trading::BrokerCandle> HistoricalDataStore::get_resampled(const QString& symbol,+ const QString& exchange,+ const QString& target_interval,+ qint64 from_ms, qint64 to_ms) const {+ auto plan = plan_for(target_interval);+ if (!plan) {+ LOG_WARN("Historify", QString("get_resampled: unsupported target interval '%1'").arg(target_interval));+ return {};+ }++ // Load the base series. For calendar/fixed bucketing we widen the lower bound+ // is not strictly required (we just bucket whatever falls in [from,to]); a+ // partial leading bucket is acceptable and matches OpenAlgo's behaviour.+ QVector<trading::BrokerCandle> base = get_candles(symbol, exchange, plan->base_interval, from_ms, to_ms);+ if (base.isEmpty())+ return {};++ // base is already ordered ascending by timestamp. Aggregate sequentially:+ // open=first, high=max, low=min, close=last, volume=sum, oi=last.+ QVector<trading::BrokerCandle> out;+ bool have_bucket = false;+ qint64 cur_key = 0;+ trading::BrokerCandle agg;++ auto bucket_key = [&](qint64 ts) -> qint64 {+ if (plan->calendar_week)+ return week_bucket_start(ts);+ if (plan->calendar_month)+ return month_bucket_start(ts);+ return fixed_bucket_start(ts, plan->fixed_bucket_ms);+ };++ for (const auto& c : base) {+ const qint64 key = bucket_key(static_cast<qint64>(c.timestamp));+ if (!have_bucket || key != cur_key) {+ if (have_bucket)+ out.append(agg);+ // Start a new bucket. Stamp the candle at the bucket start.+ cur_key = key;+ have_bucket = true;+ agg = c;+ agg.timestamp = key;+ } else {+ agg.high = std::max(agg.high, c.high);+ agg.low = std::min(agg.low, c.low);+ agg.close = c.close; // last+ agg.volume += c.volume;+ agg.oi = c.oi; // last+ }+ }+ if (have_bucket)+ out.append(agg);+ return out;+}++// ── Watchlist ───────────────────────────────────────────────────────────────────++bool HistoricalDataStore::add_to_watchlist(const QString& symbol, const QString& exchange,+ const QString& interval) {+ auto r = db().execute(+ "INSERT OR IGNORE INTO historify_watchlist (symbol, exchange, interval) VALUES (?, ?, ?)",+ {symbol.toUpper(), exchange.toUpper(), interval});+ if (r.is_err()) {+ LOG_ERROR("Historify", QString("add_to_watchlist failed — %1").arg(QString::fromStdString(r.error())));+ return false;+ }+ return true;+}++bool HistoricalDataStore::remove_from_watchlist(const QString& symbol, const QString& exchange,+ const QString& interval) {+ auto r = db().execute(+ "DELETE FROM historify_watchlist WHERE symbol = ? AND exchange = ? AND interval = ?",+ {symbol.toUpper(), exchange.toUpper(), interval});+ if (r.is_err()) {+ LOG_ERROR("Historify",+ QString("remove_from_watchlist failed — %1").arg(QString::fromStdString(r.error())));+ return false;+ }+ return true;+}++QVector<HistoricalDataStore::WatchEntry> HistoricalDataStore::watchlist() const {+ QVector<WatchEntry> out;+ auto r = db().execute("SELECT symbol, exchange, interval FROM historify_watchlist "+ "ORDER BY symbol, exchange, interval");+ if (r.is_err()) {+ LOG_ERROR("Historify", QString("watchlist failed — %1").arg(QString::fromStdString(r.error())));+ return out;+ }+ auto& q = r.value();+ while (q.next()) {+ WatchEntry e;+ e.symbol = q.value(0).toString();+ e.exchange = q.value(1).toString();+ e.interval = q.value(2).toString();+ out.append(e);+ }+ return out;+}++// ── Catalog ───────────────────────────────────────────────────────────────────++QVector<HistoricalDataStore::CatalogEntry> HistoricalDataStore::catalog() const {+ QVector<CatalogEntry> out;+ auto r = db().execute(+ "SELECT symbol, exchange, interval, MIN(timestamp_ms), MAX(timestamp_ms), COUNT(*) "+ "FROM market_data GROUP BY symbol, exchange, interval ORDER BY symbol, exchange, interval");+ if (r.is_err()) {+ LOG_ERROR("Historify", QString("catalog failed — %1").arg(QString::fromStdString(r.error())));+ return out;+ }+ auto& q = r.value();+ while (q.next()) {+ CatalogEntry e;+ e.symbol = q.value(0).toString();+ e.exchange = q.value(1).toString();+ e.interval = q.value(2).toString();+ e.first_ts = q.value(3).toLongLong();+ e.last_ts = q.value(4).toLongLong();+ e.record_count = q.value(5).toInt();+ out.append(e);+ }+ return out;+}++// ── Export ────────────────────────────────────────────────────────────────────++bool HistoricalDataStore::export_csv(const QString& symbol, const QString& exchange,+ const QString& interval, const QString& file_path, qint64 from_ms,+ qint64 to_ms) const {+ const QVector<trading::BrokerCandle> candles = get_candles(symbol, exchange, interval, from_ms, to_ms);++ QFile f(file_path);+ if (!f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {+ LOG_ERROR("Historify", QString("export_csv: cannot open %1 — %2").arg(file_path, f.errorString()));+ return false;+ }+ QTextStream ts(&f);+ ts << "timestamp,open,high,low,close,volume,oi\n";+ for (const auto& c : candles) {+ ts << static_cast<qint64>(c.timestamp) << ',' << c.open << ',' << c.high << ',' << c.low << ','+ << c.close << ',' << c.volume << ',' << c.oi << '\n';+ }+ f.close();+ LOG_INFO("Historify", QString("Exported %1 rows to %2").arg(candles.size()).arg(file_path));+ return true;+}++bool HistoricalDataStore::export_parquet(const QString& symbol, const QString& exchange,+ const QString& interval, const QString& file_path,+ qint64 from_ms, qint64 to_ms) const {+ // TODO(parquet): no Arrow/Parquet library is vendored. Downgrade to CSV and+ // warn so the caller still gets data. Replace with a real Parquet writer+ // once Arrow/Parquet is added to the build.+ LOG_WARN("Historify", "export_parquet: no Parquet library available — writing CSV instead");+ return export_csv(symbol, exchange, interval, file_path, from_ms, to_ms);+}++// ── Auto-download hook ──────────────────────────────────────────────────────────++bool HistoricalDataStore::refresh_now(const QString& symbol, const QString& exchange,+ const QString& interval,+ const QVector<trading::BrokerCandle>& candles) {+ // Documented entry point for a future scheduler / broker-fetch service to+ // push fetched candles. Currently just persists them.+ return store_candles(symbol, exchange, interval, candles);+}++int HistoricalDataStore::refresh_watchlist() {+ // TODO(auto-download): drive broker historical fetches for each watchlist+ // entry (through the trading layer / DataHub), then call refresh_now() with+ // the results. Not wired in this pass — return the count so a scheduler can+ // log what it would do.+ const auto entries = watchlist();+ LOG_INFO("Historify",+ QString("refresh_watchlist: %1 entries pending (auto-download not wired)").arg(entries.size()));+ return entries.size();+}++} // namespace fincept::storagediff --git a/fincept-qt/src/storage/HistoricalDataStore.h b/fincept-qt/src/storage/HistoricalDataStore.hnew file mode 100644index 000000000..e148f586d--- /dev/null+++ b/fincept-qt/src/storage/HistoricalDataStore.h@@ -0,0 +1,132 @@+#pragma once+// HistoricalDataStore — persistent historical OHLCV+OI data store (Historify).+//+// Phase 3 §13. Port of OpenAlgo's Historify (services/historify_service.py ++// database/historify_db.py) onto Fincept's EXISTING SQLite stack.+//+// DECISION — SQLite, not DuckDB:+// OpenAlgo's Historify uses DuckDB (columnar OLAP). Fincept has NO DuckDB+// dependency and no vcpkg/conan; adding DuckDB via FetchContent is too heavy+// and risky for this pass. The Phase 3 doc explicitly lists SQLite as the+// acceptable fallback (Option B). This store therefore lives on the same+// SQLite database as every other repository (see migration v033_historify).+//+// TODO(perf): for very large-scale OLAP / multi-year backtests over millions+// of rows, a DuckDB-backed store (or a DuckDB read replica fed from this+// SQLite table) would be materially faster for columnar aggregation. Revisit+// if/when the project gains a package manager and the row counts justify it.+//+// Conventions:+// - namespace fincept::storage (matches the src/storage/ directory).+// - Timestamps are epoch MILLISECONDS throughout (trading::BrokerCandle uses+// int64 ms). OpenAlgo uses epoch seconds; this store standardises on ms.+// - Schema lives in migration v033_historify.cpp.+// - Singleton, accessed on the main thread. Uses Database::instance() which+// hands out a per-thread connection, so background callers are tolerated.++#include "trading/TradingTypes.h"++#include <QString>+#include <QVector>++#include <cstdint>++namespace fincept::storage {++class HistoricalDataStore {+ public:+ static HistoricalDataStore& instance();++ // ── OHLCV storage ────────────────────────────────────────────────────────++ /// Upsert candles for (symbol, exchange, interval). Idempotent on timestamp+ /// (INSERT OR REPLACE keyed on the candle's epoch-ms timestamp). Runs in a+ /// single transaction. Returns false on any write error.+ bool store_candles(const QString& symbol, const QString& exchange, const QString& interval,+ const QVector<trading::BrokerCandle>& candles);++ /// Query stored candles in [from_ms, to_ms] inclusive, ordered ascending by+ /// timestamp. Pass from_ms<=0 / to_ms<=0 to leave that bound open.+ QVector<trading::BrokerCandle> get_candles(const QString& symbol, const QString& exchange,+ const QString& interval, qint64 from_ms, qint64 to_ms) const;++ /// Compute a higher-timeframe series by resampling a stored base series:+ /// 4h / 8h ← aggregated from stored "1h"+ /// 1w / 1mo ← aggregated from stored "1d"+ /// OHLC aggregation: open=first, high=max, low=min, close=last, volume=sum,+ /// oi=last in each target bucket. Returns empty if target_interval is not a+ /// supported resample target or the base series is missing.+ QVector<trading::BrokerCandle> get_resampled(const QString& symbol, const QString& exchange,+ const QString& target_interval, qint64 from_ms,+ qint64 to_ms) const;++ // ── Watchlist (symbols flagged for auto-download) ────────────────────────++ /// Add a (symbol, exchange, interval) to the auto-download watchlist.+ /// Idempotent (INSERT OR IGNORE on the composite key).+ bool add_to_watchlist(const QString& symbol, const QString& exchange, const QString& interval);++ /// Remove a (symbol, exchange, interval) from the watchlist.+ bool remove_from_watchlist(const QString& symbol, const QString& exchange, const QString& interval);++ struct WatchEntry {+ QString symbol;+ QString exchange;+ QString interval;+ };+ /// All watchlist entries, ordered by symbol/exchange/interval.+ QVector<WatchEntry> watchlist() const;++ // ── Catalog metadata ─────────────────────────────────────────────────────++ struct CatalogEntry {+ QString symbol;+ QString exchange;+ QString interval;+ qint64 first_ts = 0; // epoch ms of earliest stored candle+ qint64 last_ts = 0; // epoch ms of latest stored candle+ int record_count = 0;+ };+ /// Per-series summary (MIN/MAX timestamp + COUNT) derived from market_data.+ QVector<CatalogEntry> catalog() const;++ // ── Export ───────────────────────────────────────────────────────────────++ /// Export a stored series to CSV: header `timestamp,open,high,low,close,+ /// volume,oi` then one row per candle (timestamp in epoch ms). [from_ms,+ /// to_ms] inclusive; pass 0 for either bound to leave it open. Returns false+ /// on query / file-write error.+ bool export_csv(const QString& symbol, const QString& exchange, const QString& interval,+ const QString& file_path, qint64 from_ms = 0, qint64 to_ms = 0) const;++ /// TODO(parquet): true columnar Parquet export requires a parquet/arrow lib+ /// (none is vendored). For now this writes CSV to `file_path` and logs a+ /// warning that Parquet was downgraded to CSV. Wire a real Parquet writer+ /// when Arrow/Parquet is added to the build.+ bool export_parquet(const QString& symbol, const QString& exchange, const QString& interval,+ const QString& file_path, qint64 from_ms = 0, qint64 to_ms = 0) const;++ // ── Auto-download hook ───────────────────────────────────────────────────++ /// Entry point for callers (a future scheduler / broker-fetch service) to+ /// push freshly fetched candles into the store for a watchlist series.+ /// Equivalent to store_candles() but named to document intent at the call+ /// site. This pass intentionally does NOT wire broker fetches — the actual+ /// download is a TODO hook (see refresh_watchlist()).+ bool refresh_now(const QString& symbol, const QString& exchange, const QString& interval,+ const QVector<trading::BrokerCandle>& candles);++ /// TODO(auto-download): periodic refresh of every watchlist entry. Not wired+ /// in this pass — broker historical fetches must be driven through the+ /// trading layer / DataHub, then the results pushed back via refresh_now().+ /// Intentionally a no-op placeholder so a scheduler can call it once the+ /// fetch path exists. Returns the number of entries it would refresh.+ int refresh_watchlist();++ private:+ HistoricalDataStore() = default;+ HistoricalDataStore(const HistoricalDataStore&) = delete;+ HistoricalDataStore& operator=(const HistoricalDataStore&) = delete;+};++} // namespace fincept::storagediff --git a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp b/fincept-qt/src/storage/repositories/PaperTradingRepository.cppindex ae24d1905..5f3438086 100644--- a/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp+++ b/fincept-qt/src/storage/repositories/PaperTradingRepository.cpp@@ -255,6 +255,36 @@ Result<void> PaperTradingRepository::delete_all_positions(const QString& portfolreturn exec_write("DELETE FROM pt_positions WHERE portfolio_id = ?", {portfolio_id});}+// ── Margin Blocks (Phase 3 §4) ───────────────────────────────────────────────++Result<void> PaperTradingRepository::insert_margin_block(const QString& id, const QString& portfolio_id,+ const QString& order_id, const QString& symbol,+ double blocked_amount) {+ // order_id is UNIQUE; use INSERT OR REPLACE so a re-block on the same order+ // overwrites rather than failing on the unique constraint.+ return exec_write("INSERT OR REPLACE INTO pt_margin_blocks "+ "(id, portfolio_id, order_id, symbol, blocked_amount) VALUES (?, ?, ?, ?, ?)",+ {id, portfolio_id, order_id, symbol, blocked_amount});+}++double PaperTradingRepository::get_margin_block(const QString& order_id) {+ auto r = db().execute("SELECT blocked_amount FROM pt_margin_blocks WHERE order_id = ?", {order_id});+ if (r.is_err())+ return 0.0;+ auto& q = r.value();+ if (!q.next())+ return 0.0;+ return q.value(0).toDouble();+}++Result<void> PaperTradingRepository::delete_margin_block(const QString& order_id) {+ return exec_write("DELETE FROM pt_margin_blocks WHERE order_id = ?", {order_id});+}++Result<void> PaperTradingRepository::delete_all_margin_blocks(const QString& portfolio_id) {+ return exec_write("DELETE FROM pt_margin_blocks WHERE portfolio_id = ?", {portfolio_id});+}+// ── Trades ───────────────────────────────────────────────────────────────────Result<void> PaperTradingRepository::insert_trade(const PtTrade& t) {diff --git a/fincept-qt/src/storage/repositories/PaperTradingRepository.h b/fincept-qt/src/storage/repositories/PaperTradingRepository.hindex 950ef7097..d747a3c19 100644--- a/fincept-qt/src/storage/repositories/PaperTradingRepository.h+++ b/fincept-qt/src/storage/repositories/PaperTradingRepository.h@@ -40,6 +40,17 @@ class PaperTradingRepository : public BaseRepository<trading::PtPortfolio> {Result<void> delete_position(const QString& id);Result<void> delete_all_positions(const QString& portfolio_id);+ // ── Margin Blocks (Phase 3 §4) ──────────────────────────────────────────+ // Tracks margin blocked from available balance per order, so the exact+ // amount can be released on fill/cancel. Backed by the existing+ // pt_margin_blocks table (created in v001_initial). order_id is UNIQUE.+ Result<void> insert_margin_block(const QString& id, const QString& portfolio_id, const QString& order_id,+ const QString& symbol, double blocked_amount);+ /// Returns the blocked amount for an order, or 0.0 if none recorded.+ double get_margin_block(const QString& order_id);+ Result<void> delete_margin_block(const QString& order_id);+ Result<void> delete_all_margin_blocks(const QString& portfolio_id);+// ── Trades ───────────────────────────────────────────────────────────────Result<void> insert_trade(const trading::PtTrade& t);Result<QVector<trading::PtTrade>> get_trades(const QString& portfolio_id, int64_t limit = 100);diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.hindex dae7e178a..7160624c5 100644--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h@@ -78,5 +78,8 @@ void register_migration_v028();void register_migration_v029();void register_migration_v030();void register_migration_v031();+void register_migration_v032();+void register_migration_v033();+void register_migration_v034();} // namespace finceptdiff --git a/fincept-qt/src/storage/sqlite/migrations/v032_pending_orders.cpp b/fincept-qt/src/storage/sqlite/migrations/v032_pending_orders.cppnew file mode 100644index 000000000..d8847b9ea--- /dev/null+++ b/fincept-qt/src/storage/sqlite/migrations/v032_pending_orders.cpp@@ -0,0 +1,65 @@+// v032_pending_orders — Action Center (semi-auto order approval), Phase 3 §2.+//+// Stores orders queued for manual approval while an account is in SemiAuto+// order mode. The per-account order mode itself lives in the `settings` table+// (key "action_center.mode.<account_id>"), not here.+//+// order_data is the serialized order JSON (no credentials). Display fields+// (symbol/action/quantity/etc.) are derived at read time from order_data, so+// they are NOT stored as columns. status ∈ {pending, approved, rejected}.++#include "storage/sqlite/migrations/MigrationRunner.h"++#include <QSqlError>+#include <QSqlQuery>++namespace fincept {+namespace {++static Result<void> sql(QSqlDatabase& db, const char* stmt) {+ QSqlQuery q(db);+ if (!q.exec(stmt))+ return Result<void>::err(q.lastError().text().toStdString());+ return Result<void>::ok();+}++Result<void> apply_v032(QSqlDatabase& db) {+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS pending_orders ("+ " id TEXT PRIMARY KEY,"+ " account_id TEXT NOT NULL,"+ " order_type TEXT NOT NULL,"+ " order_data TEXT NOT NULL,"+ " status TEXT NOT NULL DEFAULT 'pending',"+ " created_at TEXT,"+ " approved_at TEXT,"+ " rejected_at TEXT,"+ " rejection_reason TEXT,"+ " broker_order_id TEXT"+ ")");+ if (r.is_err())+ return r;++ r = sql(db, "CREATE INDEX IF NOT EXISTS idx_pending_orders_account_status "+ "ON pending_orders(account_id, status)");+ if (r.is_err())+ return r;++ r = sql(db, "CREATE INDEX IF NOT EXISTS idx_pending_orders_status "+ "ON pending_orders(status)");+ if (r.is_err())+ return r;++ return Result<void>::ok();+}++} // anonymous namespace++void register_migration_v032() {+ static bool done = false;+ if (done)+ return;+ done = true;+ MigrationRunner::register_migration({32, "pending_orders", apply_v032});+}++} // namespace finceptdiff --git a/fincept-qt/src/storage/sqlite/migrations/v033_historify.cpp b/fincept-qt/src/storage/sqlite/migrations/v033_historify.cppnew file mode 100644index 000000000..6db4494e9--- /dev/null+++ b/fincept-qt/src/storage/sqlite/migrations/v033_historify.cpp@@ -0,0 +1,89 @@+// v033_historify — Persistent historical OHLCV+OI data store (Historify), Phase 3 §13.+//+// Backs `fincept::storage::HistoricalDataStore`. Mirrors OpenAlgo's Historify+// (database/historify_db.py) but on the EXISTING SQLite stack rather than DuckDB.+//+// DECISION: SQLite, not DuckDB. The project has no DuckDB / vcpkg / conan+// dependency; pulling DuckDB in via FetchContent is too heavy/risky. The Phase 3+// doc explicitly lists SQLite as the acceptable fallback (Option B). DuckDB+// remains a possible future optimization for large-scale OLAP / backtesting+// (millions of rows) — see the TODO in HistoricalDataStore.h.+//+// Tables:+// market_data — one row per (symbol, exchange, interval, timestamp_ms).+// Base storage intervals (e.g. 1h, 1d) are stored; higher+// timeframes (4h/8h, 1w/1mo) are computed on-demand by+// HistoricalDataStore::get_resampled().+// historify_watchlist — symbols flagged for auto-download (the fetch wiring is+// a documented TODO hook; this migration only stores the+// list).+//+// timestamp_ms is epoch MILLISECONDS (matches trading::BrokerCandle::timestamp+// which the broker historical endpoints populate). NOTE: OpenAlgo uses epoch+// SECONDS — the Fincept store standardises on ms throughout.++#include "storage/sqlite/migrations/MigrationRunner.h"++#include <QSqlError>+#include <QSqlQuery>++namespace fincept {+namespace {++static Result<void> sql(QSqlDatabase& db, const char* stmt) {+ QSqlQuery q(db);+ if (!q.exec(stmt))+ return Result<void>::err(q.lastError().text().toStdString());+ return Result<void>::ok();+}++Result<void> apply_v033(QSqlDatabase& db) {+ // OHLCV+OI store. Composite primary key makes store_candles idempotent on+ // re-download (INSERT OR REPLACE collapses duplicate timestamps).+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS market_data ("+ " symbol TEXT NOT NULL,"+ " exchange TEXT NOT NULL,"+ " interval TEXT NOT NULL,"+ " timestamp_ms INTEGER NOT NULL,"+ " open REAL NOT NULL DEFAULT 0,"+ " high REAL NOT NULL DEFAULT 0,"+ " low REAL NOT NULL DEFAULT 0,"+ " close REAL NOT NULL DEFAULT 0,"+ " volume REAL NOT NULL DEFAULT 0,"+ " oi REAL NOT NULL DEFAULT 0,"+ " PRIMARY KEY (symbol, exchange, interval, timestamp_ms)"+ ")");+ if (r.is_err())+ return r;++ // Range-scan index for get_candles / get_resampled (series + time window).+ r = sql(db, "CREATE INDEX IF NOT EXISTS idx_market_data_series_time "+ "ON market_data (symbol, exchange, interval, timestamp_ms)");+ if (r.is_err())+ return r;++ // Watchlist of (symbol, exchange, interval) to auto-download.+ r = sql(db, "CREATE TABLE IF NOT EXISTS historify_watchlist ("+ " symbol TEXT NOT NULL,"+ " exchange TEXT NOT NULL,"+ " interval TEXT NOT NULL,"+ " added_at TEXT DEFAULT (datetime('now')),"+ " PRIMARY KEY (symbol, exchange, interval)"+ ")");+ if (r.is_err())+ return r;++ return Result<void>::ok();+}++} // anonymous namespace++void register_migration_v033() {+ static bool done = false;+ if (done)+ return;+ done = true;+ MigrationRunner::register_migration({33, "historify", apply_v033});+}++} // namespace finceptdiff --git a/fincept-qt/src/storage/sqlite/migrations/v034_strategy_portfolio.cpp b/fincept-qt/src/storage/sqlite/migrations/v034_strategy_portfolio.cppnew file mode 100644index 000000000..432636a79--- /dev/null+++ b/fincept-qt/src/storage/sqlite/migrations/v034_strategy_portfolio.cpp@@ -0,0 +1,83 @@+// v034_strategy_portfolio — Strategy Portfolio persistence (Phase 3 §16) and+// Quantity Freeze limits (Phase 3 §17).+//+// saved_strategies: user-saved multi-leg option strategies. Legs are serialized+// as a JSON array (one object per OptionsLeg) in the legs_json TEXT column —+// strikes/expiries/quantities vary per leg so a child table buys little here.+// See StrategyPortfolio.cpp for the leg schema.+//+// qty_freeze: per (symbol, exchange) maximum quantity an exchange accepts in a+// single order (e.g. NSE NIFTY futures = 1800). Looked up before placing an+// order; over-limit orders are auto-split via place_split_orders. See+// QtyFreeze.cpp. A few well-known NSE F&O defaults are seeded here.+//+// Version note: v033 is reserved for the parallel Historify (DuckDB) work; this+// migration deliberately takes v034 to avoid colliding with it.++#include "storage/sqlite/migrations/MigrationRunner.h"++#include <QSqlError>+#include <QSqlQuery>++namespace fincept {+namespace {++static Result<void> sql(QSqlDatabase& db, const char* stmt) {+ QSqlQuery q(db);+ if (!q.exec(stmt))+ return Result<void>::err(q.lastError().text().toStdString());+ return Result<void>::ok();+}++Result<void> apply_v034(QSqlDatabase& db) {+ // ── Saved strategy portfolio (§16) ──────────────────────────────────────+ auto r = sql(db, "CREATE TABLE IF NOT EXISTS saved_strategies ("+ " id TEXT PRIMARY KEY,"+ " name TEXT NOT NULL,"+ " underlying TEXT,"+ " notes TEXT,"+ " legs_json TEXT NOT NULL DEFAULT '[]',"+ " created_at TEXT"+ ")");+ if (r.is_err())+ return r;++ r = sql(db, "CREATE INDEX IF NOT EXISTS idx_saved_strategies_underlying "+ "ON saved_strategies(underlying)");+ if (r.is_err())+ return r;++ // ── Quantity freeze limits (§17) ────────────────────────────────────────+ r = sql(db, "CREATE TABLE IF NOT EXISTS qty_freeze ("+ " symbol TEXT NOT NULL,"+ " exchange TEXT NOT NULL,"+ " freeze_qty INTEGER NOT NULL,"+ " PRIMARY KEY (symbol, exchange)"+ ")");+ if (r.is_err())+ return r;++ // Seed a few well-known NSE F&O freeze limits. INSERT OR IGNORE so a later+ // user/admin edit is never clobbered on re-run.+ r = sql(db, "INSERT OR IGNORE INTO qty_freeze (symbol, exchange, freeze_qty) VALUES "+ " ('NIFTY', 'NFO', 1800),"+ " ('BANKNIFTY', 'NFO', 900),"+ " ('FINNIFTY', 'NFO', 1800),"+ " ('MIDCPNIFTY', 'NFO', 4200)");+ if (r.is_err())+ return r;++ return Result<void>::ok();+}++} // anonymous namespace++void register_migration_v034() {+ static bool done = false;+ if (done)+ return;+ done = true;+ MigrationRunner::register_migration({34, "strategy_portfolio", apply_v034});+}++} // namespace finceptdiff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cppindex f8595d448..6c08c4a09 100644--- a/fincept-qt/src/trading/AccountDataStream.cpp+++ b/fincept-qt/src/trading/AccountDataStream.cpp@@ -5,8 +5,18 @@#include "trading/BrokerRegistry.h"#include "trading/OrderMatcher.h"#include "trading/PaperTrading.h"+#include "trading/instruments/InstrumentService.h"#include "trading/brokers/alpaca/AlpacaWebSocket.h"+#include "trading/websocket/AliceBlueWebSocket.h"+#include "trading/websocket/BrokerWebSocketBase.h"+#include "trading/websocket/DhanWebSocket.h"+#include "trading/websocket/FivePaisaWebSocket.h"#include "trading/websocket/FyersWebSocket.h"+#include "trading/websocket/IIFLWebSocket.h"+#include "trading/websocket/KotakWebSocket.h"+#include "trading/websocket/MotilalPoller.h"+#include "trading/websocket/ShoonyaWebSocket.h"+#include "trading/websocket/UpstoxWebSocket.h"#include <QDate>#include <QDateTime>@@ -150,6 +160,28 @@ bool AccountDataStream::is_token_expired() const {return expires_at > 0 && expires_at <= QDateTime::currentSecsSinceEpoch();}+bool AccountDataStream::check_token_expiry(const QString& error) {+ // All brokers prefix expired-session errors with "[TOKEN_EXPIRED]"+ // (originated by ZerodhaBroker; generalized here so every broker benefits).+ if (!error.startsWith("[TOKEN_EXPIRED]"))+ return false;++ // May be called from a QtConcurrent worker — AccountManager mutates state+ // and we emit a signal, so marshal to the thread that owns this object.+ QPointer<AccountDataStream> self = this;+ QMetaObject::invokeMethod(this, [self]() {+ if (!self)+ return;+ AccountManager::instance().set_connection_state(+ self->account_id_, ConnectionState::TokenExpired,+ QStringLiteral("Broker session token expired"));+ LOG_WARN(ADS_TAG, QString("Token expired for account %1 (%2)")+ .arg(self->account_id_, self->broker_id_));+ emit self->token_expired(self->account_id_);+ }, Qt::QueuedConnection);+ return true;+}+void AccountDataStream::on_quote_timer() {if (is_token_expired()) {emit token_expired(account_id_);@@ -214,10 +246,8 @@ void AccountDataStream::async_fetch_quote() {auto result = broker->get_quotes(creds, {symbol});if (self) self->quote_fetching_ = false;if (!result.success || !result.data || result.data->isEmpty()) {- if (result.error.startsWith("[TOKEN_EXPIRED]") && self)- QMetaObject::invokeMethod(self, [self]() {- if (self) emit self->token_expired(self->account_id_);- }, Qt::QueuedConnection);+ if (self)+ self->check_token_expiry(result.error);return;}const auto quote = result.data->first();@@ -242,10 +272,8 @@ void AccountDataStream::async_fetch_positions() {if (!broker) return;auto result = broker->get_positions(creds);if (!result.success || !result.data) {- if (result.error.startsWith("[TOKEN_EXPIRED]") && self)- QMetaObject::invokeMethod(self, [self]() {- if (self) emit self->token_expired(self->account_id_);- }, Qt::QueuedConnection);+ if (self)+ self->check_token_expiry(result.error);return;}QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {@@ -269,10 +297,8 @@ void AccountDataStream::async_fetch_holdings() {if (!broker) return;auto result = broker->get_holdings(creds);if (!result.success || !result.data) {- if (result.error.startsWith("[TOKEN_EXPIRED]") && self)- QMetaObject::invokeMethod(self, [self]() {- if (self) emit self->token_expired(self->account_id_);- }, Qt::QueuedConnection);+ if (self)+ self->check_token_expiry(result.error);return;}QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {@@ -296,10 +322,8 @@ void AccountDataStream::async_fetch_orders() {if (!broker) return;auto result = broker->get_orders(creds);if (!result.success || !result.data) {- if (result.error.startsWith("[TOKEN_EXPIRED]") && self)- QMetaObject::invokeMethod(self, [self]() {- if (self) emit self->token_expired(self->account_id_);- }, Qt::QueuedConnection);+ if (self)+ self->check_token_expiry(result.error);return;}QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {@@ -323,10 +347,8 @@ void AccountDataStream::async_fetch_funds() {if (!broker) return;auto result = broker->get_funds(creds);if (!result.success || !result.data) {- if (result.error.startsWith("[TOKEN_EXPIRED]") && self)- QMetaObject::invokeMethod(self, [self]() {- if (self) emit self->token_expired(self->account_id_);- }, Qt::QueuedConnection);+ if (self)+ self->check_token_expiry(result.error);return;}QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {@@ -352,7 +374,11 @@ void AccountDataStream::async_fetch_watchlist_quotes() {auto* broker = BrokerRegistry::instance().get(bid);if (!broker) return;auto result = broker->get_quotes(creds, symbols.toVector());- if (!result.success || !result.data) return;+ if (!result.success || !result.data) {+ if (self)+ self->check_token_expiry(result.error);+ return;+ }QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {if (!self) return;for (const auto& q : data)@@ -402,10 +428,8 @@ void AccountDataStream::fetch_candles(const QString& symbol, const QString& timeauto result = broker->get_history(creds, symbol, timeframe, from_dt, to_dt);if (self) self->candles_fetching_ = false;if (!result.success || !result.data) {- if (result.error.startsWith("[TOKEN_EXPIRED]") && self)- QMetaObject::invokeMethod(self, [self]() {- if (self) emit self->token_expired(self->account_id_);- }, Qt::QueuedConnection);+ if (self)+ self->check_token_expiry(result.error);return;}QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {@@ -584,6 +608,38 @@ void AccountDataStream::fetch_clock() {// ── WebSocket ───────────────────────────────────────────────────────────────+void AccountDataStream::wire_base_ws(BrokerWebSocketBase* ws) {+ connect(ws, &BrokerWebSocketBase::tick_received, this, [this](const BrokerQuote& q) {+ ++ws_tick_count_;+ quote_cache_[q.symbol] = q;+ emit quote_updated(account_id_, q.symbol, q);+ });+ connect(ws, &BrokerWebSocketBase::depth_received, this, [this](const MarketDepth& d) {+ if (d.bids.isEmpty() && d.asks.isEmpty())+ return;+ QVector<QPair<double, double>> bids, asks;+ for (const auto& b : d.bids)+ bids.append({b.price, static_cast<double>(b.quantity)});+ for (const auto& a : d.asks)+ asks.append({a.price, static_cast<double>(a.quantity)});+ const double best_bid = bids.isEmpty() ? 0 : bids.first().first;+ const double best_ask = asks.isEmpty() ? 0 : asks.first().first;+ const double spread = (best_bid > 0 && best_ask > 0) ? best_ask - best_bid : 0;+ const double spread_pct = best_bid > 0 ? spread / best_bid * 100.0 : 0;+ emit orderbook_fetched(account_id_, bids, asks, spread, spread_pct, {}, {});+ });+ connect(ws, &BrokerWebSocketBase::connected, this, [this]() {+ emit connection_state_changed(account_id_, ConnectionState::Connected);+ });+ connect(ws, &BrokerWebSocketBase::disconnected, this, [this]() {+ emit connection_state_changed(account_id_, ConnectionState::Disconnected);+ });+ connect(ws, &BrokerWebSocketBase::error_occurred, this, [this](const QString& e) {+ LOG_ERROR(ADS_TAG, QString("WS error: %1").arg(e));+ check_token_expiry(e);+ });+}+void AccountDataStream::ws_init() {if (broker_id_ == "fyers") {auto creds = AccountManager::instance().load_credentials(account_id_);@@ -650,6 +706,7 @@ void AccountDataStream::ws_init() {connect(fws, &FyersWebSocket::error_occurred, this, [this](const QString& err) {LOG_ERROR(ADS_TAG, QString("Fyers WS error: %1").arg(err));+ check_token_expiry(err);});fws->open();@@ -716,6 +773,7 @@ void AccountDataStream::ws_init() {connect(aws, &AlpacaWebSocket::error_occurred, this, [this](const QString& err) {LOG_ERROR(ADS_TAG, QString("Alpaca WS error: %1").arg(err));+ check_token_expiry(err);});connect(aws, &AlpacaWebSocket::market_closed, this, [this]() {@@ -726,6 +784,213 @@ void AccountDataStream::ws_init() {return;}+ // ── Phase 2 broker WebSocket adapters (shared BrokerWebSocketBase) ─────────+ // Helper: collect the current selected + watchlist symbols (deduped).+ auto current_symbols = [this]() {+ QStringList syms;+ if (!selected_symbol_.isEmpty())+ syms.append(selected_symbol_);+ for (const auto& s : watchlist_symbols_) {+ if (!syms.contains(s))+ syms.append(s);+ }+ syms.removeDuplicates();+ return syms;+ };+ // Helper: resolve symbols → numeric instrument tokens via InstrumentService+ // for this broker. Symbols that don't resolve are skipped.+ auto resolve_tokens = [this](const QStringList& syms) {+ QVector<qint64> tokens;+ auto& svc = InstrumentService::instance();+ for (const auto& s : syms) {+ const QString exch = (s == selected_symbol_ && !selected_exchange_.isEmpty())+ ? selected_exchange_+ : QStringLiteral("NSE");+ auto tok = svc.instrument_token(s, exch, broker_id_);+ if (tok.has_value())+ tokens.append(*tok);+ }+ return tokens;+ };++ if (broker_id_ == "upstox") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ if (creds.access_token.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("Upstox WS: missing access_token for %1").arg(account_id_));+ return;+ }+ auto* uws = new UpstoxWebSocket(creds.access_token, this);+ ws_ = uws;+ wire_base_ws(uws);+ connect(uws, &UpstoxWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("Upstox WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<UpstoxWebSocket*>(ws_))+ w->subscribe(resolve_tokens(current_symbols()));+ });+ uws->open();+ return;+ }++ if (broker_id_ == "dhan") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ if (creds.access_token.isEmpty() || creds.api_key.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("Dhan WS: missing access_token/client_id for %1").arg(account_id_));+ return;+ }+ auto* dws = new DhanWebSocket(creds.access_token, creds.api_key, this);+ ws_ = dws;+ wire_base_ws(dws);+ connect(dws, &DhanWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("Dhan WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<DhanWebSocket*>(ws_))+ w->subscribe(resolve_tokens(current_symbols()));+ });+ dws->open();+ return;+ }++ if (broker_id_ == "kotak") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ const QStringList parts = creds.access_token.split(":::");+ if (parts.size() < 4) {+ LOG_WARN(ADS_TAG, QString("Kotak WS: malformed token for %1").arg(account_id_));+ return;+ }+ // Packed: "trading_token:::trading_sid:::base_url:::access_token[:::server_id]"+ const QString auth_token = parts.value(0); // JWT → "Authorization"+ const QString sid = parts.value(1); // redis session → "Sid"+ const QString access_tok = parts.value(3);+ const QString server_id = parts.value(4);+ if (auth_token.isEmpty() || sid.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("Kotak WS: missing auth_token/sid for %1").arg(account_id_));+ return;+ }+ auto* kws = new KotakWebSocket(auth_token, sid, server_id, access_tok, this);+ ws_ = kws;+ wire_base_ws(kws);+ connect(kws, &KotakWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("Kotak WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<KotakWebSocket*>(ws_)) {+ if (!selected_exchange_.isEmpty())+ w->set_default_exchange(selected_exchange_);+ w->subscribe(resolve_tokens(current_symbols()));+ }+ });+ kws->open();+ return;+ }++ if (broker_id_ == "iifl") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ // access_token packed as "trade_token:::feed_token"; feed token is for market data.+ const QStringList parts = creds.access_token.split(":::");+ const QString market_token = parts.size() >= 2 ? parts.value(1) : creds.access_token;+ if (market_token.isEmpty() || creds.user_id.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("IIFL WS: missing market_token/user_id for %1").arg(account_id_));+ return;+ }+ auto* iws = new IIFLWebSocket(market_token, creds.user_id, this);+ ws_ = iws;+ wire_base_ws(iws);+ connect(iws, &IIFLWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("IIFL WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<IIFLWebSocket*>(ws_)) {+ if (!selected_exchange_.isEmpty())+ w->set_default_exchange(selected_exchange_);+ w->subscribe(resolve_tokens(current_symbols()));+ }+ });+ iws->open();+ return;+ }++ if (broker_id_ == "fivepaisa") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ // client_code = 3rd ":::" part of ApiKey ("app_key:::user_id:::client_id"),+ // falling back to user_id when absent.+ const QStringList key_parts = creds.api_key.split(":::");+ QString client_code = key_parts.size() >= 3 ? key_parts.value(2) : QString();+ if (client_code.isEmpty())+ client_code = creds.user_id;+ if (creds.access_token.isEmpty() || client_code.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("5Paisa WS: missing access_token/client_code for %1").arg(account_id_));+ return;+ }+ auto* fws = new FivePaisaWebSocket(creds.access_token, client_code, this);+ ws_ = fws;+ wire_base_ws(fws);+ connect(fws, &FivePaisaWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("5Paisa WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<FivePaisaWebSocket*>(ws_))+ w->subscribe(resolve_tokens(current_symbols()));+ });+ fws->open();+ return;+ }++ if (broker_id_ == "aliceblue") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ // client_id stored in user_id; session JWT in access_token.+ if (creds.user_id.isEmpty() || creds.access_token.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("AliceBlue WS: missing client_id/jwt for %1").arg(account_id_));+ return;+ }+ auto* aws = new AliceBlueWebSocket(creds.user_id, creds.access_token, this);+ ws_ = aws;+ wire_base_ws(aws);+ connect(aws, &AliceBlueWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("AliceBlue WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<AliceBlueWebSocket*>(ws_)) {+ if (!selected_exchange_.isEmpty())+ w->set_default_exchange(selected_exchange_);+ w->subscribe(resolve_tokens(current_symbols()));+ }+ });+ aws->open();+ return;+ }++ if (broker_id_ == "shoonya") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ // user_id = uid/actid; access_token = susertoken (sent verbatim).+ if (creds.user_id.isEmpty() || creds.access_token.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("Shoonya WS: missing user_id/susertoken for %1").arg(account_id_));+ return;+ }+ auto* sws = new ShoonyaWebSocket(creds.user_id, creds.user_id, creds.access_token, this);+ ws_ = sws;+ wire_base_ws(sws);+ connect(sws, &ShoonyaWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {+ LOG_INFO(ADS_TAG, QString("Shoonya WS connected for %1").arg(account_id_));+ if (auto* w = qobject_cast<ShoonyaWebSocket*>(ws_)) {+ if (!selected_exchange_.isEmpty())+ w->set_default_exchange(selected_exchange_);+ w->subscribe(resolve_tokens(current_symbols()));+ }+ });+ sws->open();+ return;+ }++ if (broker_id_ == "motilal") {+ auto creds = AccountManager::instance().load_credentials(account_id_);+ if (creds.api_key.isEmpty()) {+ LOG_WARN(ADS_TAG, QString("Motilal poller: missing credentials for %1").arg(account_id_));+ return;+ }+ // Motilal has no streaming socket — MotilalPoller polls quotes by symbol.+ auto* mp = new MotilalPoller(creds, this);+ ws_ = mp;+ wire_base_ws(mp);+ connect(mp, &MotilalPoller::connected, this, [this, current_symbols]() {+ LOG_INFO(ADS_TAG, QString("Motilal poller started for %1").arg(account_id_));+ if (auto* w = qobject_cast<MotilalPoller*>(ws_))+ w->subscribe(current_symbols());+ });+ mp->open();+ return;+ }+if (broker_id_ != "angelone")return;@@ -761,6 +1026,8 @@ bool AccountDataStream::ws_active() const {return fws->is_connected() && ws_tick_count_ > 0;if (auto* aws = qobject_cast<AlpacaWebSocket*>(ws_))return aws->is_connected() && ws_tick_count_ > 0;+ if (auto* b = qobject_cast<BrokerWebSocketBase*>(ws_))+ return b->is_connected() && ws_tick_count_ > 0;return false;}@@ -788,6 +1055,39 @@ void AccountDataStream::ws_resubscribe() {}aws->set_subscriptions(symbols);}++ // Generic Phase 2 adapters (shared BrokerWebSocketBase). Rebuild the symbol+ // set wholesale: drop existing subscriptions, then subscribe the current set.+ if (auto* b = qobject_cast<BrokerWebSocketBase*>(ws_)) {+ QStringList symbols;+ if (!selected_symbol_.isEmpty())+ symbols.append(selected_symbol_);+ for (const auto& s : watchlist_symbols_) {+ if (!symbols.contains(s))+ symbols.append(s);+ }+ symbols.removeDuplicates();++ // Motilal polls by symbol — feed it the symbol list directly.+ if (auto* mp = qobject_cast<MotilalPoller*>(ws_)) {+ mp->subscribe(symbols);+ return;+ }++ // Token-based adapters: resolve symbols → instrument tokens.+ QVector<qint64> tokens;+ auto& svc = InstrumentService::instance();+ for (const auto& s : symbols) {+ const QString exch = (s == selected_symbol_ && !selected_exchange_.isEmpty())+ ? selected_exchange_+ : QStringLiteral("NSE");+ auto tok = svc.instrument_token(s, exch, broker_id_);+ if (tok.has_value())+ tokens.append(*tok);+ }+ b->unsubscribe();+ b->subscribe(tokens);+ }}} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/AccountDataStream.h b/fincept-qt/src/trading/AccountDataStream.hindex 6ed04e31d..1f078ffec 100644--- a/fincept-qt/src/trading/AccountDataStream.h+++ b/fincept-qt/src/trading/AccountDataStream.h@@ -82,6 +82,14 @@ class AccountDataStream : public QObject {// --- Token expiry check ---bool is_token_expired() const;+ // Inspect a broker error string for the "[TOKEN_EXPIRED]" prefix that all+ // brokers use to signal an expired/invalid session. When detected, marks+ // the account ConnectionState::TokenExpired via AccountManager and emits+ // token_expired(). Safe to call from any thread — marshals to the main+ // thread before touching AccountManager / emitting signals. No-op if the+ // error does not indicate token expiry. Returns true if expiry was handled.+ bool check_token_expiry(const QString& error);+// --- Async fetch methods (all follow P8: QPointer + QtConcurrent + QueuedConnection) ---void async_fetch_quote();void async_fetch_positions();@@ -100,6 +108,9 @@ class AccountDataStream : public QObject {void ws_teardown();bool ws_active() const;void ws_resubscribe();+ // Wire the common BrokerWebSocketBase signals (tick/depth/connect/error) into+ // this stream. Used by all Phase 2 adapters that share BrokerWebSocketBase.+ void wire_base_ws(class BrokerWebSocketBase* ws);// --- State ---QString account_id_;diff --git a/fincept-qt/src/trading/ActionCenter.cpp b/fincept-qt/src/trading/ActionCenter.cppnew file mode 100644index 000000000..ba6eb2d48--- /dev/null+++ b/fincept-qt/src/trading/ActionCenter.cpp@@ -0,0 +1,438 @@+// ActionCenter.cpp — semi-auto order approval implementation (Phase 3 §2).+#include "trading/ActionCenter.h"++#include "core/logging/Logger.h"+#include "storage/repositories/SettingsRepository.h"+#include "storage/sqlite/Database.h"+#include "trading/AccountManager.h"+#include "trading/TradingEvents.h"+#include "trading/UnifiedTrading.h"++#include <QJsonArray>+#include <QJsonDocument>+#include <QSqlQuery>+#include <QUuid>++#include <cmath>++namespace fincept::trading {++namespace {+constexpr const char* kLog = "ActionCenter";++QString iso(const QDateTime& dt) { return dt.isValid() ? dt.toString(Qt::ISODate) : QString(); }+QDateTime from_iso(const QString& s) { return s.isEmpty() ? QDateTime() : QDateTime::fromString(s, Qt::ISODate); }+} // namespace++ActionCenter& ActionCenter::instance() {+ static ActionCenter s;+ return s;+}++const QSet<QString>& ActionCenter::immediate_ops() {+ // Risk-management + read-only ops always execute immediately, never queued.+ // Mirrors OpenAlgo order_router_service.py IMMEDIATE_EXECUTION_OPERATIONS.+ static const QSet<QString> ops = {+ "closeallpositions", "closeposition", "cancelorder", "cancelallorder",+ "modifyorder", "orderstatus", "orderbook", "tradebook", "positions",+ "holdings", "funds", "openposition", "modifygttorder", "cancelgttorder",+ "gttorderbook",+ };+ return ops;+}++// ── Route decision ─────────────────────────────────────────────────────────++bool ActionCenter::should_queue(const QString& account_id, const QString& order_type) const {+ if (immediate_ops().contains(order_type.toLower()))+ return false;+ return get_order_mode(account_id) == OrderMode::SemiAuto;+}++// ── Mode (persisted in settings) ───────────────────────────────────────────++void ActionCenter::set_order_mode(const QString& account_id, OrderMode mode) {+ const QString key = "action_center.mode." + account_id;+ SettingsRepository::instance().set(key, order_mode_str(mode), "action_center");+ LOG_INFO(kLog, QString("Order mode for %1 set to %2").arg(account_id, order_mode_str(mode)));+ emit stats_updated(account_id);+}++OrderMode ActionCenter::get_order_mode(const QString& account_id) const {+ const QString key = "action_center.mode." + account_id;+ auto r = SettingsRepository::instance().get(key, "auto");+ return parse_order_mode(r.is_ok() ? r.value() : QString("auto"));+}++// ── Serialization ──────────────────────────────────────────────────────────++QJsonObject ActionCenter::serialize_unified_order(const UnifiedOrder& order) {+ QJsonObject j;+ j["symbol"] = order.symbol;+ j["exchange"] = order.exchange;+ j["action"] = order.side == OrderSide::Buy ? "BUY" : "SELL";+ j["quantity"] = order.quantity;+ j["price"] = order.price;+ j["trigger_price"] = order.stop_price;+ j["stop_price"] = order.stop_price;+ // price_type in OpenAlgo terms (MARKET/LIMIT/SL/SL-M).+ QString pt;+ switch (order.order_type) {+ case OrderType::Market: pt = "MARKET"; break;+ case OrderType::Limit: pt = "LIMIT"; break;+ case OrderType::StopLoss: pt = "SL-M"; break;+ case OrderType::StopLossLimit: pt = "SL"; break;+ }+ j["pricetype"] = pt;+ j["product"] = QString::fromLatin1(product_type_str(order.product_type));+ j["validity"] = order.validity;+ j["stop_loss"] = order.stop_loss;+ j["take_profit"] = order.take_profit;+ j["amo"] = order.amo;+ j["instrument_token"] = order.instrument_token;+ return j;+}++UnifiedOrder ActionCenter::deserialize_unified_order(const QJsonObject& json) {+ UnifiedOrder o;+ o.symbol = json.value("symbol").toString();+ o.exchange = json.value("exchange").toString();+ o.side = json.value("action").toString().toUpper() == "SELL" ? OrderSide::Sell : OrderSide::Buy;+ o.quantity = json.value("quantity").toDouble();+ o.price = json.value("price").toDouble();+ o.stop_price = json.contains("stop_price") ? json.value("stop_price").toDouble()+ : json.value("trigger_price").toDouble();++ const QString pt = json.value("pricetype").toString().toUpper();+ if (pt == "LIMIT")+ o.order_type = OrderType::Limit;+ else if (pt == "SL")+ o.order_type = OrderType::StopLossLimit;+ else if (pt == "SL-M")+ o.order_type = OrderType::StopLoss;+ else+ o.order_type = OrderType::Market;++ const QString prod = json.value("product").toString().toLower();+ if (prod == "delivery" || prod == "cnc")+ o.product_type = ProductType::Delivery;+ else if (prod == "margin" || prod == "nrml")+ o.product_type = ProductType::Margin;+ else if (prod == "cover_order")+ o.product_type = ProductType::CoverOrder;+ else if (prod == "bracket_order")+ o.product_type = ProductType::BracketOrder;+ else if (prod == "mtf")+ o.product_type = ProductType::MTF;+ else+ o.product_type = ProductType::Intraday;++ o.validity = json.value("validity").toString("DAY");+ o.stop_loss = json.value("stop_loss").toDouble();+ o.take_profit = json.value("take_profit").toDouble();+ o.amo = json.value("amo").toBool();+ o.instrument_token = json.value("instrument_token").toString();+ return o;+}++// ── Display fields ─────────────────────────────────────────────────────────++void ActionCenter::populate_display_fields(PendingOrder& po) {+ const QJsonObject& d = po.order_data;+ po.strategy = d.value("strategy").toString("N/A");++ auto qty_str = [](const QJsonValue& v) -> QString {+ if (v.isDouble()) {+ double q = v.toDouble();+ // show ints without trailing .0+ return q == std::floor(q) ? QString::number((qint64)q) : QString::number(q);+ }+ return v.toString();+ };++ if (po.order_type == "basketorder") {+ const QJsonArray orders = d.value("orders").toArray();+ po.symbol = QString("Basket (%1 orders)").arg(orders.size());+ po.exchange = orders.size() > 1 ? "Multiple"+ : (orders.isEmpty() ? "" : orders.first().toObject().value("exchange").toString());+ po.action = orders.size() > 1 ? "Multiple"+ : (orders.isEmpty() ? "" : orders.first().toObject().value("action").toString());+ qint64 total = 0;+ for (const auto& v : orders)+ total += (qint64)v.toObject().value("quantity").toDouble();+ po.quantity = QString::number(total);+ po.price_type = orders.size() > 1 ? "Multiple"+ : (orders.isEmpty() ? "" : orders.first().toObject().value("pricetype").toString("MARKET"));+ return;+ }++ if (po.order_type == "splitorder") {+ po.symbol = d.value("symbol").toString();+ po.exchange = d.value("exchange").toString();+ po.action = d.value("action").toString();+ po.quantity = QString("%1 (split: %2)").arg(qty_str(d.value("quantity")),+ qty_str(d.value("splitsize")));+ po.price_type = d.value("pricetype").toString("MARKET");+ return;+ }++ // placeorder / smartorder / placegttorder default.+ po.symbol = d.value("symbol").toString();+ po.exchange = d.value("exchange").toString();+ po.action = d.value("action").toString();+ po.quantity = qty_str(d.value("quantity"));+ po.price_type = d.value("pricetype").toString(d.value("price_type").toString("MARKET"));+}++// ── Persistence ────────────────────────────────────────────────────────────++QString ActionCenter::queue_order(const QString& account_id, const QString& order_type,+ const QJsonObject& order_data) {+ PendingOrder po;+ po.id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ po.account_id = account_id;+ po.order_type = order_type;+ // Strip credential-like keys defensively.+ QJsonObject clean = order_data;+ clean.remove("apikey");+ clean.remove("api_key");+ clean.remove("api_secret");+ clean.remove("access_token");+ po.order_data = clean;+ po.status = "pending";+ po.created_at = QDateTime::currentDateTime();+ populate_display_fields(po);++ const QString json_str = QString::fromUtf8(QJsonDocument(po.order_data).toJson(QJsonDocument::Compact));+ auto r = Database::instance().execute(+ "INSERT INTO pending_orders (id, account_id, order_type, order_data, status, created_at) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ {po.id, po.account_id, po.order_type, json_str, po.status, iso(po.created_at)});+ if (r.is_err()) {+ LOG_ERROR(kLog, QString("queue_order failed: %1").arg(QString::fromStdString(r.error())));+ return {};+ }++ LOG_INFO(kLog, QString("Queued %1 order %2 for account %3").arg(order_type, po.id, account_id));+ emit pending_order_created(po);+ emit stats_updated(account_id);+ return po.id;+}++PendingOrder ActionCenter::map_row(QSqlQuery& q) {+ PendingOrder po;+ po.id = q.value("id").toString();+ po.account_id = q.value("account_id").toString();+ po.order_type = q.value("order_type").toString();+ po.order_data = QJsonDocument::fromJson(q.value("order_data").toString().toUtf8()).object();+ po.status = q.value("status").toString();+ po.created_at = from_iso(q.value("created_at").toString());+ po.approved_at = from_iso(q.value("approved_at").toString());+ po.rejected_at = from_iso(q.value("rejected_at").toString());+ po.rejection_reason = q.value("rejection_reason").toString();+ po.broker_order_id = q.value("broker_order_id").toString();+ populate_display_fields(po);+ return po;+}++std::optional<PendingOrder> ActionCenter::get_order(const QString& pending_id) const {+ auto r = Database::instance().execute("SELECT * FROM pending_orders WHERE id = ?", {pending_id});+ if (r.is_err())+ return std::nullopt;+ auto& q = r.value();+ if (!q.next())+ return std::nullopt;+ return map_row(q);+}++QVector<PendingOrder> ActionCenter::get_pending_orders(const QString& account_id) const {+ QVector<PendingOrder> out;+ QString sql = "SELECT * FROM pending_orders WHERE status = 'pending'";+ QVariantList params;+ if (!account_id.isEmpty()) {+ sql += " AND account_id = ?";+ params << account_id;+ }+ sql += " ORDER BY created_at DESC";+ auto r = Database::instance().execute(sql, params);+ if (r.is_err())+ return out;+ auto& q = r.value();+ while (q.next())+ out.append(map_row(q));+ return out;+}++QVector<PendingOrder> ActionCenter::get_all_orders(const QString& account_id, int limit) const {+ QVector<PendingOrder> out;+ QString sql = "SELECT * FROM pending_orders";+ QVariantList params;+ if (!account_id.isEmpty()) {+ sql += " WHERE account_id = ?";+ params << account_id;+ }+ sql += " ORDER BY created_at DESC LIMIT ?";+ params << limit;+ auto r = Database::instance().execute(sql, params);+ if (r.is_err())+ return out;+ auto& q = r.value();+ while (q.next())+ out.append(map_row(q));+ return out;+}++ActionCenter::Stats ActionCenter::get_stats(const QString& account_id) const {+ Stats s;+ // Stats are computed across ALL orders (matches OpenAlgo behaviour: tabs+ // always show correct totals regardless of the active status filter).+ const auto orders = get_all_orders(account_id, 100000);+ for (const auto& o : orders) {+ if (o.status == "pending")+ ++s.total_pending;+ else if (o.status == "approved")+ ++s.total_approved;+ else if (o.status == "rejected")+ ++s.total_rejected;++ const QString act = o.action.toUpper();+ if (act == "BUY")+ ++s.total_buy;+ else if (act == "SELL")+ ++s.total_sell;++ if (o.order_type == "placeorder")+ ++s.by_type_place;+ else if (o.order_type == "smartorder")+ ++s.by_type_smart;+ else if (o.order_type == "basketorder")+ ++s.by_type_basket;+ }+ return s;+}++// ── Execution on approval ──────────────────────────────────────────────────++QString ActionCenter::execute_pending(const PendingOrder& po, bool& ok, QString& err) {+ ok = false;+ if (po.order_type == "placeorder" || po.order_type == "smartorder" ||+ po.order_type == "placegttorder") {+ // Smart/GTT collapse to a standard place via UnifiedTrading for now —+ // the serialized order carries the same fields. (place_smart_order /+ // GTT-specific routing can be wired here later without changing the+ // queue/approve contract.)+ UnifiedOrder order = deserialize_unified_order(po.order_data);+ UnifiedOrderResponse resp = UnifiedTrading::instance().place_order(po.account_id, order);+ ok = resp.success;+ err = resp.message;+ return resp.order_id;+ }++ if (po.order_type == "basketorder") {+ BasketOrderRequest basket;+ basket.strategy_name = po.order_data.value("strategy").toString();+ const QJsonArray arr = po.order_data.value("orders").toArray();+ for (const auto& v : arr)+ basket.orders.append(deserialize_unified_order(v.toObject()));+ // place_basket_orders is async (background thread + callback). For the+ // approval gate we fire it and report acceptance immediately; per-leg+ // results surface via the trading event bus / order book.+ UnifiedTrading::instance().place_basket_orders(po.account_id, basket,+ [](const BasketOrderResult&) {});+ ok = true;+ err.clear();+ return {}; // no single broker order id for a basket+ }++ if (po.order_type == "splitorder") {+ SplitOrderRequest req;+ req.base_order = deserialize_unified_order(po.order_data);+ req.split_size = po.order_data.value("splitsize").toInt(+ (int)po.order_data.value("split_size").toDouble());+ req.delay_between_ms = po.order_data.value("delay_between_ms").toInt(100);+ UnifiedTrading::instance().place_split_orders(po.account_id, req,+ [](const SplitOrderResult&) {});+ ok = true;+ err.clear();+ return {};+ }++ err = "Unknown order_type: " + po.order_type;+ return {};+}++void ActionCenter::approve_order(const QString& pending_id) {+ auto po_opt = get_order(pending_id);+ if (!po_opt) {+ LOG_WARN(kLog, "approve_order: pending id not found: " + pending_id);+ return;+ }+ PendingOrder po = *po_opt;+ if (po.status != "pending") {+ LOG_WARN(kLog, QString("approve_order: %1 is not pending (status=%2)").arg(pending_id, po.status));+ return;+ }++ bool ok = false;+ QString err;+ const QString broker_order_id = execute_pending(po, ok, err);++ const QDateTime now = QDateTime::currentDateTime();+ auto r = Database::instance().execute(+ "UPDATE pending_orders SET status = ?, approved_at = ?, broker_order_id = ?, "+ "rejection_reason = ? WHERE id = ?",+ {ok ? "approved" : "rejected", iso(now), broker_order_id,+ ok ? QString() : ("Execution failed: " + err), pending_id});+ if (r.is_err())+ LOG_ERROR(kLog, QString("approve_order update failed: %1").arg(QString::fromStdString(r.error())));++ if (ok) {+ LOG_INFO(kLog, QString("Approved %1 → broker order %2").arg(pending_id, broker_order_id));+ emit order_approved(pending_id, broker_order_id);+ } else {+ LOG_WARN(kLog, QString("Approval of %1 executed but broker rejected: %2").arg(pending_id, err));+ emit order_rejected(pending_id, "Execution failed: " + err);+ }+ emit stats_updated(po.account_id);+}++void ActionCenter::reject_order(const QString& pending_id, const QString& reason) {+ auto po_opt = get_order(pending_id);+ if (!po_opt) {+ LOG_WARN(kLog, "reject_order: pending id not found: " + pending_id);+ return;+ }+ PendingOrder po = *po_opt;+ if (po.status != "pending")+ return;++ const QDateTime now = QDateTime::currentDateTime();+ auto r = Database::instance().execute(+ "UPDATE pending_orders SET status = 'rejected', rejected_at = ?, rejection_reason = ? WHERE id = ?",+ {iso(now), reason, pending_id});+ if (r.is_err()) {+ LOG_ERROR(kLog, QString("reject_order update failed: %1").arg(QString::fromStdString(r.error())));+ return;+ }+ LOG_INFO(kLog, QString("Rejected %1: %2").arg(pending_id, reason));+ emit order_rejected(pending_id, reason);+ emit stats_updated(po.account_id);+}++void ActionCenter::approve_all_pending(const QString& account_id) {+ const auto pending = get_pending_orders(account_id);+ for (const auto& po : pending)+ approve_order(po.id);+ if (!pending.isEmpty())+ emit stats_updated(account_id);+}++void ActionCenter::reject_all_pending(const QString& account_id, const QString& reason) {+ const auto pending = get_pending_orders(account_id);+ for (const auto& po : pending)+ reject_order(po.id, reason);+ if (!pending.isEmpty())+ emit stats_updated(account_id);+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/ActionCenter.h b/fincept-qt/src/trading/ActionCenter.hnew file mode 100644index 000000000..48398c1b5--- /dev/null+++ b/fincept-qt/src/trading/ActionCenter.h@@ -0,0 +1,145 @@+#pragma once+// ActionCenter — semi-auto order approval (OpenAlgo bridge, Phase 3 §2).+//+// In SemiAuto mode, queueable order operations (placeorder/smartorder/+// basketorder/splitorder/placegttorder) are NOT sent to the broker+// immediately — they are persisted as PendingOrder records and surfaced in+// the Action Center UI, where the user can Approve (execute) or Reject (drop+// with a reason). Risk-management and read-only operations always execute+// immediately and are never queued.+//+// Design note (anti-recursion): ActionCenter is a *pre-gate* that the UI/screen+// layer consults BEFORE calling UnifiedTrading::place_order(). It is NOT an+// interceptor inside place_order(). On approval, ActionCenter deserializes the+// stored order and calls UnifiedTrading::instance().place_order(account_id,+// order) directly — place_order does not itself consult ActionCenter, so there+// is no recursion. (See OpenAlgo order_router_service.py for the original flow.)+//+// Persistence: pending orders live in the SQLite `pending_orders` table+// (migration v032). Per-account order mode is stored in the `settings` table+// via SettingsRepository (key "action_center.mode.<account_id>").++#include "trading/TradingTypes.h"++#include <QDateTime>+#include <QJsonObject>+#include <QObject>+#include <QSet>+#include <QString>+#include <QVector>++#include <optional>++namespace fincept::trading {++enum class OrderMode {+ Auto, // execute immediately (default)+ SemiAuto, // queue queueable ops for manual approval+};++inline const char* order_mode_str(OrderMode m) {+ return m == OrderMode::SemiAuto ? "semi_auto" : "auto";+}++inline OrderMode parse_order_mode(const QString& s) {+ return s == "semi_auto" ? OrderMode::SemiAuto : OrderMode::Auto;+}++/// A queued order awaiting approval / rejection.+struct PendingOrder {+ QString id; // UUID+ QString account_id; // owning broker account+ QString order_type; // "placeorder","smartorder","basketorder","splitorder","placegttorder"+ QJsonObject order_data; // serialized order (no credentials)+ QString status; // "pending","approved","rejected"+ QDateTime created_at;+ QDateTime approved_at;+ QDateTime rejected_at;+ QString rejection_reason;+ QString broker_order_id; // set after execution on approval++ // Parsed display fields (derived from order_data for the table view).+ QString symbol;+ QString exchange;+ QString action; // "BUY" / "SELL" / "Multiple"+ QString quantity;+ QString price_type;+ QString strategy;+};++class ActionCenter : public QObject {+ Q_OBJECT+ public:+ static ActionCenter& instance();++ // Route decision: returns true only when the account is in SemiAuto mode+ // AND the operation is queueable (not in IMMEDIATE_OPS). The caller (screen+ // layer) consults this before placing the order.+ bool should_queue(const QString& account_id, const QString& order_type) const;++ // Queue an order for approval. Returns the new pending id (empty on failure).+ // `order_data` should NOT contain credentials. Emits pending_order_created.+ QString queue_order(const QString& account_id, const QString& order_type,+ const QJsonObject& order_data);++ // User actions.+ void approve_order(const QString& pending_id);+ void reject_order(const QString& pending_id, const QString& reason);+ void approve_all_pending(const QString& account_id = {});+ void reject_all_pending(const QString& account_id, const QString& reason);++ // Query.+ QVector<PendingOrder> get_pending_orders(const QString& account_id = {}) const;+ QVector<PendingOrder> get_all_orders(const QString& account_id = {}, int limit = 100) const;+ std::optional<PendingOrder> get_order(const QString& pending_id) const;++ // Statistics (mirrors OpenAlgo's calculate_action_center_stats).+ struct Stats {+ int total_pending = 0;+ int total_approved = 0;+ int total_rejected = 0;+ int total_buy = 0;+ int total_sell = 0;+ int by_type_place = 0;+ int by_type_smart = 0;+ int by_type_basket = 0;+ };+ Stats get_stats(const QString& account_id = {}) const;++ // Per-account order mode (persisted in settings).+ void set_order_mode(const QString& account_id, OrderMode mode);+ OrderMode get_order_mode(const QString& account_id) const;++ // ── Serialization helpers (shared with screens / order entry) ────────────+ // Serialize a UnifiedOrder into the JSON form stored in order_data. Round+ // trips with deserialize_unified_order(). No credentials are included.+ static QJsonObject serialize_unified_order(const UnifiedOrder& order);+ static UnifiedOrder deserialize_unified_order(const QJsonObject& json);++ signals:+ void pending_order_created(const fincept::trading::PendingOrder& order);+ void order_approved(const QString& pending_id, const QString& broker_order_id);+ void order_rejected(const QString& pending_id, const QString& reason);+ void stats_updated(const QString& account_id);++ private:+ ActionCenter() = default;++ // Operations that always execute immediately (never queued).+ static const QSet<QString>& immediate_ops();++ // Parse the display fields on a PendingOrder from its order_data + type.+ static void populate_display_fields(PendingOrder& po);++ // Row mapper for the pending_orders table.+ static PendingOrder map_row(class QSqlQuery& q);++ // Execute a queued order against UnifiedTrading. Returns the broker order id+ // (empty on failure) and sets `ok`/`err`.+ QString execute_pending(const PendingOrder& po, bool& ok, QString& err);+};++} // namespace fincept::trading++#include <QMetaType>+Q_DECLARE_METATYPE(fincept::trading::PendingOrder)diff --git a/fincept-qt/src/trading/BrokerInterface.h b/fincept-qt/src/trading/BrokerInterface.hindex 71fd850fa..6795525b7 100644--- a/fincept-qt/src/trading/BrokerInterface.h+++ b/fincept-qt/src/trading/BrokerInterface.h@@ -37,6 +37,47 @@ struct ProductTypeDef {trading::ProductType value;};+// ============================================================================+// estimate_order_margin — shared fallback margin estimator+// Used by brokers that have no native pre-trade margin API (OpenAlgo's Python+// raises NotImplementedError for these). Mirrors Phase 3 §5's heuristic:+// Intraday → 20% (≈5x)+// Delivery → 100% (full payment)+// Futures → 10% (≈10x)+// Option buy → premium (full)+// Option sell→ 15% (SPAN estimate)+// default → 20%+// ============================================================================+inline OrderMargin estimate_order_margin(const UnifiedOrder& order) {+ const double trade_value = order.quantity * order.price;+ OrderMargin m;+ m.symbol = order.symbol;+ m.exchange = order.exchange;+ m.side = (order.side == OrderSide::Buy) ? "BUY" : "SELL";+ m.quantity = order.quantity;+ m.price = order.price;++ const bool is_opt = order.symbol.endsWith("CE") || order.symbol.endsWith("PE");+ const bool is_fut = order.symbol.contains("FUT");++ if (order.product_type == ProductType::Intraday)+ m.total = trade_value * 0.20; // ~5x+ else if (order.product_type == ProductType::Delivery)+ m.total = trade_value; // full payment+ else if (is_fut)+ m.total = trade_value * 0.10; // ~10x+ else if (is_opt && order.side == OrderSide::Buy)+ m.total = trade_value; // premium only+ else if (is_opt)+ m.total = trade_value * 0.15; // sell SPAN estimate+ else+ m.total = trade_value * 0.20;++ m.cash = m.total;+ m.leverage = (m.total > 0.0) ? trade_value / m.total : 1.0;+ return m;+}+struct BrokerProfile {// IdentityQString id; // e.g. "alpaca"@@ -277,6 +318,115 @@ class IBroker {return {false, std::nullopt, "GTT not supported for this broker"};}+ // --- Bulk Operations (Phase 1: OpenAlgo bridge) ---++ /// Cancel all open/pending orders. Default: fetch order book, cancel each open order.+ virtual ApiResponse<CancelAllResult> cancel_all_orders(const BrokerCredentials& creds) {+ CancelAllResult result;+ auto orders_resp = get_orders(creds);+ if (!orders_resp.success)+ return {false, std::nullopt, orders_resp.error};+ for (const auto& o : orders_resp.data.value_or(QVector<BrokerOrderInfo>{})) {+ auto s = o.status.toLower();+ if (s == "open" || s == "pending" || s == "new" || s == "trigger pending"+ || s == "trigger_pending" || s == "ordered" || s == "transit"+ || s == "accepted" || s == "partially_filled" || s == "working") {+ result.total_attempted++;+ auto r = cancel_order(creds, o.order_id);+ if (r.success)+ result.canceled_order_ids.append(o.order_id);+ else+ result.failed.append({o.order_id, r.error});+ }+ }+ return {true, result, {}};+ }++ /// Close all open positions by placing market counter-orders.+ virtual ApiResponse<CloseAllResult> close_all_positions(const BrokerCredentials& creds) {+ CloseAllResult result;+ auto pos_resp = get_positions(creds);+ if (!pos_resp.success)+ return {false, std::nullopt, pos_resp.error};+ for (const auto& p : pos_resp.data.value_or(QVector<BrokerPosition>{})) {+ if (p.quantity == 0) continue;+ result.total_positions++;+ UnifiedOrder counter;+ counter.symbol = p.symbol;+ counter.exchange = p.exchange;+ counter.side = (p.quantity > 0) ? OrderSide::Sell : OrderSide::Buy;+ counter.quantity = std::abs(p.quantity);+ counter.order_type = OrderType::Market;+ auto r = place_order(creds, counter);+ if (r.success)+ result.closed_symbols.append(p.symbol);+ else+ result.failed.append({p.symbol, r.error});+ }+ return {true, result, {}};+ }++ /// Close a single position by symbol/exchange/product.+ virtual ApiResponse<OrderPlaceResponse> close_position(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange, const QString& product_type)+ {+ auto pos_resp = get_positions(creds);+ if (!pos_resp.success)+ return {false, std::nullopt, pos_resp.error};+ for (const auto& p : pos_resp.data.value_or(QVector<BrokerPosition>{})) {+ if (p.symbol == symbol && p.exchange == exchange+ && (product_type.isEmpty() || p.product_type == product_type)+ && p.quantity != 0) {+ UnifiedOrder counter;+ counter.symbol = p.symbol;+ counter.exchange = p.exchange;+ counter.side = (p.quantity > 0) ? OrderSide::Sell : OrderSide::Buy;+ counter.quantity = std::abs(p.quantity);+ counter.order_type = OrderType::Market;+ auto opr = place_order(creds, counter);+ if (!opr.success)+ return {false, std::nullopt, opr.error};+ return {true, opr, ""};+ }+ }+ return {false, std::nullopt, "Position not found"};+ }++ /// Batch quotes for multiple symbols. Default: sequential fallback.+ virtual ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols)+ {+ QVector<BrokerQuote> results;+ for (const auto& [sym, exch] : symbols) {+ auto r = get_quotes(creds, {sym});+ if (r.success && r.data.has_value() && !r.data->isEmpty())+ results.append(r.data->first());+ }+ return {true, results, {}};+ }++ /// Market depth (Level 2 bid/ask). Default: not supported.+ virtual ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange)+ {+ Q_UNUSED(creds); Q_UNUSED(symbol); Q_UNUSED(exchange);+ return {false, std::nullopt, "Market depth not supported for this broker"};+ }++ /// Option chain for an underlying. Default: not supported.+ virtual ApiResponse<QVector<OptionChainEntry>> get_option_chain(+ const BrokerCredentials& creds,+ const QString& underlying, const QString& exchange,+ const QString& expiry, int strike_count = 0)+ {+ Q_UNUSED(creds); Q_UNUSED(underlying); Q_UNUSED(exchange);+ Q_UNUSED(expiry); Q_UNUSED(strike_count);+ return {false, std::nullopt, "Option chain not supported for this broker"};+ }+// --- WebSocket streaming ---virtual const char* ws_adapter_name() const { return ""; }diff --git a/fincept-qt/src/trading/BrokerRegistry.cpp b/fincept-qt/src/trading/BrokerRegistry.cppindex dcd0c7d6a..8f7592439 100644--- a/fincept-qt/src/trading/BrokerRegistry.cpp+++ b/fincept-qt/src/trading/BrokerRegistry.cpp@@ -17,8 +17,12 @@#include "trading/brokers/iifl/IIFLBroker.h"#include "trading/brokers/kotak/KotakBroker.h"#include "trading/brokers/motilal/MotilalBroker.h"+#include "trading/brokers/paytm/PaytmBroker.h"+#include "trading/brokers/samco/SamcoBroker.h"#include "trading/brokers/saxo/SaxoBankBroker.h"#include "trading/brokers/shoonya/ShoonyaBroker.h"+#include "trading/brokers/flattrade/FlattradeBroker.h"+#include "trading/brokers/tradejini/TradejiniBroker.h"#include "trading/brokers/tradier/TradierBroker.h"#include "trading/brokers/upstox/UpstoxBroker.h"#include "trading/brokers/zerodha/ZerodhaBroker.h"@@ -122,6 +126,10 @@ void BrokerRegistry::register_all() {brokers_["iifl"] = std::make_unique<IIFLBroker>();brokers_["motilal"] = std::make_unique<MotilalBroker>();brokers_["shoonya"] = std::make_unique<ShoonyaBroker>();+ brokers_["samco"] = std::make_unique<SamcoBroker>();+ brokers_["flattrade"] = std::make_unique<FlattradeBroker>();+ brokers_["paytm"] = std::make_unique<PaytmBroker>();+ brokers_["tradejini"] = std::make_unique<TradejiniBroker>();// US brokersbrokers_["alpaca"] = std::make_unique<AlpacaBroker>();diff --git a/fincept-qt/src/trading/DataStreamManager.cpp b/fincept-qt/src/trading/DataStreamManager.cppindex fbd73176e..419e2df85 100644--- a/fincept-qt/src/trading/DataStreamManager.cpp+++ b/fincept-qt/src/trading/DataStreamManager.cpp@@ -7,20 +7,75 @@# include "datahub/DataHubMetaTypes.h"# include "trading/BrokerTopic.h"+#include <QDateTime>+#include <QSet>#include <QVariant>namespace fincept::trading {namespace {constexpr const char* DSM_TAG = "DataStreamManager";++// Brokers whose tokens expire daily at ~3:00 AM IST. Crypto and international+// brokers (alpaca, ibkr, tradier, saxo) are intentionally excluded.+const QSet<QString>& indian_brokers() {+ static const QSet<QString> kSet = {+ "zerodha", "angelone", "upstox", "fyers", "dhan", "groww",+ "kotak", "iifl", "fivepaisa", "aliceblue", "shoonya", "motilal"};+ return kSet;}+// Hourly cadence is enough to catch the 3:00 AM IST window without polling+// the clock aggressively.+constexpr int DSM_EXPIRY_CHECK_MS = 60 * 60 * 1000;+} // namespace+DataStreamManager& DataStreamManager::instance() {static DataStreamManager s;return s;}-DataStreamManager::DataStreamManager() = default;+DataStreamManager::DataStreamManager() {+ // Daily IST token-expiry sweep (Phase 3 §19). This is an infrastructure+ // cadence timer on a long-lived service singleton (like the DataHub+ // scheduler), not a visibility-driven widget timer, so it runs continuously.+ expiry_check_timer_ = new QTimer(this);+ expiry_check_timer_->setInterval(DSM_EXPIRY_CHECK_MS);+ connect(expiry_check_timer_, &QTimer::timeout, this,+ &DataStreamManager::check_indian_token_expiry);+ expiry_check_timer_->start();+}++void DataStreamManager::check_indian_token_expiry() {+ // Convert now → IST (UTC+5:30) without needing tz data.+ const QDateTime ist =+ QDateTime::currentDateTimeUtc().addSecs(5 * 3600 + 30 * 60);+ const int hour = ist.time().hour();+ const int doy = ist.date().dayOfYear();++ // Only act inside the 3:00–3:59 AM IST window, and at most once per IST day.+ if (hour != 3 || doy == last_expiry_check_day_)+ return;+ last_expiry_check_day_ = doy;++ auto& am = AccountManager::instance();+ const auto accounts = am.list_accounts();+ int marked = 0;+ for (const auto& acct : accounts) {+ if (!acct.is_active || acct.trading_mode != "live")+ continue;+ if (!indian_brokers().contains(acct.broker_id))+ continue;+ if (am.connection_state(acct.account_id) == ConnectionState::TokenExpired)+ continue;+ am.set_connection_state(acct.account_id, ConnectionState::TokenExpired,+ QStringLiteral("Daily 3:00 AM IST session expiry"));+ ++marked;+ }+ if (marked > 0)+ LOG_INFO(DSM_TAG, QString("3:00 AM IST sweep: marked %1 Indian account(s) "+ "TokenExpired").arg(marked));+}// ── Stream lifecycle ────────────────────────────────────────────────────────diff --git a/fincept-qt/src/trading/DataStreamManager.h b/fincept-qt/src/trading/DataStreamManager.hindex 70c45186d..b65d65b1c 100644--- a/fincept-qt/src/trading/DataStreamManager.h+++ b/fincept-qt/src/trading/DataStreamManager.h@@ -9,6 +9,7 @@#include <QHash>#include <QObject>#include <QString>+#include <QTimer># include "datahub/Producer.h"@@ -65,6 +66,16 @@ class DataStreamManager : public QObjectDataStreamManager();void wire_stream_signals(AccountDataStream* stream);+ // Session expiry (Phase 3 §19). Indian broker tokens expire at ~3:00 AM IST+ // daily regardless of activity. This timer fires hourly and, when the IST+ // clock is in the 3:00–3:59 AM window, proactively marks active live+ // Indian-broker accounts as ConnectionState::TokenExpired so the UI can+ // prompt re-auth even if no API call has failed yet. Crypto / international+ // brokers are exempt (24/7 or different expiry rules).+ void check_indian_token_expiry();+ QTimer* expiry_check_timer_ = nullptr;+ int last_expiry_check_day_ = -1; // QDate::dayOfYear of last proactive sweep+// Slot-style handlers that fan the per-account signals to hub topics.// Connected from wire_stream_signals() so every stream publishes.void on_positions_for_hub(const QString& account_id, const QVector<BrokerPosition>& positions);diff --git a/fincept-qt/src/trading/LatencyTracker.cpp b/fincept-qt/src/trading/LatencyTracker.cppnew file mode 100644index 000000000..3110334c6--- /dev/null+++ b/fincept-qt/src/trading/LatencyTracker.cpp@@ -0,0 +1,163 @@+// LatencyTracker — per-order latency monitoring (in-memory v1).+//+// TODO(persistence): mirror OpenAlgo's latency_db and persist completed+// OrderLatency records to SQLite (keep ORDER-type logs forever, auto-purge+// DATA-type logs after N days). For this pass we keep a bounded in-memory ring+// which is sufficient for live stats/reporting without DB I/O on the hot path.++#include "trading/LatencyTracker.h"++#include "core/logging/Logger.h"++#include <QMutexLocker>++#include <algorithm>+#include <cmath>++namespace fincept::trading {++LatencyTracker& LatencyTracker::instance() {+ static LatencyTracker s;+ return s;+}++void LatencyTracker::begin(const QString& tracking_id) {+ QMutexLocker lock(&mutex_);+ InFlight f;+ f.total.start();+ f.stage.start();+ in_flight_.insert(tracking_id, f);+}++void LatencyTracker::mark_validation_done(const QString& tracking_id) {+ QMutexLocker lock(&mutex_);+ auto it = in_flight_.find(tracking_id);+ if (it == in_flight_.end())+ return;+ // restart() returns elapsed-since-last-restart in ms and resets the timer.+ it->validation_ms = static_cast<double>(it->stage.restart());+}++void LatencyTracker::mark_broker_request_sent(const QString& tracking_id) {+ QMutexLocker lock(&mutex_);+ auto it = in_flight_.find(tracking_id);+ if (it == in_flight_.end())+ return;+ // Marks the start of the broker call — discard any time between validation+ // and the request actually firing.+ it->stage.restart();+}++void LatencyTracker::mark_broker_response_received(const QString& tracking_id) {+ QMutexLocker lock(&mutex_);+ auto it = in_flight_.find(tracking_id);+ if (it == in_flight_.end())+ return;+ it->broker_rtt_ms = static_cast<double>(it->stage.restart());+}++void LatencyTracker::mark_complete(const QString& tracking_id, const QString& order_id,+ const QString& account_id, const QString& broker,+ const QString& symbol, const QString& order_type,+ const QString& status, const QString& error) {+ QMutexLocker lock(&mutex_);+ auto it = in_flight_.find(tracking_id);+ if (it == in_flight_.end()) {+ LOG_WARN("LatencyTracker",+ QString("mark_complete for unknown tracking_id: %1").arg(tracking_id));+ return;+ }++ OrderLatency entry;+ entry.order_id = order_id;+ entry.account_id = account_id;+ entry.broker = broker;+ entry.symbol = symbol;+ entry.order_type = order_type;+ entry.validation_ms = it->validation_ms;+ entry.broker_rtt_ms = it->broker_rtt_ms;+ entry.response_ms = static_cast<double>(it->stage.elapsed()); // since broker response received+ entry.total_ms = static_cast<double>(it->total.elapsed());+ entry.status = status;+ entry.error = error;+ entry.timestamp = QDateTime::currentDateTime();++ in_flight_.erase(it);++ history_.append(entry);+ while (history_.size() > kMaxHistory)+ history_.removeFirst();+}++QVector<LatencyTracker::OrderLatency> LatencyTracker::get_history(const QString& account_id,+ int limit) const {+ QMutexLocker lock(&mutex_);+ QVector<OrderLatency> out;+ if (limit <= 0)+ return out;++ // Walk newest-first, collect up to `limit` matches, then restore chronological order.+ for (int i = history_.size() - 1; i >= 0 && out.size() < limit; --i) {+ const OrderLatency& e = history_.at(i);+ if (!account_id.isEmpty() && e.account_id != account_id)+ continue;+ out.append(e);+ }+ std::reverse(out.begin(), out.end());+ return out;+}++LatencyTracker::LatencyStats LatencyTracker::get_stats(const QString& broker,+ int last_n_hours) const {+ QMutexLocker lock(&mutex_);+ LatencyStats stats;++ const QDateTime cutoff =+ (last_n_hours > 0) ? QDateTime::currentDateTime().addSecs(-qint64(last_n_hours) * 3600)+ : QDateTime();++ QVector<double> rtts;+ double sum_rtt = 0;+ double sum_total = 0;++ for (const OrderLatency& e : history_) {+ if (!broker.isEmpty() && e.broker != broker)+ continue;+ if (cutoff.isValid() && e.timestamp < cutoff)+ continue;++ ++stats.total_orders;+ if (e.status == QStringLiteral("FAILED"))+ ++stats.failed_orders;++ rtts.append(e.broker_rtt_ms);+ sum_rtt += e.broker_rtt_ms;+ sum_total += e.total_ms;+ }++ if (stats.total_orders == 0)+ return stats;++ stats.avg_rtt_ms = sum_rtt / stats.total_orders;+ stats.avg_total_ms = sum_total / stats.total_orders;++ std::sort(rtts.begin(), rtts.end());+ auto percentile = [&rtts](double p) -> double {+ if (rtts.isEmpty())+ return 0;+ // Nearest-rank percentile on the sorted copy.+ int idx = static_cast<int>(std::ceil(p / 100.0 * rtts.size())) - 1;+ if (idx < 0)+ idx = 0;+ if (idx >= rtts.size())+ idx = rtts.size() - 1;+ return rtts.at(idx);+ };+ stats.p50_rtt_ms = percentile(50);+ stats.p95_rtt_ms = percentile(95);+ stats.p99_rtt_ms = percentile(99);++ return stats;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/LatencyTracker.h b/fincept-qt/src/trading/LatencyTracker.hnew file mode 100644index 000000000..bd3f3f715--- /dev/null+++ b/fincept-qt/src/trading/LatencyTracker.h@@ -0,0 +1,82 @@+#pragma once+// LatencyTracker — per-order latency monitoring for the trading layer.+//+// Tracks the timing of an order through its execution stages (validation ->+// broker round-trip -> response processing) and keeps an in-memory ring of+// completed orders for stats/reporting. Modelled on OpenAlgo's+// utils/latency_monitor.py (stage-based timing + RTT comparable to Postman).+//+// Usage (caller picks a unique tracking_id, e.g. a UUID or temp order ref):+// auto& lt = LatencyTracker::instance();+// lt.begin(tid);+// ... run validation ...+// lt.mark_validation_done(tid);+// lt.mark_broker_request_sent(tid);+// ... fire broker HTTP call ...+// lt.mark_broker_response_received(tid);+// ... process response ...+// lt.mark_complete(tid, order_id, account_id, broker, symbol, "PLACE",+// success ? "SUCCESS" : "FAILED", error);+//+// All methods are thread-safe.++#include <QDateTime>+#include <QElapsedTimer>+#include <QHash>+#include <QMutex>+#include <QString>+#include <QVector>++namespace fincept::trading {++class LatencyTracker {+ public:+ struct OrderLatency {+ QString order_id;+ QString account_id;+ QString broker;+ QString symbol;+ QString order_type; // "PLACE","SMART","CANCEL","CLOSE_ALL","BASKET","SPLIT"+ double validation_ms = 0;+ double broker_rtt_ms = 0;+ double response_ms = 0;+ double total_ms = 0;+ QString status; // "SUCCESS","FAILED"+ QString error;+ QDateTime timestamp;+ };++ static LatencyTracker& instance();++ // Lightweight in-flight tracking keyed by a caller-chosen tracking_id.+ void begin(const QString& tracking_id);+ void mark_validation_done(const QString& tracking_id);+ void mark_broker_request_sent(const QString& tracking_id);+ void mark_broker_response_received(const QString& tracking_id);+ void mark_complete(const QString& tracking_id, const QString& order_id,+ const QString& account_id, const QString& broker, const QString& symbol,+ const QString& order_type, const QString& status, const QString& error = {});++ QVector<OrderLatency> get_history(const QString& account_id = {}, int limit = 100) const;++ struct LatencyStats {+ double avg_rtt_ms = 0, p50_rtt_ms = 0, p95_rtt_ms = 0, p99_rtt_ms = 0, avg_total_ms = 0;+ int total_orders = 0, failed_orders = 0;+ };+ LatencyStats get_stats(const QString& broker = {}, int last_n_hours = 24) const;++ private:+ LatencyTracker() = default;+ struct InFlight {+ QElapsedTimer total;+ QElapsedTimer stage;+ double validation_ms = 0;+ double broker_rtt_ms = 0;+ };+ QHash<QString, InFlight> in_flight_;+ QVector<OrderLatency> history_; // in-memory ring; cap at kMaxHistory entries+ mutable QMutex mutex_;+ static constexpr int kMaxHistory = 5000;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/OptionsStrategyBuilder.cpp b/fincept-qt/src/trading/OptionsStrategyBuilder.cppnew file mode 100644index 000000000..798f1badb--- /dev/null+++ b/fincept-qt/src/trading/OptionsStrategyBuilder.cpp@@ -0,0 +1,204 @@+#include "OptionsStrategyBuilder.h"++#include <QDate>++#include <algorithm>+#include <cmath>++namespace fincept::trading {++namespace {++// Default exchange for option legs. Index/equity F&O on NSE trade on NFO.+// BSE F&O (SENSEX/BANKEX) would use "BFO" — symbol resolution will refine this+// once InstrumentService is wired in.+constexpr const char* kDefaultFnoExchange = "NFO";++// Compact an expiry into the form used in tradingsymbols: "2025-03-28" -> "28MAR25".+// Falls back to the digits/letters of the input string when it is not an ISO date.+QString compact_expiry(const QString& expiry)+{+ QDate d = QDate::fromString(expiry, "yyyy-MM-dd");+ if (d.isValid()) {+ // Fixed English month abbreviations — QDate::toString("MMM") uses the+ // system locale, which would produce non-English names; tradingsymbols+ // require the uppercase English abbreviation regardless of locale.+ static const char* const kMonths[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN",+ "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};+ const QString month = QString::fromLatin1(kMonths[d.month() - 1]);+ return QString("%1%2%3")+ .arg(d.day(), 2, 10, QChar('0'))+ .arg(month)+ .arg(d.year() % 100, 2, 10, QChar('0'));+ }+ // Not an ISO date — strip separators so the symbol stays readable.+ QString compact = expiry;+ compact.remove('-');+ compact.remove('/');+ compact.remove(' ');+ return compact.toUpper();+}++// Format a strike without a trailing ".0" for whole-number strikes.+QString strike_str(double strike)+{+ if (std::floor(strike) == strike)+ return QString::number(static_cast<long long>(strike));+ return QString::number(strike, 'g', 10);+}++// Build a single leg with its placeholder symbol filled in.+OptionsLeg make_leg(const QString& underlying, const QString& expiry, double strike,+ const QString& opt_type, OrderSide side, double quantity)+{+ OptionsLeg leg;+ leg.symbol = OptionsStrategyBuilder::build_option_symbol(underlying, expiry, strike, opt_type);+ leg.exchange = QString::fromLatin1(kDefaultFnoExchange);+ leg.side = side;+ leg.quantity = quantity;+ leg.strike = strike;+ leg.option_type = opt_type;+ leg.expiry = expiry;+ return leg;+}++} // namespace++QString OptionsStrategyBuilder::build_option_symbol(const QString& underlying,+ const QString& expiry, double strike,+ const QString& opt_type)+{+ // TODO: Replace with InstrumentService lookup. Real broker tradingsymbols+ // (e.g. Zerodha "NIFTY25MAR24500CE", Dhan numeric security IDs) must be+ // resolved from the instrument master — this placeholder is a human-readable+ // approximation only and is not guaranteed to be tradable as-is.+ return underlying.toUpper() + compact_expiry(expiry) + strike_str(strike) + opt_type.toUpper();+}++OptionsStrategy OptionsStrategyBuilder::straddle(const QString& underlying, const QString& expiry,+ double atm_strike, double lot_size,+ OrderSide direction)+{+ OptionsStrategy s;+ s.name = (direction == OrderSide::Buy) ? "Long Straddle" : "Short Straddle";+ s.legs.append(make_leg(underlying, expiry, atm_strike, "CE", direction, lot_size));+ s.legs.append(make_leg(underlying, expiry, atm_strike, "PE", direction, lot_size));+ // Payoff requires the net premium (CE + PE) which needs live quotes:+ // long straddle: max_loss = premium paid; breakevens = strike ± premium.+ // short straddle: max_profit = premium received; breakevens = strike ± premium.+ // Left at 0 until premium data is supplied.+ return s;+}++OptionsStrategy OptionsStrategyBuilder::strangle(const QString& underlying, const QString& expiry,+ double atm_strike, double width, double lot_size,+ OrderSide direction)+{+ OptionsStrategy s;+ s.name = (direction == OrderSide::Buy) ? "Long Strangle" : "Short Strangle";+ const double call_strike = atm_strike + width; // OTM call+ const double put_strike = atm_strike - width; // OTM put+ s.legs.append(make_leg(underlying, expiry, call_strike, "CE", direction, lot_size));+ s.legs.append(make_leg(underlying, expiry, put_strike, "PE", direction, lot_size));+ // Payoff requires the net premium (needs live quotes):+ // long: max_loss = premium paid; breakevens = call_strike + prem / put_strike - prem.+ // short: max_profit = premium received; same breakeven structure.+ // Left at 0 until premium data is supplied.+ return s;+}++OptionsStrategy OptionsStrategyBuilder::iron_condor(const QString& underlying,+ const QString& expiry, double atm_strike,+ double near_width, double far_width,+ double lot_size)+{+ OptionsStrategy s;+ s.name = "Iron Condor";+ const double sell_ce = atm_strike + near_width; // short near call+ const double buy_ce = atm_strike + far_width; // long far call (protection)+ const double sell_pe = atm_strike - near_width; // short near put+ const double buy_pe = atm_strike - far_width; // long far put (protection)++ // Order: sell near CE, buy far CE, sell near PE, buy far PE (per spec §13).+ s.legs.append(make_leg(underlying, expiry, sell_ce, "CE", OrderSide::Sell, lot_size));+ s.legs.append(make_leg(underlying, expiry, buy_ce, "CE", OrderSide::Buy, lot_size));+ s.legs.append(make_leg(underlying, expiry, sell_pe, "PE", OrderSide::Sell, lot_size));+ s.legs.append(make_leg(underlying, expiry, buy_pe, "PE", OrderSide::Buy, lot_size));++ // Max loss is bounded by the wing width minus the net credit:+ // max_loss = (far_width - near_width) * lot_size - net_credit.+ // max_profit = net_credit. Both depend on the net premium collected, which+ // needs live quotes — left at 0. Breakevens are short_strike ± net_credit+ // (per contract), also premium-dependent.+ return s;+}++OptionsStrategy OptionsStrategyBuilder::bull_call_spread(const QString& underlying,+ const QString& expiry, double lower_strike,+ double upper_strike, double lot_size)+{+ OptionsStrategy s;+ s.name = "Bull Call Spread";+ s.legs.append(make_leg(underlying, expiry, lower_strike, "CE", OrderSide::Buy, lot_size));+ s.legs.append(make_leg(underlying, expiry, upper_strike, "CE", OrderSide::Sell, lot_size));++ // The maximum payoff (gross of premium) is the strike spread × lot size.+ // The net debit (premium paid) is unknown without quotes, so:+ // true max_profit = (spread × lot) - net_debit,+ // true max_loss = net_debit,+ // breakeven_lower = lower_strike + net_debit (per contract).+ // We expose the strike-geometry portion as the gross spread payoff and leave+ // the premium-dependent net figures at 0.+ const double spread = (upper_strike - lower_strike) * lot_size;+ s.max_profit = spread; // gross of premium — see note above+ return s;+}++OptionsStrategy OptionsStrategyBuilder::bear_put_spread(const QString& underlying,+ const QString& expiry, double upper_strike,+ double lower_strike, double lot_size)+{+ OptionsStrategy s;+ s.name = "Bear Put Spread";+ s.legs.append(make_leg(underlying, expiry, upper_strike, "PE", OrderSide::Buy, lot_size));+ s.legs.append(make_leg(underlying, expiry, lower_strike, "PE", OrderSide::Sell, lot_size));++ // Gross payoff (before premium) is the strike spread × lot size. The net+ // debit is premium-dependent (needs quotes), so:+ // true max_profit = (spread × lot) - net_debit,+ // true max_loss = net_debit,+ // breakeven_upper = upper_strike - net_debit (per contract).+ // Expose the gross spread payoff; leave net/premium figures at 0.+ const double spread = (upper_strike - lower_strike) * lot_size;+ s.max_profit = spread; // gross of premium — see note above+ return s;+}++BasketOrderRequest OptionsStrategyBuilder::to_basket_order(const OptionsStrategy& strategy,+ ProductType product)+{+ BasketOrderRequest request;+ request.strategy_name = strategy.name;++ // SELL legs first (collect premium → reduce margin), BUY legs second.+ // stable_partition preserves the relative order within each group.+ QVector<OptionsLeg> sorted = strategy.legs;+ std::stable_partition(sorted.begin(), sorted.end(),+ [](const OptionsLeg& leg) { return leg.side == OrderSide::Sell; });++ request.orders.reserve(sorted.size());+ for (const OptionsLeg& leg : sorted) {+ UnifiedOrder order;+ order.symbol = leg.symbol;+ order.exchange = leg.exchange;+ order.side = leg.side;+ order.quantity = leg.quantity;+ order.order_type = OrderType::Market;+ order.product_type = product;+ request.orders.append(order);+ }++ return request;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/OptionsStrategyBuilder.h b/fincept-qt/src/trading/OptionsStrategyBuilder.hnew file mode 100644index 000000000..2980de476--- /dev/null+++ b/fincept-qt/src/trading/OptionsStrategyBuilder.h@@ -0,0 +1,95 @@+#pragma once+// Options Strategy Builder — generates option legs for common multi-leg+// strategies (straddle, strangle, iron condor, vertical spreads) and converts+// them into a BasketOrderRequest for execution.+//+// Spec: docs/OPENALGO_BRIDGE_PHASE2.md §13 and §15.+// OpenAlgo reference: services/flow_executor_service.py (_generate_strategy_legs).++#include "TradingTypes.h"++#include <QString>+#include <QVector>++namespace fincept::trading {++// ----------------------------------------------------------------------------+// A single option leg within a strategy.+// ----------------------------------------------------------------------------+struct OptionsLeg {+ QString symbol; // e.g. "NIFTY28MAR25500CE" (placeholder — see build_option_symbol)+ QString exchange; // "NFO" (NSE F&O) / "BFO" (BSE F&O)+ OrderSide side = OrderSide::Buy;+ double quantity = 0; // already multiplied by lot size+ double strike = 0;+ QString option_type; // "CE" (call) or "PE" (put)+ QString expiry; // "2025-03-28"+};++// ----------------------------------------------------------------------------+// A complete options strategy: a named bundle of legs plus payoff metrics.+// ----------------------------------------------------------------------------+struct OptionsStrategy {+ QString name;+ QVector<OptionsLeg> legs;+ // Payoff metrics. Computed where they follow directly from strike geometry+ // and lot size (e.g. vertical spreads). Left at 0 where option premium data+ // is required — see notes in OptionsStrategyBuilder.cpp.+ double max_profit = 0;+ double max_loss = 0;+ double breakeven_upper = 0;+ double breakeven_lower = 0;+};++// ----------------------------------------------------------------------------+// Static factory for common option strategies + basket-order conversion.+// ----------------------------------------------------------------------------+class OptionsStrategyBuilder {+public:+ // Long straddle (direction = Buy) or short straddle (direction = Sell):+ // ATM CE + ATM PE, both on the same side.+ static OptionsStrategy straddle(const QString& underlying, const QString& expiry,+ double atm_strike, double lot_size,+ OrderSide direction);++ // Long strangle (direction = Buy) or short strangle (direction = Sell):+ // OTM CE at (atm + width) + OTM PE at (atm - width), both on the same side.+ static OptionsStrategy strangle(const QString& underlying, const QString& expiry,+ double atm_strike, double width, double lot_size,+ OrderSide direction);++ // Iron condor (always a net credit, short-vol strategy):+ // Sell near CE (atm + near_width), buy far CE (atm + far_width),+ // Sell near PE (atm - near_width), buy far PE (atm - far_width).+ static OptionsStrategy iron_condor(const QString& underlying, const QString& expiry,+ double atm_strike, double near_width, double far_width,+ double lot_size);++ // Bull call spread (debit): buy lower-strike CE, sell upper-strike CE.+ static OptionsStrategy bull_call_spread(const QString& underlying, const QString& expiry,+ double lower_strike, double upper_strike,+ double lot_size);++ // Bear put spread (debit): buy upper-strike PE, sell lower-strike PE.+ static OptionsStrategy bear_put_spread(const QString& underlying, const QString& expiry,+ double upper_strike, double lower_strike,+ double lot_size);++ // Convert a strategy's legs into a BasketOrderRequest. SELL legs are placed+ // first (collect premium / reduce margin) via std::stable_partition, matching+ // OpenAlgo's options_multiorder_service ordering. Each leg becomes a Market+ // UnifiedOrder with the supplied product type. The strategy name is copied to+ // BasketOrderRequest::strategy_name.+ static BasketOrderRequest to_basket_order(const OptionsStrategy& strategy,+ ProductType product);++ // Build a readable placeholder option symbol of the form+ // "<UNDERLYING><EXPIRY-COMPACT><STRIKE><CE|PE>", e.g. "NIFTY28MAR25500CE".+ // TODO: Replace with InstrumentService lookup once available — exchange+ // tradingsymbols vary per broker and must be resolved from the instrument+ // master rather than constructed by string concatenation.+ static QString build_option_symbol(const QString& underlying, const QString& expiry,+ double strike, const QString& opt_type);+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/OrderValidator.cpp b/fincept-qt/src/trading/OrderValidator.cppnew file mode 100644index 000000000..2a0d2708a--- /dev/null+++ b/fincept-qt/src/trading/OrderValidator.cpp@@ -0,0 +1,102 @@+#include "trading/OrderValidator.h"++namespace fincept::trading {++const QSet<QString>& OrderValidator::valid_exchanges() {+ static const QSet<QString> kExchanges = {+ // India+ "NSE", "BSE", "NFO", "BFO", "MCX", "CDS", "BCD", "NCDEX",+ "NSE_INDEX", "BSE_INDEX", "MCX_INDEX",+ // US / global+ "NYSE", "NASDAQ", "AMEX", "ARCA", "BATS", "CBOE", "LSE", "TSX",+ "XETRA", "EURONEXT", "XNYS", "XNAS",+ // crypto / forex+ "CRYPTO", "FOREX"};+ return kExchanges;+}++bool OrderValidator::is_valid_exchange(const QString& exchange) {+ return valid_exchanges().contains(exchange.toUpper());+}++bool OrderValidator::requires_price(OrderType type) {+ return type == OrderType::Limit || type == OrderType::StopLossLimit;+}++bool OrderValidator::requires_trigger_price(OrderType type) {+ return type == OrderType::StopLoss || type == OrderType::StopLossLimit;+}++OrderValidator::ValidationResult OrderValidator::validate(const UnifiedOrder& order) {+ ValidationResult r;++ if (order.symbol.trimmed().isEmpty())+ r.errors.append("Symbol is required");+ if (order.exchange.trimmed().isEmpty())+ r.errors.append("Exchange is required");+ else if (!is_valid_exchange(order.exchange))+ r.errors.append("Invalid exchange: " + order.exchange);++ if (order.quantity <= 0)+ r.errors.append("Quantity must be positive");++ if (requires_price(order.order_type) && order.price <= 0)+ r.errors.append("Price is required for LIMIT / SL-Limit orders");++ if (requires_trigger_price(order.order_type) && order.stop_price <= 0)+ r.errors.append("Trigger price is required for SL / SL-M orders");++ r.valid = r.errors.isEmpty();+ return r;+}++OrderValidator::ValidationResult OrderValidator::validate_smart(const SmartOrder& order) {+ ValidationResult r;++ if (order.symbol.trimmed().isEmpty())+ r.errors.append("Symbol is required");+ if (order.exchange.trimmed().isEmpty())+ r.errors.append("Exchange is required");+ else if (!is_valid_exchange(order.exchange))+ r.errors.append("Invalid exchange: " + order.exchange);++ // Smart order: position_size is the target. When target is 0 (flatten) the+ // engine derives action from current position, so quantity is optional. When+ // there is no target and no fallback quantity, nothing can be placed.+ if (order.position_size == 0 && order.quantity <= 0)+ r.errors.append("Either position_size or a positive quantity is required");++ if (requires_price(order.order_type) && order.price <= 0)+ r.errors.append("Price is required for LIMIT / SL-Limit orders");++ if (requires_trigger_price(order.order_type) && order.trigger_price <= 0)+ r.errors.append("Trigger price is required for SL / SL-M orders");++ r.valid = r.errors.isEmpty();+ return r;+}++OrderValidator::ValidationResult OrderValidator::validate_basket(const BasketOrderRequest& basket) {+ ValidationResult r;++ if (basket.orders.isEmpty()) {+ r.errors.append("Basket has no orders");+ r.valid = false;+ return r;+ }++ for (int i = 0; i < basket.orders.size(); ++i) {+ auto leg = validate(basket.orders[i]);+ if (!leg.valid) {+ for (const auto& e : leg.errors)+ r.errors.append(QString("Order %1 (%2): %3")+ .arg(i + 1)+ .arg(basket.orders[i].symbol, e));+ }+ }++ r.valid = r.errors.isEmpty();+ return r;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/OrderValidator.h b/fincept-qt/src/trading/OrderValidator.hnew file mode 100644index 000000000..c36842bb3--- /dev/null+++ b/fincept-qt/src/trading/OrderValidator.h@@ -0,0 +1,32 @@+#pragma once+// OrderValidator — pre-flight validation for orders before they reach a broker.+// Mirrors OpenAlgo's restx_api/schemas.py checks: required fields, valid exchange,+// positive quantity, price required for LIMIT, trigger required for SL/SL-M.++#include "trading/TradingTypes.h"++#include <QStringList>+#include <QSet>++namespace fincept::trading {++class OrderValidator {+ public:+ struct ValidationResult {+ bool valid = true;+ QStringList errors;+ };++ static ValidationResult validate(const UnifiedOrder& order);+ static ValidationResult validate_smart(const SmartOrder& order);+ static ValidationResult validate_basket(const BasketOrderRequest& basket);++ static bool is_valid_exchange(const QString& exchange);++ private:+ static bool requires_price(OrderType type);+ static bool requires_trigger_price(OrderType type);+ static const QSet<QString>& valid_exchanges();+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/PaperTrading.cpp b/fincept-qt/src/trading/PaperTrading.cppindex c989f7cf1..420ab5691 100644--- a/fincept-qt/src/trading/PaperTrading.cpp+++ b/fincept-qt/src/trading/PaperTrading.cpp@@ -10,8 +10,10 @@#include "storage/sqlite/Database.h"#include <QDateTime>+#include <QHash>#include <QMutex>#include <QMutexLocker>+#include <QTime>#include <QUuid>#include <cmath>@@ -35,6 +37,141 @@ static auto& repo() {// from corrupting balance or positions.static QMutex s_fill_mutex;+// ============================================================================+// Leverage / Market-hours Config (Phase 3 §4)+// ============================================================================+//+// Per-portfolio leverage rules and the market-hours enforcement flag are held+// in memory rather than in the pt_portfolios table. The existing schema has no+// columns for them and the task forbids adding a migration / editing CMake, so+// an in-memory map (rebuilt at runtime by callers via the setters) is the+// source of truth. Defaults match OpenAlgo's sandbox.++namespace {++struct PtRuntimeConfig {+ PtLeverageConfig leverage;+ bool enforce_market_hours = false;+};++QMutex s_config_mutex;+QHash<QString, PtRuntimeConfig>& config_map() {+ static QHash<QString, PtRuntimeConfig> m;+ return m;+}++PtRuntimeConfig config_for(const QString& portfolio_id) {+ QMutexLocker lock(&s_config_mutex);+ return config_map().value(portfolio_id, PtRuntimeConfig{});+}++} // namespace++void pt_set_leverage_config(const QString& portfolio_id, const PtLeverageConfig& cfg) {+ QMutexLocker lock(&s_config_mutex);+ config_map()[portfolio_id].leverage = cfg;+}++PtLeverageConfig pt_get_leverage_config(const QString& portfolio_id) {+ return config_for(portfolio_id).leverage;+}++void pt_set_enforce_market_hours(const QString& portfolio_id, bool enforce) {+ QMutexLocker lock(&s_config_mutex);+ config_map()[portfolio_id].enforce_market_hours = enforce;+}++bool pt_get_enforce_market_hours(const QString& portfolio_id) {+ return config_for(portfolio_id).enforce_market_hours;+}++// ============================================================================+// Instrument-type helpers (Phase 3 §4)+// ============================================================================++bool pt_is_option(const QString& symbol) {+ // Canonical option symbols end with CE (call) or PE (put), e.g.+ // "NIFTY28FEB2520000CE". Match case-insensitively on the suffix.+ return symbol.endsWith("CE", Qt::CaseInsensitive) || symbol.endsWith("PE", Qt::CaseInsensitive);+}++bool pt_is_future(const QString& symbol) {+ // Canonical future symbols end with FUT, e.g. "NIFTY28FEB25FUT".+ return symbol.endsWith("FUT", Qt::CaseInsensitive);+}++// ============================================================================+// Margin calculation (Phase 3 §4)+// ============================================================================++namespace {++// Select leverage for a trade based on instrument type, product, exchange and+// side. Mirrors OpenAlgo fund_manager.py::_get_leverage.+double select_leverage(const PtLeverageConfig& cfg, const QString& symbol, const QString& exchange,+ const QString& product, const QString& side) {+ // Futures take priority (FUT suffix), then options (CE/PE suffix).+ if (pt_is_future(symbol))+ return cfg.futures;+ if (pt_is_option(symbol))+ return (side.compare("buy", Qt::CaseInsensitive) == 0) ? cfg.options_buy : cfg.options_sell;++ // Equity: leverage depends on product. MIS (intraday) gets equity_mis,+ // everything else (CNC/NRML/delivery/blank) gets equity_cnc.+ const QString ex = exchange.toUpper();+ if (ex == "NSE" || ex == "BSE" || ex.isEmpty()) {+ if (product.compare("MIS", Qt::CaseInsensitive) == 0 || product.compare("intraday", Qt::CaseInsensitive) == 0)+ return cfg.equity_mis;+ return cfg.equity_cnc;+ }++ // Unknown exchange: fall back to 1x (full margin) — safest default.+ return 1.0;+}++} // namespace++double pt_calculate_required_margin(const QString& portfolio_id, const QString& symbol, const QString& exchange,+ const QString& product, double quantity, double price, const QString& side) {+ if (!std::isfinite(quantity) || quantity <= 0.0 || !std::isfinite(price) || price <= 0.0)+ return 0.0;++ PtLeverageConfig cfg = pt_get_leverage_config(portfolio_id);+ double leverage = select_leverage(cfg, symbol, exchange, product, side);+ if (!std::isfinite(leverage) || leverage <= 0.0)+ leverage = 1.0;++ double trade_value = quantity * price;+ return trade_value / leverage;+}++// ============================================================================+// Exchange hours (Phase 3 §4)+// ============================================================================++bool pt_is_market_open(const QString& exchange) {+ // IST = UTC + 5:30.+ QDateTime ist = QDateTime::currentDateTimeUtc().addSecs(5 * 3600 + 30 * 60);+ QTime t = ist.time();+ const QString ex = exchange.toUpper();++ if (ex == "NSE" || ex == "BSE" || ex == "NFO" || ex == "BFO") {+ // Equity / equity derivatives: 09:15 – 15:30 IST.+ return t >= QTime(9, 15) && t <= QTime(15, 30);+ }+ if (ex == "MCX") {+ // Commodities: 09:00 – 23:30 IST.+ return t >= QTime(9, 0) && t <= QTime(23, 30);+ }+ if (ex == "CDS" || ex == "BCD") {+ // Currency derivatives: 09:00 – 17:00 IST.+ return t >= QTime(9, 0) && t <= QTime(17, 0);+ }++ // Unknown / crypto / international: always open (24/7).+ return true;+}+// ============================================================================// Portfolio Operations// ============================================================================@@ -98,6 +235,7 @@ PtPortfolio pt_reset_portfolio(const QString& id) {repo().delete_all_trades(id);repo().cancel_all_orders(id);repo().delete_all_positions(id);+ repo().delete_all_margin_blocks(id); // clear any blocked margin (Phase 3 §4)// Reset balance to initialauto p = pt_get_portfolio(id);repo().update_balance(id, p.initial_balance);@@ -108,9 +246,37 @@ PtPortfolio pt_reset_portfolio(const QString& id) {// Order Operations// ============================================================================+// Persist a rejected order record (best-effort) then throw, so the rejection is+// both visible in the order book and surfaced to callers via the existing+// exception-based contract.+[[noreturn]] static void reject_order(const QString& portfolio_id, const QString& symbol, const QString& side,+ const QString& order_type, double quantity, std::optional<double> price,+ std::optional<double> stop_price, bool reduce_only, const QString& product,+ const QString& exchange, const std::string& reason) {+ PtOrder rej;+ rej.id = generate_uuid();+ rej.portfolio_id = portfolio_id;+ rej.symbol = symbol;+ rej.side = side;+ rej.order_type = order_type;+ rej.quantity = quantity;+ rej.price = price;+ rej.stop_price = stop_price;+ rej.filled_qty = 0.0;+ rej.status = "rejected";+ rej.reduce_only = reduce_only;+ rej.margin_blocked = 0.0;+ rej.product = product;+ rej.exchange = exchange;+ rej.created_at = now_rfc3339();+ repo().insert_order(rej); // best-effort; ignore failure+ throw std::runtime_error(reason);+}+PtOrder pt_place_order(const QString& portfolio_id, const QString& symbol, const QString& side,const QString& order_type, double quantity, std::optional<double> price,- std::optional<double> stop_price, bool reduce_only) {+ std::optional<double> stop_price, bool reduce_only, const QString& exchange,+ const QString& product) {// Validationif (order_type != "market" && order_type != "limit" && order_type != "stop" && order_type != "stop_limit")throw std::runtime_error("Invalid order type: " + order_type.toStdString());@@ -127,10 +293,20 @@ PtOrder pt_place_order(const QString& portfolio_id, const QString& symbol, constif ((order_type == "stop" || order_type == "stop_limit") && !stop_price)throw std::runtime_error("Stop order requires stop_price");- // Margin check — skip for reduce_only orders and orders that close/reduce existing positionsauto portfolio = pt_get_portfolio(portfolio_id);++ // Exchange-hours enforcement — opt-in per portfolio (default off preserves+ // existing behavior). Only enforced when an exchange is supplied.+ if (pt_get_enforce_market_hours(portfolio_id) && !exchange.isEmpty() && !pt_is_market_open(exchange)) {+ reject_order(portfolio_id, symbol, side, order_type, quantity, price, stop_price, reduce_only, product,+ exchange, ("Market closed for exchange " + exchange).toStdString());+ }++ // Margin blocking — skip for reduce_only orders and for the portion of an+ // order that closes/reduces an existing opposite position. Only the net new+ // exposure consumes margin.+ double margin_to_block = 0.0;if (!reduce_only) {- // Determine if this order closes an existing opposite positionQString opposite_side = (side == "buy") ? "short" : "long";auto opposite_pos = repo().find_position(portfolio_id, symbol, opposite_side);double net_new_qty = quantity;@@ -139,14 +315,21 @@ PtOrder pt_place_order(const QString& portfolio_id, const QString& symbol, constnet_new_qty = std::max(0.0, quantity - opposite_pos->quantity);}- // Only check margin for the net new exposureif (net_new_qty > 0.0) {double ref = price.value_or(stop_price.value_or(0.0));if (ref <= 0.0)throw std::runtime_error("Market orders require a reference price for margin calculation");- double required = net_new_qty * ref / portfolio.leverage;- if (required > portfolio.balance)- throw std::runtime_error("Insufficient margin");++ // Per-product / per-instrument leverage. If exchange/product are not+ // supplied, select_leverage falls back to the equity rules /+ // portfolio default, and for blank exchange the equity CNC path.+ margin_to_block =+ pt_calculate_required_margin(portfolio_id, symbol, exchange, product, net_new_qty, ref, side);++ if (margin_to_block > portfolio.balance) {+ reject_order(portfolio_id, symbol, side, order_type, quantity, price, stop_price, reduce_only, product,+ exchange, "Insufficient margin");+ }}}@@ -162,15 +345,41 @@ PtOrder pt_place_order(const QString& portfolio_id, const QString& symbol, constorder.filled_qty = 0.0;order.status = "pending";order.reduce_only = reduce_only;+ order.margin_blocked = margin_to_block;+ order.product = product;+ order.exchange = exchange;order.created_at = now_rfc3339();auto r = repo().insert_order(order);if (r.is_err())throw std::runtime_error(r.error());++ // Block the margin from available balance and record it against the order so+ // the exact amount can be released on fill/cancel.+ if (margin_to_block > 0.0) {+ repo().update_balance(portfolio_id, portfolio.balance - margin_to_block);+ repo().insert_margin_block(generate_uuid(), portfolio_id, order.id, symbol, margin_to_block);+ }+return order;}void pt_cancel_order(const QString& order_id) {+ // Release any margin blocked when the order was placed back to available+ // balance (no realized P&L — the order never filled). Serialized under the+ // fill mutex so a concurrent fill can't double-release the same block.+ QMutexLocker lock(&s_fill_mutex);++ double blocked = repo().get_margin_block(order_id);+ if (blocked > 0.0) {+ auto ord = repo().get_order(order_id);+ if (ord.is_ok()) {+ auto portfolio = pt_get_portfolio(ord.value().portfolio_id);+ repo().update_balance(portfolio.id, portfolio.balance + blocked);+ }+ repo().delete_margin_block(order_id);+ }+repo().cancel_order(order_id);}@@ -283,17 +492,38 @@ PtTrade pt_fill_order(const QString& order_id, double fill_price, std::optional<}}- // 7. Update balance+ // 7a. Release blocked margin (Phase 3 §4).+ // Margin was blocked from balance at placement for the net-new exposure.+ // Release it proportionally to the filled quantity on each (possibly+ // partial) fill. On the final fill, release whatever remains so rounding+ // never leaves margin stuck.+ double new_filled = order.filled_qty + qty;+ bool fully_filled = (new_filled >= order.quantity);+ double order_blocked = repo().get_margin_block(order_id);+ double margin_release = 0.0;+ if (order_blocked > 0.0) {+ if (fully_filled) {+ margin_release = order_blocked; // release all remaining+ repo().delete_margin_block(order_id);+ } else {+ double frac = (order.quantity > 0.0) ? (qty / order.quantity) : 1.0;+ margin_release = order_blocked * frac;+ double remaining = std::max(0.0, order_blocked - margin_release);+ repo().insert_margin_block(generate_uuid(), order.portfolio_id, order_id, order.symbol, remaining);+ }+ }++ // 7b. Update balance// Fee model: deduct fee only on closing fills (when realized PnL is produced).// Entry fees are NOT deducted from balance at open — they are included in the// exit fee when the position is closed. This matches how most exchanges present// unrealized P&L (gross of entry fee) and only settle fees on close.- double balance_change = had_opposite ? (pnl - fee) : pnl;+ // Released margin is credited back to available balance alongside realized P&L.+ double balance_change = (had_opposite ? (pnl - fee) : pnl) + margin_release;repo().update_balance(order.portfolio_id, portfolio.balance + balance_change);// 8. Update order- double new_filled = order.filled_qty + qty;- QString new_status = (new_filled >= order.quantity) ? "filled" : "partial";+ QString new_status = fully_filled ? "filled" : "partial";double prev_avg = order.avg_price.value_or(0.0);double new_avg =(new_filled > 0.0) ? (prev_avg * order.filled_qty + fill_price * qty) / new_filled : fill_price;diff --git a/fincept-qt/src/trading/PaperTrading.h b/fincept-qt/src/trading/PaperTrading.hindex 40cc5ed3a..98860370b 100644--- a/fincept-qt/src/trading/PaperTrading.h+++ b/fincept-qt/src/trading/PaperTrading.h@@ -19,10 +19,54 @@ QVector<PtPortfolio> pt_list_portfolios(const QString& exchange = "");void pt_delete_portfolio(const QString& id);PtPortfolio pt_reset_portfolio(const QString& id);+// --- Leverage / Margin config (Phase 3 §4) ---+// Per-portfolio leverage rules + market-hours enforcement live in an in-memory+// config map (the existing pt_portfolios schema has no columns for them, and we+// must not add a migration). Defaults match OpenAlgo: equity MIS 5x, CNC 1x,+// futures 10x, options buy/sell 1x. enforce_market_hours defaults to FALSE so+// existing behavior is unchanged.+void pt_set_leverage_config(const QString& portfolio_id, const PtLeverageConfig& cfg);+PtLeverageConfig pt_get_leverage_config(const QString& portfolio_id);+void pt_set_enforce_market_hours(const QString& portfolio_id, bool enforce);+bool pt_get_enforce_market_hours(const QString& portfolio_id);++// --- Instrument-type helpers (Phase 3 §4) ---+// Detect derivative type from the canonical symbol suffix (CE/PE = option,+// FUT = future). Mirrors OpenAlgo's utils/symbol_utils.py.+bool pt_is_option(const QString& symbol);+bool pt_is_future(const QString& symbol);++// --- Margin calculation (Phase 3 §4) ---+// trade_value = quantity * price; required margin = trade_value / leverage,+// where leverage is selected by product/instrument-type/exchange/side.+double pt_calculate_required_margin(const QString& portfolio_id, const QString& symbol, const QString& exchange,+ const QString& product, double quantity, double price, const QString& side);++// --- Exchange hours (Phase 3 §4) ---+// IST-aware (UTC+5:30) market-open check. NSE/BSE/NFO/BFO 09:15–15:30,+// MCX 09:00–23:30, CDS 09:00–17:00; all other/unknown exchanges (incl. crypto)+// are treated as always open. This is a free function — enforcement is opt-in+// per portfolio via pt_set_enforce_market_hours().+bool pt_is_market_open(const QString& exchange);+// --- Orders ---+// NOTE (Phase 3 §4): `exchange` and `product` are NEW trailing params with+// defaults — existing call sites (which pass up to `reduce_only`) compile+// unchanged. When provided, they drive per-product leverage and (if the+// portfolio opts in) market-hours enforcement.+//+// Rejection contract: to preserve the existing exception-based contract that+// all current callers rely on (they wrap pt_place_order in try/catch and treat+// a throw as failure), an order that fails the margin or market-hours check+// still THROWS std::runtime_error — but BEFORE throwing it persists a+// status == "rejected" order record (with margin_blocked = 0) so the rejection+// is visible in the order book. Successfully placed orders that increase+// exposure have their required margin blocked and recorded on the order+// (order.margin_blocked) and in pt_margin_blocks.PtOrder pt_place_order(const QString& portfolio_id, const QString& symbol, const QString& side,const QString& order_type, double quantity, std::optional<double> price = std::nullopt,- std::optional<double> stop_price = std::nullopt, bool reduce_only = false);+ std::optional<double> stop_price = std::nullopt, bool reduce_only = false,+ const QString& exchange = "", const QString& product = "");void pt_cancel_order(const QString& order_id);QVector<PtOrder> pt_get_orders(const QString& portfolio_id, const QString& status = "");diff --git a/fincept-qt/src/trading/RateLimiter.cpp b/fincept-qt/src/trading/RateLimiter.cppnew file mode 100644index 000000000..51fc6b03f--- /dev/null+++ b/fincept-qt/src/trading/RateLimiter.cpp@@ -0,0 +1,77 @@+#include "RateLimiter.h"++namespace fincept::trading {++OrderRateLimiter& OrderRateLimiter::instance()+{+ static OrderRateLimiter limiter;+ return limiter;+}++OrderRateLimiter::OrderRateLimiter()+{+ set_limit(BrokerId::Zerodha, 10);+ set_limit(BrokerId::AngelOne, 10);+ set_limit(BrokerId::Upstox, 10);+ set_limit(BrokerId::Fyers, 10);+ set_limit(BrokerId::Dhan, 20);+ set_limit(BrokerId::Kotak, 10);+ set_limit(BrokerId::Groww, 10);+ set_limit(BrokerId::AliceBlue, 10);+ set_limit(BrokerId::FivePaisa, 10);+ set_limit(BrokerId::IIFL, 10);+ set_limit(BrokerId::Motilal, 10);+ set_limit(BrokerId::Shoonya, 10);+ set_limit(BrokerId::Alpaca, 200);+ set_limit(BrokerId::IBKR, 50);+ set_limit(BrokerId::Tradier, 10);+ set_limit(BrokerId::SaxoBank, 10);+ set_limit(BrokerId::MetaTrader4, 10);+}++OrderRateLimiter::BrokerLimit& OrderRateLimiter::get_or_create(BrokerId broker)+{+ QMutexLocker locker(®istry_mutex_);+ int key = static_cast<int>(broker);+ auto it = limits_.find(key);+ if (it == limits_.end())+ it = limits_.emplace(key, std::make_unique<BrokerLimit>()).first;+ return *it->second;+}++void OrderRateLimiter::acquire(BrokerId broker)+{+ auto& limit = get_or_create(broker);+ QMutexLocker locker(&limit.mutex);++ qint64 now = QDateTime::currentMSecsSinceEpoch();+ qint64 min_interval_ms = 1000 / limit.orders_per_second;+ qint64 elapsed = now - limit.last_order_ms;++ if (elapsed < min_interval_ms) {+ qint64 wait = min_interval_ms - elapsed;+ locker.unlock();+ QThread::msleep(static_cast<unsigned long>(wait));+ locker.relock();+ }++ limit.last_order_ms = QDateTime::currentMSecsSinceEpoch();+}++void OrderRateLimiter::set_limit(BrokerId broker, int orders_per_second)+{+ auto& limit = get_or_create(broker);+ QMutexLocker locker(&limit.mutex);+ limit.orders_per_second = (orders_per_second > 0) ? orders_per_second : DEFAULT_LIMIT;+}++int OrderRateLimiter::get_limit(BrokerId broker) const+{+ QMutexLocker locker(®istry_mutex_);+ int key = static_cast<int>(broker);+ auto it = limits_.find(key);+ if (it == limits_.end()) return DEFAULT_LIMIT;+ return it->second->orders_per_second;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/RateLimiter.h b/fincept-qt/src/trading/RateLimiter.hnew file mode 100644index 000000000..ba561e489--- /dev/null+++ b/fincept-qt/src/trading/RateLimiter.h@@ -0,0 +1,39 @@+#pragma once++#include "TradingTypes.h"+#include <QMutex>+#include <QMutexLocker>+#include <QDateTime>+#include <QThread>++#include <memory>+#include <unordered_map>++namespace fincept::trading {++class OrderRateLimiter {+public:+ static OrderRateLimiter& instance();++ void acquire(BrokerId broker);+ void set_limit(BrokerId broker, int orders_per_second);+ int get_limit(BrokerId broker) const;++private:+ OrderRateLimiter();++ struct BrokerLimit {+ int orders_per_second = 10;+ qint64 last_order_ms = 0;+ QMutex mutex;+ };++ BrokerLimit& get_or_create(BrokerId broker);++ std::unordered_map<int, std::unique_ptr<BrokerLimit>> limits_;+ mutable QMutex registry_mutex_;++ static constexpr int DEFAULT_LIMIT = 10;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/SmartOrderEngine.cpp b/fincept-qt/src/trading/SmartOrderEngine.cppnew file mode 100644index 000000000..7d24357ff--- /dev/null+++ b/fincept-qt/src/trading/SmartOrderEngine.cpp@@ -0,0 +1,145 @@+#include "SmartOrderEngine.h"+#include "../core/logging/Logger.h"+#include <cmath>++namespace fincept::trading {++SmartOrderEngine& SmartOrderEngine::instance()+{+ static SmartOrderEngine engine;+ return engine;+}++QMutex* SmartOrderEngine::get_symbol_lock(+ const QString& symbol, const QString& exchange, const QString& product)+{+ std::string key = (symbol + ":" + exchange + ":" + product).toStdString();+ QMutexLocker locker(&lock_registry_mutex_);+ auto it = symbol_locks_.find(key);+ if (it == symbol_locks_.end())+ it = symbol_locks_.emplace(key, std::make_unique<QMutex>()).first;+ return it->second.get();+}++QVector<BrokerPosition> SmartOrderEngine::get_positions_cached(+ IBroker* broker, const BrokerCredentials& creds)+{+ QMutexLocker locker(&cache_mutex_);+ qint64 now = QDateTime::currentMSecsSinceEpoch();+ auto it = position_cache_.find(creds.access_token);+ if (it != position_cache_.end() && (now - it->fetched_at_ms) < CACHE_TTL_MS) {+ return it->positions;+ }+ locker.unlock();++ auto resp = broker->get_positions(creds);+ QVector<BrokerPosition> positions;+ if (resp.success && resp.data.has_value())+ positions = resp.data.value();++ locker.relock();+ position_cache_[creds.access_token] = {positions, QDateTime::currentMSecsSinceEpoch()};+ return positions;+}++void SmartOrderEngine::invalidate_cache(const QString& auth_token)+{+ QMutexLocker locker(&cache_mutex_);+ position_cache_.remove(auth_token);+}++void SmartOrderEngine::clear_all_caches()+{+ QMutexLocker locker(&cache_mutex_);+ position_cache_.clear();+}++double SmartOrderEngine::find_current_position(+ const QVector<BrokerPosition>& positions,+ const QString& symbol, const QString& exchange, const QString& product)+{+ for (const auto& p : positions) {+ if (p.symbol == symbol && p.exchange == exchange+ && (product.isEmpty() || p.product_type == product)) {+ return p.quantity;+ }+ }+ return 0.0;+}++ApiResponse<SmartOrderResult> SmartOrderEngine::execute(+ IBroker* broker, const BrokerCredentials& creds, const SmartOrder& order)+{+ auto* lock = get_symbol_lock(order.symbol, order.exchange,+ product_type_str(order.product_type));+ QMutexLocker locker(lock);++ auto positions = get_positions_cached(broker, creds);+ double current = find_current_position(+ positions, order.symbol, order.exchange,+ product_type_str(order.product_type));++ double target = order.position_size;+ OrderSide action;+ double quantity;++ if (target == 0 && current == 0) {+ action = order.action;+ quantity = order.quantity;+ if (quantity <= 0) {+ return {true, SmartOrderResult{false, {}, {}, 0,+ "No action needed. Position is zero and no quantity specified."}, {}};+ }+ } else if (target == 0 && current > 0) {+ action = OrderSide::Sell;+ quantity = std::abs(current);+ } else if (target == 0 && current < 0) {+ action = OrderSide::Buy;+ quantity = std::abs(current);+ } else if (current == 0) {+ action = (target > 0) ? OrderSide::Buy : OrderSide::Sell;+ quantity = std::abs(target);+ } else if (target > current) {+ action = OrderSide::Buy;+ quantity = target - current;+ } else if (target < current) {+ action = OrderSide::Sell;+ quantity = current - target;+ } else {+ return {true, SmartOrderResult{false, {}, {}, 0,+ "No action needed. Position already at target."}, {}};+ }++ LOG_INFO("SmartOrder", QString("Adjusting %1:%2 from %3 to %4 → %5 %6")+ .arg(order.symbol, order.exchange)+ .arg(current).arg(target)+ .arg(action == OrderSide::Buy ? "BUY" : "SELL")+ .arg(quantity));++ UnifiedOrder unified;+ unified.symbol = order.symbol;+ unified.exchange = order.exchange;+ unified.side = action;+ unified.quantity = quantity;+ unified.order_type = order.order_type;+ unified.price = order.price;+ unified.stop_price = order.trigger_price;+ unified.product_type = order.product_type;++ auto resp = broker->place_order(creds, unified);++ invalidate_cache(creds.access_token);++ SmartOrderResult result;+ result.action_taken = true;+ result.order_id = resp.success ? resp.order_id : QString();+ result.executed_action = action;+ result.executed_quantity = quantity;+ result.message = resp.success+ ? QString("Adjusted position from %1 to %2").arg(current).arg(target)+ : resp.error;++ return {resp.success, result, resp.error};+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/SmartOrderEngine.h b/fincept-qt/src/trading/SmartOrderEngine.hnew file mode 100644index 000000000..f320970b3--- /dev/null+++ b/fincept-qt/src/trading/SmartOrderEngine.h@@ -0,0 +1,56 @@+#pragma once++#include "TradingTypes.h"+#include "BrokerInterface.h"+#include <QHash>+#include <QMutex>+#include <QMutexLocker>+#include <QDateTime>+#include <memory>+#include <string>+#include <unordered_map>++namespace fincept::trading {++class SmartOrderEngine {+public:+ static SmartOrderEngine& instance();++ ApiResponse<SmartOrderResult> execute(+ IBroker* broker,+ const BrokerCredentials& creds,+ const SmartOrder& order);++ void invalidate_cache(const QString& auth_token);+ void clear_all_caches();++private:+ SmartOrderEngine() = default;++ QMutex* get_symbol_lock(const QString& symbol,+ const QString& exchange,+ const QString& product);++ struct PositionCache {+ QVector<BrokerPosition> positions;+ qint64 fetched_at_ms = 0;+ };++ QVector<BrokerPosition> get_positions_cached(+ IBroker* broker, const BrokerCredentials& creds);++ double find_current_position(+ const QVector<BrokerPosition>& positions,+ const QString& symbol,+ const QString& exchange,+ const QString& product);++ std::unordered_map<std::string, std::unique_ptr<QMutex>> symbol_locks_;+ QMutex lock_registry_mutex_;++ QHash<QString, PositionCache> position_cache_;+ QMutex cache_mutex_;+ static constexpr qint64 CACHE_TTL_MS = 1000;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/StrategyPortfolio.cpp b/fincept-qt/src/trading/StrategyPortfolio.cppnew file mode 100644index 000000000..4ab113224--- /dev/null+++ b/fincept-qt/src/trading/StrategyPortfolio.cpp@@ -0,0 +1,184 @@+// StrategyPortfolio.cpp — saved-strategy persistence (§16) + qty-freeze (§17).+#include "trading/StrategyPortfolio.h"++#include "core/logging/Logger.h"+#include "storage/sqlite/Database.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QSqlQuery>+#include <QUuid>++namespace fincept::trading {++namespace {+constexpr const char* kLog = "StrategyPortfolio";++QJsonObject leg_to_json(const OptionsLeg& leg) {+ QJsonObject j;+ j["symbol"] = leg.symbol;+ j["exchange"] = leg.exchange;+ j["side"] = leg.side == OrderSide::Buy ? "BUY" : "SELL";+ j["quantity"] = leg.quantity;+ j["strike"] = leg.strike;+ j["option_type"] = leg.option_type;+ j["expiry"] = leg.expiry;+ return j;+}++OptionsLeg leg_from_json(const QJsonObject& j) {+ OptionsLeg leg;+ leg.symbol = j.value("symbol").toString();+ leg.exchange = j.value("exchange").toString();+ leg.side = j.value("side").toString().toUpper() == "SELL" ? OrderSide::Sell : OrderSide::Buy;+ leg.quantity = j.value("quantity").toDouble();+ leg.strike = j.value("strike").toDouble();+ leg.option_type = j.value("option_type").toString();+ leg.expiry = j.value("expiry").toString();+ return leg;+}++QString legs_to_json_str(const QVector<OptionsLeg>& legs) {+ QJsonArray arr;+ for (const auto& leg : legs)+ arr.append(leg_to_json(leg));+ return QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact));+}++QVector<OptionsLeg> legs_from_json_str(const QString& s) {+ QVector<OptionsLeg> out;+ const QJsonArray arr = QJsonDocument::fromJson(s.toUtf8()).array();+ out.reserve(arr.size());+ for (const auto& v : arr)+ out.append(leg_from_json(v.toObject()));+ return out;+}++SavedStrategy map_row(QSqlQuery& q) {+ SavedStrategy s;+ s.id = q.value("id").toString();+ s.name = q.value("name").toString();+ s.underlying = q.value("underlying").toString();+ s.notes = q.value("notes").toString();+ s.legs = legs_from_json_str(q.value("legs_json").toString());+ s.created_at = q.value("created_at").toString();+ return s;+}+} // namespace++// ── StrategyPortfolio ────────────────────────────────────────────────────────++StrategyPortfolio& StrategyPortfolio::instance() {+ static StrategyPortfolio s;+ return s;+}++QString StrategyPortfolio::save(const SavedStrategy& in) {+ SavedStrategy s = in;+ if (s.id.isEmpty())+ s.id = QUuid::createUuid().toString(QUuid::WithoutBraces);+ if (s.created_at.isEmpty())+ s.created_at = QDateTime::currentDateTime().toString(Qt::ISODate);++ // Upsert by primary key so save() is idempotent for a given id.+ auto r = Database::instance().execute(+ "INSERT INTO saved_strategies (id, name, underlying, notes, legs_json, created_at) "+ "VALUES (?, ?, ?, ?, ?, ?) "+ "ON CONFLICT(id) DO UPDATE SET name=excluded.name, underlying=excluded.underlying, "+ "notes=excluded.notes, legs_json=excluded.legs_json",+ {s.id, s.name, s.underlying, s.notes, legs_to_json_str(s.legs), s.created_at});+ if (r.is_err()) {+ LOG_ERROR(kLog, QString("save failed: %1").arg(QString::fromStdString(r.error())));+ return {};+ }+ LOG_INFO(kLog, QString("Saved strategy '%1' (%2, %3 legs)").arg(s.name, s.id).arg(s.legs.size()));+ return s.id;+}++bool StrategyPortfolio::update(const SavedStrategy& s) {+ if (s.id.isEmpty())+ return false;+ auto r = Database::instance().execute(+ "UPDATE saved_strategies SET name=?, underlying=?, notes=?, legs_json=? WHERE id=?",+ {s.name, s.underlying, s.notes, legs_to_json_str(s.legs), s.id});+ if (r.is_err()) {+ LOG_ERROR(kLog, QString("update failed: %1").arg(QString::fromStdString(r.error())));+ return false;+ }+ return r.value().numRowsAffected() > 0;+}++bool StrategyPortfolio::remove(const QString& id) {+ if (id.isEmpty())+ return false;+ auto r = Database::instance().execute("DELETE FROM saved_strategies WHERE id=?", {id});+ if (r.is_err()) {+ LOG_ERROR(kLog, QString("remove failed: %1").arg(QString::fromStdString(r.error())));+ return false;+ }+ return r.value().numRowsAffected() > 0;+}++std::optional<SavedStrategy> StrategyPortfolio::get(const QString& id) const {+ auto r = Database::instance().execute("SELECT * FROM saved_strategies WHERE id=?", {id});+ if (r.is_err())+ return std::nullopt;+ auto& q = r.value();+ if (!q.next())+ return std::nullopt;+ return map_row(q);+}++QVector<SavedStrategy> StrategyPortfolio::list() const {+ QVector<SavedStrategy> out;+ auto r = Database::instance().execute(+ "SELECT * FROM saved_strategies ORDER BY created_at DESC");+ if (r.is_err())+ return out;+ auto& q = r.value();+ while (q.next())+ out.append(map_row(q));+ return out;+}++// ── Quantity freeze (§17) ────────────────────────────────────────────────────++int qty_freeze_limit(const QString& symbol, const QString& exchange) {+ if (symbol.isEmpty())+ return 0;+ auto r = Database::instance().execute(+ "SELECT freeze_qty FROM qty_freeze WHERE symbol=? AND exchange=?",+ {symbol, exchange});+ if (r.is_err())+ return 0;+ auto& q = r.value();+ if (!q.next())+ return 0;+ const int limit = q.value(0).toInt();+ return limit > 0 ? limit : 0;+}++bool set_qty_freeze_limit(const QString& symbol, const QString& exchange, int freeze_qty) {+ if (symbol.isEmpty() || exchange.isEmpty())+ return false;++ if (freeze_qty <= 0) {+ auto r = Database::instance().execute(+ "DELETE FROM qty_freeze WHERE symbol=? AND exchange=?", {symbol, exchange});+ return r.is_ok();+ }++ auto r = Database::instance().execute(+ "INSERT INTO qty_freeze (symbol, exchange, freeze_qty) VALUES (?, ?, ?) "+ "ON CONFLICT(symbol, exchange) DO UPDATE SET freeze_qty=excluded.freeze_qty",+ {symbol, exchange, freeze_qty});+ if (r.is_err()) {+ LOG_ERROR(kLog, QString("set_qty_freeze_limit failed: %1").arg(QString::fromStdString(r.error())));+ return false;+ }+ return true;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/StrategyPortfolio.h b/fincept-qt/src/trading/StrategyPortfolio.hnew file mode 100644index 000000000..cc265f299--- /dev/null+++ b/fincept-qt/src/trading/StrategyPortfolio.h@@ -0,0 +1,79 @@+#pragma once+// StrategyPortfolio — persistence for user-saved multi-leg option strategies+// (Phase 3 §16) plus quantity-freeze limit lookups (Phase 3 §17).+//+// OpenAlgo reference: database/strategy_portfolio_db.py (§16),+// database/qty_freeze_db.py (§17).+//+// Both are backed by SQLite (migration v034). Legs are serialized as a JSON+// array of {symbol,exchange,side,quantity,strike,option_type,expiry}.++#include "trading/OptionsStrategyBuilder.h" // OptionsLeg++#include <QString>+#include <QVector>++#include <optional>++namespace fincept::trading {++// ----------------------------------------------------------------------------+// A saved strategy: a named bundle of legs the user can reload into order entry.+// ----------------------------------------------------------------------------+struct SavedStrategy {+ QString id; // uuid (generated on save if empty)+ QString name;+ QString underlying; // e.g. "NIFTY"+ QString notes;+ QVector<OptionsLeg> legs;+ QString created_at; // ISO-8601, set on first save+};++// ----------------------------------------------------------------------------+// CRUD for saved strategies. Singleton; all calls are synchronous against the+// shared SQLite connection (consistent with ActionCenter / PaperTrading).+// ----------------------------------------------------------------------------+class StrategyPortfolio {+ public:+ static StrategyPortfolio& instance();++ // Insert (or upsert by id). Generates a uuid + created_at when id is empty.+ // Returns the id, or an empty string on failure.+ QString save(const SavedStrategy& s);++ // Update an existing row by id. Returns false if the id does not exist or+ // the write fails. Does not touch created_at.+ bool update(const SavedStrategy& s);++ // Delete by id. Returns true if a row was removed.+ bool remove(const QString& id);++ // Fetch one strategy by id.+ std::optional<SavedStrategy> get(const QString& id) const;++ // All saved strategies, newest first.+ QVector<SavedStrategy> list() const;++ StrategyPortfolio(const StrategyPortfolio&) = delete;+ StrategyPortfolio& operator=(const StrategyPortfolio&) = delete;++ private:+ StrategyPortfolio() = default;+};++// ----------------------------------------------------------------------------+// Quantity freeze limits (§17).+//+// Exchanges cap the max quantity per single order (e.g. NSE NIFTY futures 1800).+// These free functions read the qty_freeze table seeded/edited via migration+// v034. Returns 0 when no limit is configured for (symbol, exchange) — callers+// treat 0 as "no freeze limit, place as-is".+// ----------------------------------------------------------------------------++// Look up the freeze limit for (symbol, exchange). Returns 0 if none.+int qty_freeze_limit(const QString& symbol, const QString& exchange);++// Set / overwrite a freeze limit. Pass freeze_qty <= 0 to clear it.+bool set_qty_freeze_limit(const QString& symbol, const QString& exchange, int freeze_qty);++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/TradingEvents.h b/fincept-qt/src/trading/TradingEvents.hnew file mode 100644index 000000000..634d22afa--- /dev/null+++ b/fincept-qt/src/trading/TradingEvents.h@@ -0,0 +1,113 @@+#pragma once+// TradingEvents — typed event records for trading operations, plus helpers to+// publish them onto the application EventBus. Consumers (Action Center UI,+// latency tracker, notification bridge, audit log) subscribe to the string+// event names below.+//+// The EventBus carries QVariantMap payloads, so each typed struct provides a+// to_map() and the publish helpers fan out onto EventBus::publish(name, map).++#include "trading/TradingTypes.h"+#include "core/events/EventBus.h"++#include <QString>+#include <QVariantMap>++namespace fincept::trading {++// Event name constants (string keys for EventBus).+namespace events {+inline constexpr const char* kOrderPlaced = "trading.order_placed";+inline constexpr const char* kOrderFailed = "trading.order_failed";+inline constexpr const char* kSmartOrderNoAction = "trading.smart_order_no_action";+inline constexpr const char* kAllOrdersCancelled = "trading.all_orders_cancelled";+inline constexpr const char* kAllPositionsClosed = "trading.all_positions_closed";+inline constexpr const char* kBasketCompleted = "trading.basket_completed";+inline constexpr const char* kSplitCompleted = "trading.split_completed";+} // namespace events++struct OrderPlacedEvent {+ QString account_id;+ QString order_id;+ QString symbol;+ QString exchange;+ OrderSide action = OrderSide::Buy;+ double quantity = 0;+ QString order_type; // "PLACE", "SMART", "BASKET", "SPLIT"+ QString mode; // "live" or "paper"++ QVariantMap to_map() const {+ return {{"account_id", account_id}, {"order_id", order_id}, {"symbol", symbol},+ {"exchange", exchange}, {"action", action == OrderSide::Buy ? "BUY" : "SELL"},+ {"quantity", quantity}, {"order_type", order_type}, {"mode", mode}};+ }+};++struct OrderFailedEvent {+ QString account_id;+ QString order_type;+ QString symbol;+ QString error_message;+ QString mode;++ QVariantMap to_map() const {+ return {{"account_id", account_id}, {"order_type", order_type}, {"symbol", symbol},+ {"error", error_message}, {"mode", mode}};+ }+};++struct SmartOrderNoActionEvent {+ QString account_id;+ QString symbol;+ QString exchange;+ QString message;+ QVariantMap to_map() const {+ return {{"account_id", account_id}, {"symbol", symbol}, {"exchange", exchange},+ {"message", message}};+ }+};++struct AllOrdersCancelledEvent {+ QString account_id;+ int canceled_count = 0;+ int failed_count = 0;+ QString mode;+ QVariantMap to_map() const {+ return {{"account_id", account_id}, {"canceled_count", canceled_count},+ {"failed_count", failed_count}, {"mode", mode}};+ }+};++struct AllPositionsClosedEvent {+ QString account_id;+ int closed_count = 0;+ int failed_count = 0;+ QString mode;+ QVariantMap to_map() const {+ return {{"account_id", account_id}, {"closed_count", closed_count},+ {"failed_count", failed_count}, {"mode", mode}};+ }+};++struct BasketCompletedEvent {+ QString account_id;+ QString strategy;+ int successful = 0;+ int failed = 0;+ int total = 0;+ QString mode;+ QVariantMap to_map() const {+ return {{"account_id", account_id}, {"strategy", strategy}, {"successful", successful},+ {"failed", failed}, {"total", total}, {"mode", mode}};+ }+};++// Publish helpers — fan out a typed event onto the EventBus.+inline void publish(const OrderPlacedEvent& e) { EventBus::instance().publish(events::kOrderPlaced, e.to_map()); }+inline void publish(const OrderFailedEvent& e) { EventBus::instance().publish(events::kOrderFailed, e.to_map()); }+inline void publish(const SmartOrderNoActionEvent& e) { EventBus::instance().publish(events::kSmartOrderNoAction, e.to_map()); }+inline void publish(const AllOrdersCancelledEvent& e) { EventBus::instance().publish(events::kAllOrdersCancelled, e.to_map()); }+inline void publish(const AllPositionsClosedEvent& e) { EventBus::instance().publish(events::kAllPositionsClosed, e.to_map()); }+inline void publish(const BasketCompletedEvent& e) { EventBus::instance().publish(events::kBasketCompleted, e.to_map()); }++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/TradingNotificationBridge.cpp b/fincept-qt/src/trading/TradingNotificationBridge.cppnew file mode 100644index 000000000..8fa60c1bc--- /dev/null+++ b/fincept-qt/src/trading/TradingNotificationBridge.cpp@@ -0,0 +1,102 @@+#include "trading/TradingNotificationBridge.h"+#include "trading/TradingEvents.h"+#include "core/events/EventBus.h"+#include "services/notifications/NotificationService.h"++namespace fincept::trading {++using notifications::NotificationRequest;+using notifications::NotificationService;+using notifications::NotifLevel;+using notifications::NotifTrigger;++TradingNotificationBridge& TradingNotificationBridge::instance() {+ static TradingNotificationBridge b;+ return b;+}++void TradingNotificationBridge::install() {+ if (installed_)+ return;+ installed_ = true;++ auto& bus = EventBus::instance();++ sub_placed_ = bus.subscribe(events::kOrderPlaced, [](const QVariantMap& d) {+ NotificationRequest req;+ req.title = "Order Placed";+ req.message = QString("%1 %2 %3 %4 (%5) — %6")+ .arg(d.value("action").toString(),+ QString::number(d.value("quantity").toDouble()),+ d.value("symbol").toString(),+ d.value("exchange").toString(),+ d.value("order_type").toString(),+ d.value("mode").toString());+ req.level = NotifLevel::Info;+ req.trigger = NotifTrigger::OrderFill;+ NotificationService::instance().send(req);+ });++ sub_failed_ = bus.subscribe(events::kOrderFailed, [](const QVariantMap& d) {+ NotificationRequest req;+ req.title = "Order Failed";+ req.message = QString("%1 %2 — %3")+ .arg(d.value("order_type").toString(),+ d.value("symbol").toString(),+ d.value("error").toString());+ req.level = NotifLevel::Warning;+ req.trigger = NotifTrigger::OrderFill;+ NotificationService::instance().send(req);+ });++ sub_cancelled_ = bus.subscribe(events::kAllOrdersCancelled, [](const QVariantMap& d) {+ NotificationRequest req;+ req.title = "All Orders Cancelled";+ req.message = QString("%1 cancelled, %2 failed (%3)")+ .arg(d.value("canceled_count").toInt())+ .arg(d.value("failed_count").toInt())+ .arg(d.value("mode").toString());+ req.level = NotifLevel::Alert;+ req.trigger = NotifTrigger::OrderFill;+ NotificationService::instance().send(req);+ });++ sub_closed_ = bus.subscribe(events::kAllPositionsClosed, [](const QVariantMap& d) {+ NotificationRequest req;+ req.title = "All Positions Squared Off";+ req.message = QString("%1 closed, %2 failed (%3)")+ .arg(d.value("closed_count").toInt())+ .arg(d.value("failed_count").toInt())+ .arg(d.value("mode").toString());+ req.level = NotifLevel::Alert;+ req.trigger = NotifTrigger::OrderFill;+ NotificationService::instance().send(req);+ });++ sub_basket_ = bus.subscribe(events::kBasketCompleted, [](const QVariantMap& d) {+ NotificationRequest req;+ req.title = "Basket Order Completed";+ req.message = QString("%1: %2/%3 placed (%4 failed)")+ .arg(d.value("strategy").toString())+ .arg(d.value("successful").toInt())+ .arg(d.value("total").toInt())+ .arg(d.value("failed").toInt());+ req.level = NotifLevel::Info;+ req.trigger = NotifTrigger::OrderFill;+ NotificationService::instance().send(req);+ });+}++void TradingNotificationBridge::uninstall() {+ if (!installed_)+ return;+ auto& bus = EventBus::instance();+ bus.unsubscribe(sub_placed_);+ bus.unsubscribe(sub_failed_);+ bus.unsubscribe(sub_cancelled_);+ bus.unsubscribe(sub_closed_);+ bus.unsubscribe(sub_basket_);+ installed_ = false;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/TradingNotificationBridge.h b/fincept-qt/src/trading/TradingNotificationBridge.hnew file mode 100644index 000000000..124eeec16--- /dev/null+++ b/fincept-qt/src/trading/TradingNotificationBridge.h@@ -0,0 +1,32 @@+#pragma once+// TradingNotificationBridge — subscribes to trading EventBus events and forwards+// the user-relevant ones (order placed/failed, bulk cancel/close, basket done) to+// NotificationService as OrderFill notifications. Closes the Phase 3 §14 gap where+// the trading layer did not auto-fire notifications on order events.+//+// Install once at startup: TradingNotificationBridge::instance().install();++#include <QObject>++namespace fincept::trading {++class TradingNotificationBridge : public QObject {+ Q_OBJECT+ public:+ static TradingNotificationBridge& instance();++ // Subscribe to the trading events on the EventBus. Idempotent.+ void install();+ void uninstall();++ private:+ TradingNotificationBridge() = default;+ bool installed_ = false;+ int sub_placed_ = 0;+ int sub_failed_ = 0;+ int sub_cancelled_ = 0;+ int sub_closed_ = 0;+ int sub_basket_ = 0;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/TradingTypes.h b/fincept-qt/src/trading/TradingTypes.hindex 630f65c23..117d217c8 100644--- a/fincept-qt/src/trading/TradingTypes.h+++ b/fincept-qt/src/trading/TradingTypes.h@@ -17,6 +17,17 @@ namespace fincept::trading {// Paper Trading Types// ============================================================================+/// Per-product leverage rules for paper-trading margin calculation.+/// Mirrors OpenAlgo's sandbox leverage config (fund_manager.py::_get_leverage).+/// All fields have sane defaults so existing portfolios keep working unchanged.+struct PtLeverageConfig {+ double equity_mis = 5.0; // intraday equity (NSE/BSE MIS)+ double equity_cnc = 1.0; // delivery equity (NSE/BSE CNC/NRML)+ double futures = 10.0; // futures (FUT suffix on NFO/BFO/MCX/CDS)+ double options_buy = 1.0; // option buy (premium only)+ double options_sell = 1.0; // option sell (margin estimate)+};+struct PtPortfolio {QString id;QString name;@@ -28,6 +39,14 @@ struct PtPortfolio {double fee_rate = 0.001;QString exchange;QString created_at;++ // NEW (Phase 3 §4): per-product leverage rules + market-hours enforcement.+ // These have defaults so existing portfolios (and the existing DB schema,+ // which has no columns for them) keep working. The leverage config and the+ // enforce flag are managed by an in-memory per-portfolio config map in+ // PaperTrading.cpp (see pt_get/set_leverage_config / pt_set_enforce_market_hours).+ PtLeverageConfig leverage_config{};+ bool enforce_market_hours = false; // opt-in; FALSE preserves existing behavior};struct PtOrder {@@ -45,6 +64,20 @@ struct PtOrder {bool reduce_only = false;QString created_at;std::optional<QString> filled_at;++ // NEW (Phase 3 §4): margin blocked from available balance when this order+ // was placed (released on fill/cancel). Default 0 = no margin blocked+ // (reduce-only / position-reducing orders, or pre-margin-engine orders).+ // Persisted via the pt_margin_blocks table, not a pt_orders column, so the+ // existing pt_orders schema and row mapper are unchanged.+ double margin_blocked = 0.0;++ // NEW (Phase 3 §4): product type used for leverage selection+ // ("MIS"/"CNC"/"NRML"); empty = use portfolio default leverage. Not+ // persisted (transient hint for the margin engine); existing call sites+ // that don't set it default to the portfolio-level leverage.+ QString product;+ QString exchange; // exchange for market-hours / instrument-type detection};struct PtPosition {@@ -402,6 +435,10 @@ enum class BrokerId {IIFL,Motilal,Shoonya,+ Samco,+ Flattrade,+ Paytm,+ Tradejini,Alpaca,IBKR,Tradier,@@ -435,6 +472,14 @@ inline const char* broker_id_str(BrokerId id) {return "motilal";case BrokerId::Shoonya:return "shoonya";+ case BrokerId::Samco:+ return "samco";+ case BrokerId::Flattrade:+ return "flattrade";+ case BrokerId::Paytm:+ return "paytm";+ case BrokerId::Tradejini:+ return "tradejini";case BrokerId::Alpaca:return "alpaca";case BrokerId::IBKR:@@ -474,6 +519,14 @@ inline std::optional<BrokerId> parse_broker_id(const QString& s) {return BrokerId::Motilal;if (s == "shoonya")return BrokerId::Shoonya;+ if (s == "samco")+ return BrokerId::Samco;+ if (s == "flattrade")+ return BrokerId::Flattrade;+ if (s == "paytm")+ return BrokerId::Paytm;+ if (s == "tradejini")+ return BrokerId::Tradejini;if (s == "alpaca")return BrokerId::Alpaca;if (s == "ibkr")@@ -630,6 +683,117 @@ struct UnifiedOrderResponse {QString mode;};+// ---------------------------------------------------------------------------+// Phase 1: Core trading operations (OpenAlgo bridge)+// ---------------------------------------------------------------------------++struct CancelAllResult {+ QStringList canceled_order_ids;+ QVector<QPair<QString, QString>> failed; // {order_id, error}+ int total_attempted = 0;+};++struct CloseAllResult {+ QStringList closed_symbols;+ QVector<QPair<QString, QString>> failed; // {symbol, error}+ int total_positions = 0;+};++struct SmartOrder {+ QString symbol;+ QString exchange;+ OrderSide action = OrderSide::Buy;+ double quantity = 0;+ double position_size = 0; // target position (positive=long, negative=short, 0=flatten)+ OrderType order_type = OrderType::Market;+ double price = 0;+ double trigger_price = 0;+ ProductType product_type = ProductType::Intraday;+};++struct SmartOrderResult {+ bool action_taken = false;+ QString order_id;+ OrderSide executed_action = OrderSide::Buy;+ double executed_quantity = 0;+ QString message;+};++struct DepthLevel {+ double price = 0;+ int quantity = 0;+ int orders = 0;+};++struct MarketDepth {+ QString symbol;+ QString exchange;+ QVector<DepthLevel> bids;+ QVector<DepthLevel> asks;+ double ltp = 0;+ double volume = 0;+ double oi = 0;+};++struct OptionChainEntry {+ double strike_price = 0;+ QString ce_symbol;+ BrokerQuote ce_quote;+ QString pe_symbol;+ BrokerQuote pe_quote;+ QString label; // "ATM", "ITM1", "OTM1", etc.+};++// ============================================================================+// Synthetic Future (Put-Call Parity)+// ============================================================================++/// Calculate the synthetic future price from ATM option quotes using put-call+/// parity: Synthetic_Future = ATM_Call_LTP - ATM_Put_LTP + ATM_Strike.+/// Useful for deriving the implied fair-value of the underlying from option+/// premiums when the spot/futures price is stale or unavailable.+inline double calculate_synthetic_future(double atm_call_ltp, double atm_put_ltp, double atm_strike)+{+ return atm_call_ltp - atm_put_ltp + atm_strike;+}++// ============================================================================+// Basket & Split Orders+// ============================================================================++struct BasketOrderRequest {+ QVector<UnifiedOrder> orders;+ QString strategy_name;+ bool pre_fetch_quotes = true;+};++struct BasketOrderResult {+ struct OrderResult {+ QString symbol;+ QString exchange;+ bool success = false;+ QString order_id;+ QString error;+ };+ QVector<OrderResult> results;+ int successful = 0;+ int failed = 0;+ int total = 0;+};++struct SplitOrderRequest {+ UnifiedOrder base_order;+ int split_size = 0;+ int delay_between_ms = 100;+};++struct SplitOrderResult {+ QVector<BasketOrderResult::OrderResult> results;+ int total_quantity_placed = 0;+ int chunks_successful = 0;+ int chunks_failed = 0;+};+} // namespace fincept::trading#include <QMetaType>diff --git a/fincept-qt/src/trading/UnifiedTrading.cpp b/fincept-qt/src/trading/UnifiedTrading.cppindex 7f276013a..a7fd19e43 100644--- a/fincept-qt/src/trading/UnifiedTrading.cpp+++ b/fincept-qt/src/trading/UnifiedTrading.cpp@@ -4,7 +4,11 @@#include "core/logging/Logger.h"#include "trading/AccountManager.h"+#include "trading/OrderValidator.h"#include "trading/PaperTrading.h"+#include "trading/SmartOrderEngine.h"+#include "trading/StrategyPortfolio.h"+#include "trading/TradingEvents.h"#include "storage/sqlite/Database.h"@@ -12,9 +16,12 @@#include <QMutexLocker>#include <QPointer>#include <QSqlQuery>+#include <QThread>#include <QTimer>#include <QtConcurrent/QtConcurrentRun>+#include <algorithm>+namespace fincept::trading {UnifiedTrading& UnifiedTrading::instance() {@@ -174,9 +181,44 @@ UnifiedOrderResponse UnifiedTrading::place_order(const QString& account_id, consif (account.account_id.isEmpty())return {false, "", "Account not found: " + account_id, ""};- if (account.trading_mode == "paper")- return place_paper_order_for_account(account_id, order);- return place_live_order_for_account(account_id, order);+ // Pre-flight validation (Phase 3 §9).+ auto vr = OrderValidator::validate(order);+ if (!vr.valid) {+ const QString err = vr.errors.join("; ");+ publish(OrderFailedEvent{account_id, "PLACE", order.symbol, err, account.trading_mode});+ return {false, "", "Validation failed: " + err, account.trading_mode};+ }++ // Quantity freeze check (Phase 3 §17). Exchanges cap the max quantity per+ // single order (e.g. NSE NIFTY futures = 1800). place_order is synchronous;+ // an auto-split is inherently async (place_split_orders runs on a worker+ // thread with a callback). To keep place_order's sync contract, we REJECT+ // over-limit orders here with an actionable message rather than silently+ // turning into an async split. Callers that want the split should use+ // place_order_auto_split() instead.+ const int freeze = qty_freeze_limit(order.symbol, order.exchange);+ if (freeze > 0 && order.quantity > freeze) {+ const QString err =+ QString("Quantity %1 exceeds freeze limit %2 for %3 on %4 — "+ "use Split Order (split size %2) or place_order_auto_split().")+ .arg(static_cast<qint64>(order.quantity))+ .arg(freeze)+ .arg(order.symbol, order.exchange);+ publish(OrderFailedEvent{account_id, "PLACE", order.symbol, err, account.trading_mode});+ return {false, "", err, account.trading_mode};+ }++ UnifiedOrderResponse resp = (account.trading_mode == "paper")+ ? place_paper_order_for_account(account_id, order)+ : place_live_order_for_account(account_id, order);++ if (resp.success) {+ publish(OrderPlacedEvent{account_id, resp.order_id, order.symbol, order.exchange,+ order.side, order.quantity, "PLACE", account.trading_mode});+ } else {+ publish(OrderFailedEvent{account_id, "PLACE", order.symbol, resp.message, account.trading_mode});+ }+ return resp;}UnifiedOrderResponse UnifiedTrading::cancel_order(const QString& account_id, const QString& order_id) {@@ -290,4 +332,537 @@ QVector<UnifiedTrading::BroadcastResult> UnifiedTrading::broadcast_order(const Qreturn results;}+// ============================================================================+// Phase 1: Bulk Operations (OpenAlgo bridge)+// ============================================================================++ApiResponse<CancelAllResult> UnifiedTrading::cancel_all_orders(const QString& account_id) {+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty())+ return {false, std::nullopt, "Account not found: " + account_id};++ if (account.trading_mode == "paper") {+ CancelAllResult result;+ auto pending = pt_get_orders(account.paper_portfolio_id, "pending");+ for (const auto& order : pending) {+ try {+ pt_cancel_order(order.id);+ result.canceled_order_ids.append(order.id);+ } catch (...) {+ result.failed.append({order.id, "Cancel failed"});+ }+ result.total_attempted++;+ }+ publish(AllOrdersCancelledEvent{account_id, (int)result.canceled_order_ids.size(),+ (int)result.failed.size(), "paper"});+ return {true, result, {}};+ }++ auto* broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker)+ return {false, std::nullopt, "Broker not found: " + account.broker_id};++ auto creds = AccountManager::instance().load_credentials(account_id);+ auto resp = broker->cancel_all_orders(creds);+ if (resp.success && resp.data.has_value()) {+ publish(AllOrdersCancelledEvent{account_id, (int)resp.data->canceled_order_ids.size(),+ (int)resp.data->failed.size(), "live"});+ }+ return resp;+}++ApiResponse<CloseAllResult> UnifiedTrading::close_all_positions(const QString& account_id) {+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty())+ return {false, std::nullopt, "Account not found: " + account_id};++ if (account.trading_mode == "paper") {+ CloseAllResult result;+ auto positions = pt_get_positions(account.paper_portfolio_id);+ for (const auto& pos : positions) {+ if (pos.quantity == 0) continue;+ result.total_positions++;+ auto side_str = (pos.quantity > 0) ? QString("sell") : QString("buy");+ try {+ auto paper_order = pt_place_order(account.paper_portfolio_id, pos.symbol,+ side_str, "market", std::abs(pos.quantity), pos.current_price, std::nullopt, false);+ pt_fill_order(paper_order.id, pos.current_price);+ result.closed_symbols.append(pos.symbol);+ } catch (...) {+ result.failed.append({pos.symbol, "Close failed"});+ }+ }+ publish(AllPositionsClosedEvent{account_id, (int)result.closed_symbols.size(),+ (int)result.failed.size(), "paper"});+ return {true, result, {}};+ }++ auto* broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker)+ return {false, std::nullopt, "Broker not found: " + account.broker_id};++ auto creds = AccountManager::instance().load_credentials(account_id);+ auto resp = broker->close_all_positions(creds);+ if (resp.success && resp.data.has_value()) {+ publish(AllPositionsClosedEvent{account_id, (int)resp.data->closed_symbols.size(),+ (int)resp.data->failed.size(), "live"});+ }+ return resp;+}++ApiResponse<OrderPlaceResponse> UnifiedTrading::close_position(+ const QString& account_id, const QString& symbol,+ const QString& exchange, const QString& product_type)+{+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty())+ return {false, std::nullopt, "Account not found: " + account_id};++ if (account.trading_mode == "paper") {+ auto positions = pt_get_positions(account.paper_portfolio_id);+ for (const auto& pos : positions) {+ QString pos_sym = pos.symbol;+ if (pos_sym == symbol || pos_sym == exchange + ":" + symbol) {+ if (pos.quantity == 0) continue;+ auto side_str = (pos.quantity > 0) ? QString("sell") : QString("buy");+ try {+ auto paper_order = pt_place_order(account.paper_portfolio_id, pos.symbol,+ side_str, "market", std::abs(pos.quantity), pos.current_price, std::nullopt, false);+ pt_fill_order(paper_order.id, pos.current_price);+ return {true, OrderPlaceResponse{true, paper_order.id, {}}, {}};+ } catch (const std::exception& e) {+ return {false, std::nullopt, QString("Close failed: %1").arg(e.what())};+ }+ }+ }+ return {false, std::nullopt, "Position not found"};+ }++ auto* broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker)+ return {false, std::nullopt, "Broker not found: " + account.broker_id};++ auto creds = AccountManager::instance().load_credentials(account_id);+ return broker->close_position(creds, symbol, exchange, product_type);+}++ApiResponse<SmartOrderResult> UnifiedTrading::place_smart_order(+ const QString& account_id, const SmartOrder& order)+{+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty())+ return {false, std::nullopt, "Account not found: " + account_id};++ if (account.trading_mode == "paper") {+ // Paper mode: get paper positions, calculate delta, place paper order+ auto positions = pt_get_positions(account.paper_portfolio_id);+ double current = 0;+ QString paper_sym = order.exchange.isEmpty() ? order.symbol : order.exchange + ":" + order.symbol;+ for (const auto& p : positions) {+ if (p.symbol == paper_sym) {+ current = p.quantity;+ break;+ }+ }++ double target = order.position_size;+ OrderSide action;+ double quantity;++ if (target == 0 && current == 0) {+ action = order.action;+ quantity = order.quantity;+ if (quantity <= 0)+ return {true, SmartOrderResult{false, {}, {}, 0,+ "No action needed. Position is zero."}, {}};+ } else if (target == 0 && current > 0) {+ action = OrderSide::Sell; quantity = std::abs(current);+ } else if (target == 0 && current < 0) {+ action = OrderSide::Buy; quantity = std::abs(current);+ } else if (current == 0) {+ action = (target > 0) ? OrderSide::Buy : OrderSide::Sell;+ quantity = std::abs(target);+ } else if (target > current) {+ action = OrderSide::Buy; quantity = target - current;+ } else if (target < current) {+ action = OrderSide::Sell; quantity = current - target;+ } else {+ return {true, SmartOrderResult{false, {}, {}, 0,+ "No action needed. Position already at target."}, {}};+ }++ auto side_str = (action == OrderSide::Buy) ? QString("buy") : QString("sell");+ try {+ auto paper_order = pt_place_order(account.paper_portfolio_id, paper_sym,+ side_str, "market", quantity, std::nullopt, std::nullopt, false);+ pt_fill_order(paper_order.id, 1000.0);+ return {true, SmartOrderResult{true, paper_order.id, action, quantity,+ QString("Paper: adjusted from %1 to %2").arg(current).arg(target)}, {}};+ } catch (const std::exception& e) {+ return {false, std::nullopt, QString("Paper smart order failed: %1").arg(e.what())};+ }+ }++ auto* broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker)+ return {false, std::nullopt, "Broker not found: " + account.broker_id};++ auto creds = AccountManager::instance().load_credentials(account_id);+ return SmartOrderEngine::instance().execute(broker, creds, order);+}++ApiResponse<QVector<BrokerQuote>> UnifiedTrading::get_multi_quotes(+ const QString& account_id,+ const QVector<QPair<QString, QString>>& symbols)+{+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty())+ return {false, std::nullopt, "Account not found: " + account_id};++ auto* broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker)+ return {false, std::nullopt, "Broker not found: " + account.broker_id};++ auto creds = AccountManager::instance().load_credentials(account_id);+ return broker->get_multi_quotes(creds, symbols);+}++ApiResponse<MarketDepth> UnifiedTrading::get_market_depth(+ const QString& account_id,+ const QString& symbol, const QString& exchange)+{+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty())+ return {false, std::nullopt, "Account not found: " + account_id};++ auto* broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker)+ return {false, std::nullopt, "Broker not found: " + account.broker_id};++ auto creds = AccountManager::instance().load_credentials(account_id);+ return broker->get_market_depth(creds, symbol, exchange);+}++// ============================================================================+// Basket & Split Orders+// ============================================================================++void UnifiedTrading::place_basket_orders(const QString& account_id, const BasketOrderRequest& basket,+ std::function<void(const BasketOrderResult&)> callback) {+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty()) {+ BasketOrderResult result;+ result.total = basket.orders.size();+ for (const auto& order : basket.orders) {+ result.results.append({order.symbol, order.exchange, false, {},+ "Account not found: " + account_id});+ result.failed++;+ }+ if (callback)+ callback(result);+ return;+ }++ const bool is_paper = (account.trading_mode == "paper");++ // Resolve broker + credentials up front on the calling thread (consistent+ // with the existing place_live_order_for_account helper).+ IBroker* broker = nullptr;+ BrokerCredentials creds;+ QString paper_portfolio_id = account.paper_portfolio_id;+ if (!is_paper) {+ broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker) {+ BasketOrderResult result;+ result.total = basket.orders.size();+ for (const auto& order : basket.orders) {+ result.results.append({order.symbol, order.exchange, false, {},+ "Broker not found: " + account.broker_id});+ result.failed++;+ }+ if (callback)+ callback(result);+ return;+ }+ creds = AccountManager::instance().load_credentials(account_id);+ if (creds.access_token.isEmpty()) {+ BasketOrderResult result;+ result.total = basket.orders.size();+ for (const auto& order : basket.orders) {+ result.results.append({order.symbol, order.exchange, false, {},+ "No credentials for account " + account.display_name ++ ". Please authenticate."});+ result.failed++;+ }+ if (callback)+ callback(result);+ return;+ }+ }++ // Order BUY legs first so that a basket which both buys and sells uses the+ // bought collateral before selling. stable_partition keeps relative order.+ QVector<UnifiedOrder> orders = basket.orders;+ std::stable_partition(orders.begin(), orders.end(),+ [](const UnifiedOrder& o) { return o.side == OrderSide::Buy; });++ QPointer<UnifiedTrading> self = this;+ QtConcurrent::run([self, orders, is_paper, broker, creds, paper_portfolio_id, callback]() {+ BasketOrderResult result;+ result.total = orders.size();++ constexpr int kBatchSize = 10;+ for (int i = 0; i < orders.size(); ++i) {+ // Pause between batches to respect broker rate limits.+ if (i > 0 && (i % kBatchSize) == 0)+ QThread::msleep(1000);++ const UnifiedOrder& order = orders.at(i);+ BasketOrderResult::OrderResult r;+ r.symbol = order.symbol;+ r.exchange = order.exchange;++ if (is_paper) {+ QString symbol = order.exchange.isEmpty() ? order.symbol+ : order.exchange + ":" + order.symbol;+ QString side_str = order_side_str(order.side);+ QString type_str = order_type_str(order.order_type);+ std::optional<double> price_opt;+ if (order.order_type == OrderType::Market)+ price_opt = 1000.0;+ else if (order.price > 0)+ price_opt = order.price;+ std::optional<double> stop_opt;+ if (order.stop_price > 0)+ stop_opt = order.stop_price;+ try {+ auto paper_order = pt_place_order(paper_portfolio_id, symbol, side_str, type_str,+ order.quantity, price_opt, stop_opt, false);+ if (order.order_type == OrderType::Market) {+ double fill_price = order.price > 0 ? order.price : 1000.0;+ pt_fill_order(paper_order.id, fill_price);+ }+ r.success = true;+ r.order_id = paper_order.id;+ } catch (const std::exception& e) {+ r.success = false;+ r.error = QString("Paper order failed: %1").arg(e.what());+ }+ } else {+ OrderPlaceResponse resp = broker->place_order(creds, order);+ r.success = resp.success;+ r.order_id = resp.order_id;+ r.error = resp.error;+ }++ if (r.success)+ result.successful++;+ else+ result.failed++;+ result.results.append(r);+ }++ if (!self)+ return;+ QMetaObject::invokeMethod(+ self,+ [self, result, callback]() {+ if (callback)+ callback(result);+ },+ Qt::QueuedConnection);+ });+}++void UnifiedTrading::place_split_orders(const QString& account_id, const SplitOrderRequest& request,+ std::function<void(const SplitOrderResult&)> callback) {+ auto account = AccountManager::instance().get_account(account_id);+ if (account.account_id.isEmpty()) {+ SplitOrderResult result;+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},+ "Account not found: " + account_id});+ result.chunks_failed++;+ if (callback)+ callback(result);+ return;+ }++ if (request.split_size <= 0) {+ SplitOrderResult result;+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},+ "Invalid split size"});+ result.chunks_failed++;+ if (callback)+ callback(result);+ return;+ }++ const int total = static_cast<int>(request.base_order.quantity);+ const int split_size = request.split_size;+ const int num_full = total / split_size;+ const int remainder = total % split_size;+ const int total_orders = num_full + (remainder > 0 ? 1 : 0);++ if (total_orders > 100) {+ SplitOrderResult result;+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},+ QString("Too many chunks (%1). Maximum is 100.").arg(total_orders)});+ result.chunks_failed++;+ if (callback)+ callback(result);+ return;+ }++ const bool is_paper = (account.trading_mode == "paper");++ IBroker* broker = nullptr;+ BrokerCredentials creds;+ QString paper_portfolio_id = account.paper_portfolio_id;+ if (!is_paper) {+ broker = BrokerRegistry::instance().get(account.broker_id);+ if (!broker) {+ SplitOrderResult result;+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},+ "Broker not found: " + account.broker_id});+ result.chunks_failed++;+ if (callback)+ callback(result);+ return;+ }+ creds = AccountManager::instance().load_credentials(account_id);+ if (creds.access_token.isEmpty()) {+ SplitOrderResult result;+ result.results.append({request.base_order.symbol, request.base_order.exchange, false, {},+ "No credentials for account " + account.display_name ++ ". Please authenticate."});+ result.chunks_failed++;+ if (callback)+ callback(result);+ return;+ }+ }++ // Build the per-chunk quantity list.+ QVector<int> chunk_qtys;+ chunk_qtys.reserve(total_orders);+ for (int i = 0; i < num_full; ++i)+ chunk_qtys.append(split_size);+ if (remainder > 0)+ chunk_qtys.append(remainder);++ UnifiedOrder base = request.base_order;+ const int delay_ms = request.delay_between_ms;++ QPointer<UnifiedTrading> self = this;+ QtConcurrent::run([self, base, chunk_qtys, delay_ms, is_paper, broker, creds,+ paper_portfolio_id, callback]() {+ SplitOrderResult result;++ for (int i = 0; i < chunk_qtys.size(); ++i) {+ if (i > 0)+ QThread::msleep(delay_ms);++ UnifiedOrder chunk = base;+ chunk.quantity = chunk_qtys.at(i);++ BasketOrderResult::OrderResult r;+ r.symbol = chunk.symbol;+ r.exchange = chunk.exchange;++ if (is_paper) {+ QString symbol = chunk.exchange.isEmpty() ? chunk.symbol+ : chunk.exchange + ":" + chunk.symbol;+ QString side_str = order_side_str(chunk.side);+ QString type_str = order_type_str(chunk.order_type);+ std::optional<double> price_opt;+ if (chunk.order_type == OrderType::Market)+ price_opt = 1000.0;+ else if (chunk.price > 0)+ price_opt = chunk.price;+ std::optional<double> stop_opt;+ if (chunk.stop_price > 0)+ stop_opt = chunk.stop_price;+ try {+ auto paper_order = pt_place_order(paper_portfolio_id, symbol, side_str, type_str,+ chunk.quantity, price_opt, stop_opt, false);+ if (chunk.order_type == OrderType::Market) {+ double fill_price = chunk.price > 0 ? chunk.price : 1000.0;+ pt_fill_order(paper_order.id, fill_price);+ }+ r.success = true;+ r.order_id = paper_order.id;+ } catch (const std::exception& e) {+ r.success = false;+ r.error = QString("Paper order failed: %1").arg(e.what());+ }+ } else {+ OrderPlaceResponse resp = broker->place_order(creds, chunk);+ r.success = resp.success;+ r.order_id = resp.order_id;+ r.error = resp.error;+ }++ if (r.success) {+ result.chunks_successful++;+ result.total_quantity_placed += static_cast<int>(chunk.quantity);+ } else {+ result.chunks_failed++;+ }+ result.results.append(r);+ }++ if (!self)+ return;+ QMetaObject::invokeMethod(+ self,+ [self, result, callback]() {+ if (callback)+ callback(result);+ },+ Qt::QueuedConnection);+ });+}++void UnifiedTrading::place_order_auto_split(const QString& account_id, const UnifiedOrder& order,+ std::function<void(const SplitOrderResult&)> callback) {+ const int freeze = qty_freeze_limit(order.symbol, order.exchange);++ if (freeze <= 0 || order.quantity <= freeze) {+ // No freeze limit (or within it) — place a single order synchronously+ // via the normal path, then deliver a one-element SplitOrderResult so+ // callers see a uniform shape. place_order's own freeze check is a+ // no-op here because quantity <= freeze.+ UnifiedOrderResponse resp = place_order(account_id, order);+ SplitOrderResult result;+ BasketOrderResult::OrderResult r;+ r.symbol = order.symbol;+ r.exchange = order.exchange;+ r.success = resp.success;+ r.order_id = resp.order_id;+ r.error = resp.success ? QString() : resp.message;+ result.results.append(r);+ if (resp.success) {+ result.chunks_successful = 1;+ result.total_quantity_placed = static_cast<int>(order.quantity);+ } else {+ result.chunks_failed = 1;+ }+ if (callback)+ callback(result);+ return;+ }++ // Over the freeze limit — auto-split into chunks of `freeze`.+ LOG_INFO("UnifiedTrading",+ QString("Auto-splitting %1 %2 (qty %3 > freeze %4) into chunks of %4")+ .arg(account_id, order.symbol)+ .arg(static_cast<qint64>(order.quantity))+ .arg(freeze));+ SplitOrderRequest req;+ req.base_order = order;+ req.split_size = freeze;+ req.delay_between_ms = 100;+ place_split_orders(account_id, req, std::move(callback));+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/UnifiedTrading.h b/fincept-qt/src/trading/UnifiedTrading.hindex a3d37c668..123d295e5 100644--- a/fincept-qt/src/trading/UnifiedTrading.h+++ b/fincept-qt/src/trading/UnifiedTrading.h@@ -9,6 +9,7 @@#include <QTimer>#include <atomic>+#include <functional>#include <optional>namespace fincept::trading {@@ -43,6 +44,37 @@ class UnifiedTrading : public QObject {};QVector<BroadcastResult> broadcast_order(const QStringList& account_ids, const UnifiedOrder& order);+ // --- Phase 1: Bulk operations (OpenAlgo bridge) ---+ ApiResponse<CancelAllResult> cancel_all_orders(const QString& account_id);+ ApiResponse<CloseAllResult> close_all_positions(const QString& account_id);+ ApiResponse<OrderPlaceResponse> close_position(const QString& account_id,+ const QString& symbol, const QString& exchange, const QString& product_type = {});+ ApiResponse<SmartOrderResult> place_smart_order(const QString& account_id, const SmartOrder& order);+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(const QString& account_id,+ const QVector<QPair<QString, QString>>& symbols);+ ApiResponse<MarketDepth> get_market_depth(const QString& account_id,+ const QString& symbol, const QString& exchange);++ // --- Basket & Split orders ---+ // Both run asynchronously on a background thread (orders are placed+ // sequentially in batches/chunks with sleeps between) and deliver their+ // result back on the caller's thread via the supplied callback.+ void place_basket_orders(const QString& account_id, const BasketOrderRequest& basket,+ std::function<void(const BasketOrderResult&)> callback);+ void place_split_orders(const QString& account_id, const SplitOrderRequest& request,+ std::function<void(const SplitOrderResult&)> callback);++ // Quantity-freeze-aware placement (Phase 3 §17). If the order quantity is+ // within the freeze limit for (symbol, exchange) — or no limit is set — this+ // places a single normal order and delivers a one-element SplitOrderResult.+ // If it exceeds the limit, it auto-splits into chunks of `freeze_limit` via+ // place_split_orders. Asynchronous in BOTH cases (background thread ++ // callback) so callers get a uniform contract regardless of whether a split+ // actually happened. Use this instead of place_order when you want+ // transparent freeze handling; use place_order for the strict sync path.+ void place_order_auto_split(const QString& account_id, const UnifiedOrder& order,+ std::function<void(const SplitOrderResult&)> callback);+UnifiedTrading(const UnifiedTrading&) = delete;UnifiedTrading& operator=(const UnifiedTrading&) = delete;diff --git a/fincept-qt/src/trading/WebhookListener.cpp b/fincept-qt/src/trading/WebhookListener.cppnew file mode 100644index 000000000..af45e99c0--- /dev/null+++ b/fincept-qt/src/trading/WebhookListener.cpp@@ -0,0 +1,198 @@+#include "trading/WebhookListener.h"++#include "core/logging/Logger.h"++#include <QHostAddress>+#include <QJsonArray>+#include <QJsonDocument>+#include <QTcpSocket>++namespace fincept::trading {++namespace {+constexpr const char* WH_TAG = "WebhookListener";+}++WebhookListener::WebhookListener(QObject* parent) : QObject(parent) {+ server_ = new QTcpServer(this);+ connect(server_, &QTcpServer::newConnection, this, &WebhookListener::handle_new_connection);+}++WebhookListener::~WebhookListener() {+ stop();+}++bool WebhookListener::start(quint16 preferred_port) {+ if (server_->isListening())+ return true;++ if (!server_->listen(QHostAddress::LocalHost, preferred_port)) {+ // Preferred port busy — fall back to an ephemeral port.+ if (!server_->listen(QHostAddress::LocalHost, 0)) {+ const QString err = server_->errorString();+ LOG_ERROR(WH_TAG, QString("Failed to bind webhook listener: %1").arg(err));+ emit error_occurred(err);+ return false;+ }+ }+ port_ = server_->serverPort();+ LOG_INFO(WH_TAG, QString("Webhook listener on 127.0.0.1:%1").arg(port_));+ return true;+}++void WebhookListener::stop() {+ if (server_ && server_->isListening())+ server_->close();+ port_ = 0;+}++bool WebhookListener::is_listening() const {+ return server_ && server_->isListening();+}++void WebhookListener::handle_new_connection() {+ while (server_->hasPendingConnections()) {+ QTcpSocket* sock = server_->nextPendingConnection();+ connect(sock, &QTcpSocket::readyRead, this, [this, sock]() {+ const QByteArray raw = sock->readAll();+ if (raw.isEmpty())+ return;++ QString path;+ QJsonObject body;+ QJsonArray body_array;+ bool is_array = false;+ const bool ok = parse_http_request(raw, path, body, body_array, is_array);++ QByteArray response;+ if (!ok) {+ response = http_response(400, "Bad Request: expected JSON body");+ } else {+ route_payload(path, body, body_array, is_array);+ response = http_response(200, "OK");+ }+ sock->write(response);+ sock->flush();+ sock->disconnectFromHost();+ });+ connect(sock, &QTcpSocket::disconnected, sock, &QObject::deleteLater);+ }+}++bool WebhookListener::parse_http_request(const QByteArray& raw, QString& path, QJsonObject& body,+ QJsonArray& body_array, bool& is_array) {+ // Split headers from body at the blank line.+ const int sep = raw.indexOf("\r\n\r\n");+ if (sep < 0)+ return false;++ const QByteArray header_block = raw.left(sep);+ const QByteArray body_block = raw.mid(sep + 4);++ // Request line: "POST /tradingview HTTP/1.1"+ const int line_end = header_block.indexOf("\r\n");+ const QByteArray request_line = line_end < 0 ? header_block : header_block.left(line_end);+ const QList<QByteArray> parts = request_line.split(' ');+ if (parts.size() >= 2)+ path = QString::fromUtf8(parts[1]);++ if (body_block.trimmed().isEmpty())+ return false;++ QJsonParseError perr;+ const QJsonDocument doc = QJsonDocument::fromJson(body_block, &perr);+ if (perr.error != QJsonParseError::NoError)+ return false;++ if (doc.isArray()) {+ is_array = true;+ body_array = doc.array();+ return true;+ }+ if (doc.isObject()) {+ is_array = false;+ body = doc.object();+ return true;+ }+ return false;+}++void WebhookListener::route_payload(const QString& path, const QJsonObject& body,+ const QJsonArray& body_array, bool is_array) {+ const QString p = path.toLower();++ // ChartInk scanner alert — carries scan_name + comma-separated "stocks".+ if (p.contains("chartink") || body.contains("stocks") || body.contains("scan_name")) {+ route_chartink(body);+ return;+ }++ // TradingView alert(s). Array payloads are treated as multiple alerts.+ auto emit_tv = [this](const QJsonObject& obj) {+ const bool is_smart = obj.contains("position_size");+ emit tradingview_alert(obj, is_smart);+ };++ if (is_array) {+ for (const auto& v : body_array) {+ if (v.isObject())+ emit_tv(v.toObject());+ }+ } else {+ emit_tv(body);+ }+}++void WebhookListener::route_chartink(const QJsonObject& body) {+ // ChartInk webhook format:+ // { "stocks": "SBIN,INFY", "trigger_prices": "500,1450",+ // "scan_name": "Bullish Breakout BUY", "alert_name": "...", "triggered_at": "..." }+ // The action is inferred from a keyword in scan_name.+ const QString scan_name = body.value("scan_name").toString().toUpper();+ QString action;+ if (scan_name.contains("SHORT"))+ action = "SELL";+ else if (scan_name.contains("COVER"))+ action = "BUY";+ else if (scan_name.contains("SELL"))+ action = "SELL";+ else if (scan_name.contains("BUY"))+ action = "BUY";++ if (action.isEmpty()) {+ LOG_WARN(WH_TAG, QString("ChartInk alert has no BUY/SELL/SHORT/COVER keyword in scan_name: %1")+ .arg(scan_name));+ emit error_occurred("ChartInk: no action keyword in scan_name");+ return;+ }++ const QStringList stocks = body.value("stocks").toString().split(',', Qt::SkipEmptyParts);+ const QStringList prices = body.value("trigger_prices").toString().split(',', Qt::SkipEmptyParts);++ for (int i = 0; i < stocks.size(); ++i) {+ QJsonObject alert;+ alert["symbol"] = stocks[i].trimmed();+ alert["exchange"] = "NSE"; // ChartInk is NSE/BSE; default NSE, consumer can remap+ alert["action"] = action;+ if (i < prices.size())+ alert["trigger_price"] = prices[i].trimmed().toDouble();+ alert["scan_name"] = scan_name;+ alert["source"] = "chartink";+ emit chartink_alert(alert);+ }+}++QByteArray WebhookListener::http_response(int status, const QString& message) {+ const QJsonObject obj{{"status", status == 200 ? "success" : "error"}, {"message", message}};+ const QByteArray json = QJsonDocument(obj).toJson(QJsonDocument::Compact);+ const QString reason = status == 200 ? "OK" : "Bad Request";+ QByteArray resp;+ resp += QString("HTTP/1.1 %1 %2\r\n").arg(status).arg(reason).toUtf8();+ resp += "Content-Type: application/json\r\n";+ resp += QString("Content-Length: %1\r\n").arg(json.size()).toUtf8();+ resp += "Connection: close\r\n\r\n";+ resp += json;+ return resp;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/WebhookListener.h b/fincept-qt/src/trading/WebhookListener.hnew file mode 100644index 000000000..86e126762--- /dev/null+++ b/fincept-qt/src/trading/WebhookListener.h@@ -0,0 +1,64 @@+#pragma once+// WebhookListener — local loopback HTTP server that receives alert webhooks+// from external charting platforms (TradingView, ChartInk) and turns them into+// orders routed through UnifiedTrading.+//+// Desktop app: there is no public server, so this binds 127.0.0.1:<port>. To+// receive alerts from a cloud platform behind NAT, the user tunnels this port+// (ngrok / cloudflared) — that is out of scope here; we only parse and route.+//+// TradingView alert JSON (line alert) → placeorder+// TradingView alert JSON (strategy) → smartorder (has "position_size")+// ChartInk scanner alert JSON → placeorder per scanned symbol+//+// The listener does NOT place orders itself. It validates + parses the payload+// and emits a signal; the owner (a screen or a service) decides what to do —+// route to UnifiedTrading directly, or queue via the Action Center (Phase 3).++#include <QObject>+#include <QTcpServer>+#include <QJsonObject>++namespace fincept::trading {++class WebhookListener : public QObject {+ Q_OBJECT+ public:+ explicit WebhookListener(QObject* parent = nullptr);+ ~WebhookListener() override;++ // Start listening on 127.0.0.1:preferred_port. Falls back to an ephemeral+ // port if busy; read the actual port via port(). Returns true on success.+ bool start(quint16 preferred_port = 8125);+ void stop();+ bool is_listening() const;+ quint16 port() const { return port_; }++ signals:+ // Emitted for a TradingView line/strategy alert. `is_smart` is true when the+ // payload carried "position_size" (strategy alert → smart order).+ void tradingview_alert(const QJsonObject& alert, bool is_smart);+ // Emitted once per scanned symbol from a ChartInk scanner alert.+ void chartink_alert(const QJsonObject& alert);+ void error_occurred(const QString& message);++ private slots:+ void handle_new_connection();++ private:+ // Parse a raw HTTP request: extract method, path, and JSON body.+ // Returns true and fills `body` if a JSON body was found.+ static bool parse_http_request(const QByteArray& raw, QString& path, QJsonObject& body,+ QJsonArray& body_array, bool& is_array);++ void route_payload(const QString& path, const QJsonObject& body,+ const QJsonArray& body_array, bool is_array);+ void route_chartink(const QJsonObject& body);++ static QByteArray http_response(int status, const QString& message);++ QTcpServer* server_ = nullptr;+ quint16 port_ = 0;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/BrokerHttp.cpp b/fincept-qt/src/trading/brokers/BrokerHttp.cppindex 1f82f4a74..6edeeea7d 100644--- a/fincept-qt/src/trading/brokers/BrokerHttp.cpp+++ b/fincept-qt/src/trading/brokers/BrokerHttp.cpp@@ -4,6 +4,7 @@#include "core/logging/Logger.h"+#include <QElapsedTimer>#include <QEventLoop>#include <QNetworkAccessManager>#include <QNetworkReply>@@ -149,16 +150,22 @@ BrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& urlreturn {false, 0, {}, "", "Failed to create network request"};}- // Block until finished (with timeout)+ // Block until finished (with timeout). Measure the actual network round-trip+ // by bracketing only the event-loop wait — this excludes request setup and+ // JSON parsing so rtt_ms is comparable to what Postman/Bruno report.QEventLoop loop;QTimer timer;timer.setSingleShot(true);QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);+ QElapsedTimer rtt;+ rtt.start();timer.start(timeout_ms_);loop.exec();+ const double elapsed_ms = static_cast<double>(rtt.nsecsElapsed()) / 1e6;BrokerHttpResponse result;+ result.rtt_ms = elapsed_ms;if (timer.isActive()) {timer.stop();@@ -166,7 +173,10 @@ BrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& url// Timeoutreply->abort();reply->deleteLater();- return {false, 0, {}, "", "Request timed out"};+ BrokerHttpResponse timeout_result;+ timeout_result.error = "Request timed out";+ timeout_result.rtt_ms = elapsed_ms;+ return timeout_result;}result.status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();diff --git a/fincept-qt/src/trading/brokers/BrokerHttp.h b/fincept-qt/src/trading/brokers/BrokerHttp.hindex eb171ab2f..2d2f9c9dc 100644--- a/fincept-qt/src/trading/brokers/BrokerHttp.h+++ b/fincept-qt/src/trading/brokers/BrokerHttp.h@@ -17,6 +17,7 @@ struct BrokerHttpResponse {QJsonObject json;QString raw_body;QString error;+ double rtt_ms = 0; // round-trip time of the network wait (ms), set on every return path};class BrokerHttp {diff --git a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.h b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.hindex 54ed41be7..3fd0f5db1 100644--- a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.h+++ b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.h@@ -10,6 +10,7 @@ class AliceBlueBroker : public IBroker {BrokerId id() const override { return BrokerId::AliceBlue; }const char* name() const override { return "AliceBlue"; }const char* base_url() const override { return "https://a3.aliceblueonline.com"; }+ const char* ws_adapter_name() const override { return "aliceblue"; }BrokerProfile profile() const override {return BrokerProfile{diff --git a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cppindex bd2e1e38c..a937864bc 100644--- a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp+++ b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.cpp@@ -961,4 +961,173 @@ ApiResponse<QVector<BrokerMetaEntry>> AlpacaBroker::get_exchange_codes(const Broreturn {true, result, "", ts};}+// ─── Bulk Operations (native Alpaca endpoints) ─────────────────────────────++// DELETE /v2/orders — cancels ALL open orders in one call.+// Returns HTTP 207 with an array of { id, status, body } results.+ApiResponse<CancelAllResult> AlpacaBroker::cancel_all_orders(const BrokerCredentials& creds) {+ auto resp = BrokerHttp::instance().del(trading_url(creds) + "/v2/orders", auth_headers(creds));+ int64_t ts = now_ts();++ // Alpaca returns 207 with an array body even on success.+ // BrokerHttp may mark 207 as success=false since it's not 200, so parse raw_body directly.+ QJsonParseError err;+ auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError && !resp.success) {+ LOG_ERROR("AlpacaBroker", QString("cancel_all_orders failed: %1 | body: %2").arg(resp.error, resp.raw_body));+ return {false, std::nullopt, resp.error.isEmpty() ? resp.raw_body : resp.error, ts};+ }++ CancelAllResult result;+ if (doc.isArray()) {+ for (const auto& v : doc.array()) {+ auto item = v.toObject();+ QString order_id = item.value("id").toString();+ int status = item.value("status").toInt();+ result.total_attempted++;+ if (status == 200) {+ result.canceled_order_ids.append(order_id);+ } else {+ auto body_obj = item.value("body").toObject();+ QString msg = body_obj.value("message").toString();+ if (msg.isEmpty())+ msg = QString("HTTP %1").arg(status);+ result.failed.append({order_id, msg});+ }+ }+ }+ // An empty array is valid — means there were no open orders.+ LOG_INFO("AlpacaBroker", QString("cancel_all_orders: %1 attempted, %2 canceled, %3 failed")+ .arg(result.total_attempted)+ .arg(result.canceled_order_ids.size())+ .arg(result.failed.size()));+ return {true, result, "", ts};+}++// DELETE /v2/positions — liquidates ALL open positions in one call.+// Returns an array of close-order objects (one per position).+ApiResponse<CloseAllResult> AlpacaBroker::close_all_positions(const BrokerCredentials& creds) {+ auto resp = BrokerHttp::instance().del(trading_url(creds) + "/v2/positions", auth_headers(creds));+ int64_t ts = now_ts();++ QJsonParseError err;+ auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError && !resp.success) {+ LOG_ERROR("AlpacaBroker", QString("close_all_positions failed: %1 | body: %2").arg(resp.error, resp.raw_body));+ return {false, std::nullopt, resp.error.isEmpty() ? resp.raw_body : resp.error, ts};+ }++ CloseAllResult result;+ if (doc.isArray()) {+ for (const auto& v : doc.array()) {+ auto item = v.toObject();+ QString symbol = item.value("symbol").toString();+ int status = item.value("status").toInt();+ result.total_positions++;+ if (status == 200) {+ result.closed_symbols.append(symbol);+ } else {+ // For positions, the body contains the close order or error info+ auto body_obj = item.value("body").toObject();+ QString msg = body_obj.value("message").toString();+ if (msg.isEmpty())+ msg = QString("HTTP %1").arg(status);+ result.failed.append({symbol, msg});+ }+ }+ }+ LOG_INFO("AlpacaBroker", QString("close_all_positions: %1 positions, %2 closed, %3 failed")+ .arg(result.total_positions)+ .arg(result.closed_symbols.size())+ .arg(result.failed.size()));+ return {true, result, "", ts};+}++// GET /v2/stocks/snapshots?symbols=SYM1,SYM2 — batch multi-quotes via snapshots.+// Alpaca's data endpoint supports up to 100 symbols per request.+// Uses data_url() (not trading_url) for market data.+ApiResponse<QVector<BrokerQuote>> AlpacaBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {+ if (symbols.isEmpty())+ return {false, std::nullopt, "No symbols", now_ts()};++ QVector<BrokerQuote> all_quotes;+ QMap<QString, QString> data_headers = alpaca_data_headers(creds);++ // Chunk into batches of 100 (Alpaca limit)+ constexpr int BATCH = 100;+ for (int start = 0; start < symbols.size(); start += BATCH) {+ const int end = std::min<int>(start + BATCH, symbols.size());+ QStringList sym_list;+ sym_list.reserve(end - start);+ for (int i = start; i < end; ++i)+ sym_list.append(symbols[i].first);++ const QString url = data_url() + "/v2/stocks/snapshots?symbols=" + sym_list.join(",") + "&feed=iex";+ auto resp = BrokerHttp::instance().get(url, data_headers);+ int64_t ts = now_ts();+ if (!resp.success) {+ LOG_ERROR("AlpacaBroker",+ QString("get_multi_quotes batch failed: %1 | body: %2").arg(resp.error, resp.raw_body));+ continue; // best-effort — partial batches still return what succeeded+ }++ QJsonParseError err;+ auto doc = QJsonDocument::fromJson(resp.raw_body.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError)+ continue;++ auto snap_obj = doc.object();+ for (int i = start; i < end; ++i) {+ const QString& sym = symbols[i].first;+ auto s = snap_obj.value(sym).toObject();+ if (s.isEmpty())+ continue;+ auto daily = s.value("dailyBar").toObject();+ auto prev = s.value("prevDailyBar").toObject();+ auto latest_trade = s.value("latestTrade").toObject();+ auto latest_quote = s.value("latestQuote").toObject();++ BrokerQuote q;+ q.symbol = sym;+ q.ltp = latest_trade.value("p").toDouble();+ q.bid = latest_quote.value("bp").toDouble();+ q.ask = latest_quote.value("ap").toDouble();+ q.bid_size = latest_quote.value("bs").toDouble();+ q.ask_size = latest_quote.value("as").toDouble();+ q.open = daily.value("o").toDouble();+ q.high = daily.value("h").toDouble();+ q.low = daily.value("l").toDouble();+ q.close = daily.value("c").toDouble();+ q.volume = daily.value("v").toDouble();++ if (q.ltp <= 0 && q.bid > 0 && q.ask > 0)+ q.ltp = (q.bid + q.ask) / 2.0;++ double prev_close = prev.value("c").toDouble();+ if (prev_close > 0 && q.ltp > 0) {+ q.change = q.ltp - prev_close;+ q.change_pct = (q.change / prev_close) * 100.0;+ }+ q.timestamp = ts;+ all_quotes.append(q);+ }+ }++ return {true, all_quotes, "", now_ts()};+}++// ============================================================================+// Pre-trade margin calculator — fallback estimator.+// Alpaca exposes no per-order margin endpoint (margin lives on the account+// object), so we use the shared heuristic estimator+// (BrokerInterface.h::estimate_order_margin). Equity symbols fall into the+// Intraday/Delivery buckets (≈20% / full).+// ============================================================================+ApiResponse<OrderMargin> AlpacaBroker::get_order_margins(const BrokerCredentials& /*creds*/,+ const UnifiedOrder& order) {+ return {true, estimate_order_margin(order), "", now_ts()};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.h b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.hindex c46773dc4..2e6cb3903 100644--- a/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.h+++ b/fincept-qt/src/trading/brokers/alpaca/AlpacaBroker.h@@ -96,6 +96,16 @@ class AlpacaBroker : public IBroker {const QString& symbol, const QString& start,const QString& end) override;+ // --- Bulk Operations (native Alpaca endpoints) ---+ ApiResponse<CancelAllResult> cancel_all_orders(const BrokerCredentials& creds) override;+ ApiResponse<CloseAllResult> close_all_positions(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ // --- Margin Calculator --- Alpaca has no per-order margin API → fallback estimator.+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+protected:QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;};diff --git a/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp b/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cppindex fa97d63c7..658eb3ccc 100644--- a/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp+++ b/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.cpp@@ -703,6 +703,193 @@ ApiResponse<QVector<BrokerQuote>> AngelOneBroker::get_quotes(const BrokerCredentreturn {true, quotes, "", ts};}+// ─────────────────────────────────────────────────────────────────────────────+// get_multi_quotes — batch quote with explicit exchange per symbol+// AngelOne quote endpoint accepts exchangeTokens grouped by exchange.+// Max 50 tokens per request; split into batches if needed.+// ─────────────────────────────────────────────────────────────────────────────++ApiResponse<QVector<BrokerQuote>> AngelOneBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {+ int64_t ts = QDateTime::currentSecsSinceEpoch();++ // Resolve all tokens and group by exchange+ struct TokenEntry {+ QString exchange;+ QString token;+ QString original_symbol;+ };+ QVector<TokenEntry> entries;+ entries.reserve(symbols.size());++ for (const auto& [sym, exch] : symbols) {+ QString exchange = exch.isEmpty() ? QStringLiteral("NSE") : exch;+ QString token = lookup_token(sym, exchange);+ if (token.isEmpty()) {+ LOG_WARN(TAG_AO, QString("get_multi_quotes: token not found for %1:%2, skipping").arg(exchange, sym));+ continue;+ }+ entries.append({exchange, token, sym});+ }++ if (entries.isEmpty())+ return {false, std::nullopt, "No valid symbol tokens found", ts};++ QVector<BrokerQuote> all_quotes;+ const auto headers = auth_headers(creds);++ // Batch in groups of 50 (AngelOne API limit)+ static constexpr int BATCH_SIZE = 50;+ for (int offset = 0; offset < entries.size(); offset += BATCH_SIZE) {+ int end = qMin(offset + BATCH_SIZE, entries.size());++ // Group this batch by exchange+ QMap<QString, QJsonArray> by_exchange;+ for (int i = offset; i < end; ++i)+ by_exchange[entries[i].exchange].append(entries[i].token);++ QJsonObject exchange_tokens;+ for (auto it = by_exchange.constBegin(); it != by_exchange.constEnd(); ++it)+ exchange_tokens[it.key()] = it.value();++ QJsonObject payload{+ {"mode", "FULL"},+ {"exchangeTokens", exchange_tokens},+ };++ auto resp = BrokerHttp::instance().post_json(+ BASE_AO + "/rest/secure/angelbroking/market/v1/quote", payload, headers);++ if (!resp.success || !resp.json.value("status").toBool()) {+ QString err = checked_error(resp, "get_multi_quotes batch failed");+ LOG_ERROR(TAG_AO, err);+ // If first batch fails, return error; otherwise return partial results+ if (all_quotes.isEmpty())+ return {false, std::nullopt, err, ts};+ break;+ }++ auto fetched = resp.json.value("data").toObject().value("fetched").toArray();+ for (const auto& v : fetched) {+ auto q = v.toObject();+ BrokerQuote quote;+ // Strip -EQ/-BE suffix so symbol matches caller's input+ {+ QString sym = q.value("tradingSymbol").toString();+ int dash = sym.lastIndexOf('-');+ if (dash > 0)+ sym = sym.left(dash);+ quote.symbol = sym;+ }+ quote.ltp = q.value("ltp").toDouble();+ quote.open = q.value("open").toDouble();+ quote.high = q.value("high").toDouble();+ quote.low = q.value("low").toDouble();+ quote.close = q.value("close").toDouble();+ quote.volume = q.value("tradeVolume").toDouble();+ quote.change = q.value("netChange").toDouble();+ quote.change_pct = q.value("percentChange").toDouble();+ // bid/ask from depth+ auto depth = q.value("depth").toObject();+ auto buy_arr = depth.value("buy").toArray();+ auto sell_arr = depth.value("sell").toArray();+ for (const auto& b : buy_arr) {+ auto obj = b.toObject();+ double p = obj.value("price").toDouble();+ if (p > 0) {+ quote.bid = p;+ quote.bid_size = obj.value("quantity").toDouble();+ break;+ }+ }+ for (const auto& s : sell_arr) {+ auto obj = s.toObject();+ double p = obj.value("price").toDouble();+ if (p > 0) {+ quote.ask = p;+ quote.ask_size = obj.value("quantity").toDouble();+ break;+ }+ }+ quote.timestamp = ts;+ all_quotes.append(quote);+ }+ }++ return {true, all_quotes, "", ts};+}++// ─────────────────────────────────────────────────────────────────────────────+// get_market_depth — Level 2 bid/ask via FULL quote mode+// AngelOne returns best5BuyData / best5SellData + totalBuyQty / totalSellQty+// ─────────────────────────────────────────────────────────────────────────────++ApiResponse<MarketDepth> AngelOneBroker::get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) {+ int64_t ts = QDateTime::currentSecsSinceEpoch();++ QString exch = exchange.isEmpty() ? QStringLiteral("NSE") : exchange;+ QString token = lookup_token(symbol, exch);+ if (token.isEmpty())+ return {false, std::nullopt, "Symbol token not found for depth: " + exch + ":" + symbol, ts};++ QJsonObject exchange_tokens;+ exchange_tokens[exch] = QJsonArray{token};++ QJsonObject payload{+ {"mode", "FULL"},+ {"exchangeTokens", exchange_tokens},+ };++ auto resp = BrokerHttp::instance().post_json(+ BASE_AO + "/rest/secure/angelbroking/market/v1/quote", payload, auth_headers(creds));++ if (!resp.success || !resp.json.value("status").toBool())+ return {false, std::nullopt, checked_error(resp, "get_market_depth failed"), ts};++ auto fetched = resp.json.value("data").toObject().value("fetched").toArray();+ if (fetched.isEmpty())+ return {false, std::nullopt, "No data returned for depth: " + exch + ":" + symbol, ts};++ auto q = fetched[0].toObject();+ MarketDepth md;+ md.symbol = symbol;+ md.exchange = exch;+ md.ltp = q.value("ltp").toDouble();+ md.volume = q.value("tradeVolume").toDouble();++ // Parse depth arrays — AngelOne returns best5BuyData / best5SellData+ // Each entry: { price, quantity, orders }+ auto depth = q.value("depth").toObject();+ auto buy_arr = depth.value("buy").toArray();+ auto sell_arr = depth.value("sell").toArray();++ // Also check for totalBuyQty / totalSellQty at top level+ // (used for aggregate display; individual levels come from depth arrays)++ for (const auto& b : buy_arr) {+ auto obj = b.toObject();+ DepthLevel level;+ level.price = obj.value("price").toDouble();+ level.quantity = static_cast<int>(obj.value("quantity").toDouble());+ level.orders = static_cast<int>(obj.value("orders").toDouble());+ md.bids.append(level);+ }++ for (const auto& s : sell_arr) {+ auto obj = s.toObject();+ DepthLevel level;+ level.price = obj.value("price").toDouble();+ level.quantity = static_cast<int>(obj.value("quantity").toDouble());+ level.orders = static_cast<int>(obj.value("orders").toDouble());+ md.asks.append(level);+ }++ return {true, md, "", ts};+}+// ─────────────────────────────────────────────────────────────────────────────// Get History (OHLCV candles)// resolution: "1m","3m","5m","10m","15m","30m","1h","1d"diff --git a/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.h b/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.hindex 28fccee42..dd0ff7fc1 100644--- a/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.h+++ b/fincept-qt/src/trading/brokers/angelone/AngelOneBroker.h@@ -58,6 +58,16 @@ class AngelOneBroker : public IBroker {ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,const QVector<QString>& symbols) override;++ // --- Multi-quote & Market Depth ---+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) override;+ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,const QString& resolution, const QString& from_date,const QString& to_date) override;diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cppindex e01f15272..7481338f2 100644--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp@@ -560,4 +560,193 @@ ApiResponse<QVector<BrokerCandle>> DhanBroker::get_history(const BrokerCredentiareturn {true, all_candles, "", ts};}+// ── Multi-Quote ──────────────────────────────────────────────────────────────+// POST /v2/marketfeed/ltp — {NSE_EQ: [securityId1, securityId2...]}+// Groups symbols by exchange segment, max 1000.+// Response: {"data": {"NSE_EQ": {"12345": {"last_price": 500.0, ohlc: {...}}}}}+ApiResponse<QVector<BrokerQuote>> DhanBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {++ int64_t ts = now_ts();+ if (symbols.isEmpty())+ return {true, QVector<BrokerQuote>{}, "", ts};++ // Group securityIds by exchange segment, keep reverse map+ QMap<QString, QJsonArray> by_segment;+ QMap<QString, QPair<QString, QString>> id_to_orig; // "seg:secId" → (symbol, exchange)++ for (const auto& [sym, exch] : symbols) {+ const QString exchange = exch.isEmpty() ? "NSE" : exch;+ const QString seg = dhan_exchange(exchange);+ const QString sec_id = lookup_security_id(sym, exchange, creds.broker_id);+ if (sec_id.isEmpty())+ continue;+ by_segment[seg].append(sec_id);+ id_to_orig[seg + ":" + sec_id] = {sym, exchange};+ }++ if (by_segment.isEmpty())+ return {false, std::nullopt, "No valid security IDs found", ts};++ // Build request body+ QJsonObject body;+ for (auto it = by_segment.constBegin(); it != by_segment.constEnd(); ++it)+ body[it.key()] = it.value();++ auto resp = BrokerHttp::instance().post_json(BASE + "/v2/marketfeed/ltp", body, auth_headers(creds));+ if (!resp.success || resp.json.value("errorType").toString().length() > 0)+ return {false, std::nullopt, checked_error(resp, "get_multi_quotes failed"), ts};++ // Parse response+ QVector<BrokerQuote> quotes;+ const auto data = resp.json.value("data").toObject();+ for (auto seg_it = data.constBegin(); seg_it != data.constEnd(); ++seg_it) {+ const QString seg = seg_it.key();+ const auto tokens = seg_it.value().toObject();+ for (auto tok_it = tokens.constBegin(); tok_it != tokens.constEnd(); ++tok_it) {+ const auto q = tok_it.value().toObject();+ BrokerQuote quote;+ const QString lookup_key = seg + ":" + tok_it.key();+ if (id_to_orig.contains(lookup_key))+ quote.symbol = id_to_orig.value(lookup_key).first;+ else+ quote.symbol = tok_it.key();+ quote.ltp = q.value("last_price").toDouble();+ const auto ohlc = q.value("ohlc").toObject();+ quote.open = ohlc.value("open").toDouble(q.value("open").toDouble());+ quote.high = ohlc.value("high").toDouble(q.value("high").toDouble());+ quote.low = ohlc.value("low").toDouble(q.value("low").toDouble());+ quote.close = ohlc.value("close").toDouble(q.value("close").toDouble());+ quote.volume = q.value("volume").toDouble();+ if (quote.close > 0) {+ quote.change = quote.ltp - quote.close;+ quote.change_pct = (quote.ltp - quote.close) / quote.close * 100.0;+ }+ quote.timestamp = ts;+ quotes.append(quote);+ }+ }+ return {true, quotes, "", ts};+}++// ── Market Depth ─────────────────────────────────────────────────────────────+// POST /v2/marketfeed/ohlc — {NSE_EQ: [securityId]}+// Returns OHLC + depth data for the requested security.+// Response: {"data": {"NSE_EQ": {"12345": {last_price, ohlc:{...}, depth:{buy:[...], sell:[...]}}}}}+ApiResponse<MarketDepth> DhanBroker::get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) {++ int64_t ts = now_ts();+ const QString exch = exchange.isEmpty() ? "NSE" : exchange;+ const QString seg = dhan_exchange(exch);+ const QString sec_id = lookup_security_id(symbol, exch, creds.broker_id);+ if (sec_id.isEmpty())+ return {false, std::nullopt, "Security ID not found for " + exch + ":" + symbol, ts};++ QJsonObject body;+ QJsonArray ids;+ ids.append(sec_id);+ body[seg] = ids;++ auto resp = BrokerHttp::instance().post_json(BASE + "/v2/marketfeed/ohlc", body, auth_headers(creds));+ if (!resp.success || resp.json.value("errorType").toString().length() > 0)+ return {false, std::nullopt, checked_error(resp, "get_market_depth failed"), ts};++ // Navigate: data → segment → securityId+ const auto data = resp.json.value("data").toObject();+ const auto seg_obj = data.value(seg).toObject();+ const auto entry = seg_obj.value(sec_id).toObject();+ if (entry.isEmpty())+ return {false, std::nullopt, "No data returned for " + seg + ":" + sec_id, ts};++ MarketDepth md;+ md.symbol = symbol;+ md.exchange = exch;+ md.ltp = entry.value("last_price").toDouble();+ md.volume = entry.value("volume").toDouble();+ md.oi = entry.value("oi").toDouble();++ const auto depth = entry.value("depth").toObject();++ const auto buy_arr = depth.value("buy").toArray();+ for (const auto& level : buy_arr) {+ auto lv = level.toObject();+ DepthLevel dl;+ dl.price = lv.value("price").toDouble();+ dl.quantity = lv.value("quantity").toInt();+ dl.orders = lv.value("orders").toInt();+ md.bids.append(dl);+ }++ const auto sell_arr = depth.value("sell").toArray();+ for (const auto& level : sell_arr) {+ auto lv = level.toObject();+ DepthLevel dl;+ dl.price = lv.value("price").toDouble();+ dl.quantity = lv.value("quantity").toInt();+ dl.orders = lv.value("orders").toInt();+ md.asks.append(dl);+ }++ return {true, md, "", ts};+}++// ============================================================================+// Pre-trade margin calculator — POST /v2/margincalculator (native, single order)+// Mirrors OpenAlgo broker/dhan/api/margin_api.py + mapping/margin_data.py.+// Payload: {dhanClientId, exchangeSegment, transactionType, quantity,+// productType, securityId, price, triggerPrice?}+// productType for margin: CNC→CNC, NRML→MARGIN, MIS→INTRADAY (matches dhan_enum_map).+// Response: {totalMargin, spanMargin, exposureMargin, variableMargin, availableBalance,+// leverage, brokerage, ...}+// ============================================================================+ApiResponse<OrderMargin> DhanBroker::get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) {+ int64_t ts = now_ts();++ const QString sec_id = lookup_security_id(order.symbol, order.exchange, creds.broker_id);+ if (sec_id.isEmpty())+ return {false, std::nullopt, "Security ID not found for " + order.exchange + ":" + order.symbol, ts};++ QJsonObject body;+ body["dhanClientId"] = creds.api_key;+ body["exchangeSegment"] = dhan_exchange(order.exchange);+ body["transactionType"] = order.side == OrderSide::Buy ? "BUY" : "SELL";+ body["quantity"] = static_cast<int>(order.quantity);+ body["productType"] = dhan_enum_map().product_or(order.product_type, "INTRADAY");+ body["securityId"] = sec_id;+ body["price"] = order.price;+ if (order.stop_price > 0)+ body["triggerPrice"] = order.stop_price;++ auto resp = BrokerHttp::instance().post_json(BASE + "/v2/margincalculator", body, auth_headers(creds));+ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json.value("errorType").toString().length() > 0 || resp.json.value("status").toString() == "failed")+ return {false, std::nullopt, checked_error(resp, "Margin calculation failed"), ts};++ const auto& j = resp.json;+ OrderMargin m;+ m.symbol = order.symbol;+ m.exchange = order.exchange;+ m.side = order.side == OrderSide::Buy ? "BUY" : "SELL";+ m.quantity = order.quantity;+ m.price = order.price;+ m.total = j.value("totalMargin").toDouble();+ m.var_margin = j.value("spanMargin").toDouble(); // SPAN+ m.elm = j.value("exposureMargin").toDouble(); // Exposure+ m.additional = j.value("variableMargin").toDouble(); // VAR / variable margin+ m.cash = j.value("availableBalance").toDouble();+ m.leverage = j.value("leverage").toDouble();+ if (m.leverage <= 0.0) {+ const double notional = order.price * order.quantity;+ if (m.total > 0.0 && notional > 0.0)+ m.leverage = notional / m.total;+ }+ return {true, m, "", ts};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.h b/fincept-qt/src/trading/brokers/dhan/DhanBroker.hindex 210e65005..1cc447eef 100644--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.h+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.h@@ -10,6 +10,7 @@ class DhanBroker : public IBroker {BrokerId id() const override { return BrokerId::Dhan; }const char* name() const override { return "Dhan"; }const char* base_url() const override { return "https://api.dhan.co"; }+ const char* ws_adapter_name() const override { return "dhan"; }BrokerProfile profile() const override {return BrokerProfile{@@ -59,6 +60,18 @@ class DhanBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // --- Multi-quote & Market Depth ---+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) override;++ // --- Margin Calculator --- POST /v2/margincalculator (native, single order)+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);diff --git a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cppindex db75a95a3..df73b7e91 100644--- a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp+++ b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.cpp@@ -687,4 +687,15 @@ ApiResponse<QVector<BrokerCandle>> FivePaisaBroker::get_history(const BrokerCredreturn {true, result, "", ts};}+// ============================================================================+// Pre-trade margin calculator — fallback estimator.+// 5Paisa has no position-specific margin calculator API (OpenAlgo's+// broker/fivepaisa/api/margin_api.py raises NotImplementedError), so we use the+// shared heuristic estimator (BrokerInterface.h::estimate_order_margin).+// ============================================================================+ApiResponse<OrderMargin> FivePaisaBroker::get_order_margins(const BrokerCredentials& /*creds*/,+ const UnifiedOrder& order) {+ return {true, estimate_order_margin(order), "", now_ts()};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.h b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.hindex ed98911d5..d200ed0c3 100644--- a/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.h+++ b/fincept-qt/src/trading/brokers/fivepaisa/FivePaisaBroker.h@@ -14,6 +14,7 @@ class FivePaisaBroker : public IBroker {BrokerId id() const override { return BrokerId::FivePaisa; }const char* name() const override { return "5Paisa"; }const char* base_url() const override { return "https://Openapi.5paisa.com"; }+ const char* ws_adapter_name() const override { return "fivepaisa"; }BrokerProfile profile() const override {return BrokerProfile{@@ -67,6 +68,9 @@ class FivePaisaBroker : public IBroker {static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);+ // --- Margin Calculator --- 5Paisa has no per-order margin API → fallback estimator.+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+protected:QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;diff --git a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cppnew file mode 100644index 000000000..4c522d813--- /dev/null+++ b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.cpp@@ -0,0 +1,682 @@+#include "trading/brokers/flattrade/FlattradeBroker.h"++#include "trading/brokers/BrokerHttp.h"++#include <QCryptographicHash>+#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QUrl>++namespace fincept::trading {++static constexpr const char* BASE = "https://piconnect.flattrade.in/PiConnectAPI";+static constexpr const char* AUTH_URL = "https://authapi.flattrade.in/trade/apitoken";++static int64_t now_ts() {+ return QDateTime::currentSecsSinceEpoch();+}++// ---------- Body builder ----------++QByteArray FlattradeBroker::make_body(const QJsonObject& jdata, const QString& token) {+ QByteArray json = QJsonDocument(jdata).toJson(QJsonDocument::Compact);+ return "jData=" + QUrl::toPercentEncoding(json) + "&jKey=" + token.toUtf8();+}++QString FlattradeBroker::uid_from_creds(const BrokerCredentials& creds) {+ // ApiKey packed as "clientid:::apikey"; uid/actid is the client-id portion.+ // Fall back to user_id, then to the whole api_key if no ":::" separator.+ const QString packed = creds.api_key;+ if (packed.contains(":::"))+ return packed.section(":::", 0, 0);+ if (!creds.user_id.isEmpty())+ return creds.user_id;+ return packed;+}++// ---------- Static helpers ----------++const BrokerEnumMap<QString>& FlattradeBroker::ft_enum_map() {+ static const auto m = [] {+ BrokerEnumMap<QString> x;+ x.set(OrderType::Market, "MKT");+ x.set(OrderType::Limit, "LMT");+ x.set(OrderType::StopLoss, "SL-MKT"); // SL-M: trigger only, market fill+ x.set(OrderType::StopLossLimit, "SL-LMT"); // SL: trigger + limit price+ x.set(ProductType::Intraday, "I");+ x.set(ProductType::Delivery, "C");+ x.set(ProductType::Margin, "M");+ return x;+ }();+ return m;+}++QString FlattradeBroker::ft_status(const QString& s) {+ QString sl = s.toUpper();+ if (sl == "COMPLETE")+ return "filled";+ if (sl == "OPEN" || sl == "TRIGGER PENDING" || sl == "TRIGGER_PENDING")+ return "open";+ if (sl == "CANCELLED" || sl == "CANCELED")+ return "cancelled";+ if (sl == "REJECTED")+ return "rejected";+ return "open";+}++bool FlattradeBroker::is_token_expired(const BrokerHttpResponse& resp) {+ if (resp.status_code == 401 || resp.status_code == 403)+ return true;+ if (!resp.success)+ return false;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return false;+ QJsonObject obj = doc.object();+ if (obj.value("stat").toString() != "Not_Ok")+ return false;+ QString emsg = obj.value("emsg").toString().toLower();+ return emsg.contains("session") || emsg.contains("invalid") || emsg.contains("token") || emsg.contains("login") ||+ emsg.contains("expired");+}++QString FlattradeBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {+ if (is_token_expired(resp))+ return "[TOKEN_EXPIRED] Session expired, please re-login";+ if (!resp.success)+ return resp.error.isEmpty() ? fallback : resp.error;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject()) {+ QString emsg = doc.object().value("emsg").toString();+ if (!emsg.isEmpty())+ return emsg;+ }+ return fallback;+}++// ---------- Auth headers ----------+// Flattrade uses no Authorization header — token is in the form body as jKey++QMap<QString, QString> FlattradeBroker::auth_headers(const BrokerCredentials& /*creds*/) const {+ return {{"Content-Type", "application/x-www-form-urlencoded"}};+}++// ---------- exchange_token ----------+// ApiKey = "clientid:::apikey"+// ApiSecret = api_secret+// AuthCode = request_code (one-time code from Flattrade auth redirect)+// security_hash = SHA256(apikey + request_code + api_secret)++TokenExchangeResponse FlattradeBroker::exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) {+ // apikey portion of the packed credential (after ":::"); the uid is before it.+ QString apikey = api_key.contains(":::") ? api_key.section(":::", 1, 1) : api_key;+ QString uid = api_key.contains(":::") ? api_key.section(":::", 0, 0) : api_key;+ QString request_code = auth_code.trimmed();++ if (apikey.isEmpty() || api_secret.isEmpty() || request_code.isEmpty())+ return {false, "", "", "", "Flattrade login: api_key, api_secret and request_code are required", ""};++ QString security_hash = QString(+ QCryptographicHash::hash((apikey + request_code + api_secret).toUtf8(), QCryptographicHash::Sha256).toHex());++ QJsonObject payload;+ payload["api_key"] = apikey;+ payload["request_code"] = request_code;+ payload["api_secret"] = security_hash;++ auto& http = BrokerHttp::instance();+ auto resp = http.post_json(AUTH_URL, payload, {{"Content-Type", "application/json"}});++ if (!resp.success)+ return {false, "", "", "", "Login failed: " + resp.error, ""};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "", "", "Login: invalid response", ""};++ QJsonObject obj = doc.object();+ if (obj.value("stat").toString() != "Ok")+ return {false, "", "", "", obj.value("emsg").toString("Login failed"), ""};++ QString token = obj.value("token").toString();+ if (token.isEmpty())+ return {false, "", "", "", "Login: no token in response", ""};++ return {true, token, "", uid, "", ""};+}++// ---------- place_order ----------++OrderPlaceResponse FlattradeBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {+ const QString uid = uid_from_creds(creds);++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["actid"] = uid;+ jdata["trantype"] = (order.side == OrderSide::Buy) ? "B" : "S";+ jdata["prd"] = ft_enum_map().product_or(order.product_type, "I");+ jdata["exch"] = order.exchange;+ // tsym goes in raw — make_body percent-encodes the JSON wrapper exactly once.+ jdata["tsym"] = order.symbol;+ jdata["qty"] = QString::number(static_cast<int>(order.quantity));+ jdata["dscqty"] = "0";+ jdata["prctyp"] = ft_enum_map().order_type_or(order.order_type, "MKT");+ jdata["prc"] = QString::number(order.price, 'f', 2);+ jdata["trgprc"] = QString::number(order.stop_price, 'f', 2);+ jdata["ret"] = order.validity.isEmpty() ? "DAY" : order.validity;+ jdata["mkt_protection"] = "0";+ jdata["remarks"] = "fincept";+ jdata["ordersource"] = "API";++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/PlaceOrder").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, "", checked_error(resp, "place_order failed")};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "place_order: invalid response"};++ QJsonObject obj = doc.object();+ if (obj.value("stat").toString() != "Ok")+ return {false, "", obj.value("emsg").toString("place_order failed")};++ return {true, obj.value("norenordno").toString(), ""};+}++// ---------- modify_order ----------++ApiResponse<QJsonObject> FlattradeBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) {+ int64_t ts = now_ts();+ const QString uid = uid_from_creds(creds);++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["actid"] = uid;+ jdata["norenordno"] = order_id;+ jdata["exch"] = mods.value("exchange").toString();+ jdata["tsym"] = mods.value("symbol").toString();+ jdata["qty"] = QString::number(mods.value("quantity").toInt(0));+ jdata["prctyp"] = mods.value("orderType").toString("LMT");+ jdata["prc"] = QString::number(mods.value("price").toDouble(0), 'f', 2);+ jdata["dscqty"] = "0";+ jdata["ret"] = mods.value("validity").toString("DAY");+ // Only include trigger price for SL/SL-M — trgprc=0 on LMT causes a reject.+ const QString prctyp = jdata["prctyp"].toString();+ if (prctyp == "SL-LMT" || prctyp == "SL-MKT")+ jdata["trgprc"] = QString::number(mods.value("triggerPrice").toDouble(0), 'f', 2);++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/ModifyOrder").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "modify_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("stat").toString() != "Ok")+ return {false, std::nullopt, obj.value("emsg").toString("modify_order failed"), ts};++ return {true, obj, "", ts};+}++// ---------- cancel_order ----------++ApiResponse<QJsonObject> FlattradeBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {+ int64_t ts = now_ts();++ QJsonObject jdata;+ jdata["uid"] = uid_from_creds(creds);+ jdata["norenordno"] = order_id;++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/CancelOrder").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "cancel_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("stat").toString() != "Ok")+ return {false, std::nullopt, obj.value("emsg").toString("cancel_order failed"), ts};++ return {true, obj, "", ts};+}++// ---------- get_orders ----------++ApiResponse<QVector<BrokerOrderInfo>> FlattradeBroker::get_orders(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ QJsonObject jdata;+ jdata["uid"] = uid_from_creds(creds);++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/OrderBook").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());++ // On empty orders: returns {"stat":"Not_Ok","emsg":"No Data"} object, not array+ if (doc.isObject()) {+ QString emsg = doc.object().value("emsg").toString().toLower();+ if (emsg.contains("no data") || emsg.contains("no order") || emsg.contains("empty"))+ return {true, QVector<BrokerOrderInfo>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, doc.object().value("emsg").toString("get_orders failed")), ts};+ }++ if (!doc.isArray())+ return {false, std::nullopt, "get_orders: invalid response", ts};++ QJsonArray arr = doc.array();+ QVector<BrokerOrderInfo> orders;+ orders.reserve(arr.size());++ for (const QJsonValue& v : arr) {+ QJsonObject o = v.toObject();+ BrokerOrderInfo info;+ info.order_id = o.value("norenordno").toString();+ info.symbol = o.value("tsym").toString();+ info.exchange = o.value("exch").toString();+ info.quantity = o.value("qty").toString().toInt();+ info.filled_qty = o.value("fillshares").toString().toInt();+ info.price = o.value("prc").toString().toDouble();+ info.stop_price = o.value("trgprc").toString().toDouble();+ info.avg_price = o.value("avgprc").toString().toDouble();+ info.status = ft_status(o.value("status").toString());+ info.side = (o.value("trantype").toString() == "B") ? "buy" : "sell";+ info.order_type = o.value("prctyp").toString();+ info.product_type = o.value("prd").toString();+ info.timestamp = o.value("norentm").toString();+ info.message = o.value("rejreason").toString();+ orders.append(info);+ }++ return {true, orders, "", ts};+}++// ---------- get_trade_book ----------++ApiResponse<QJsonObject> FlattradeBroker::get_trade_book(const BrokerCredentials& creds) {+ int64_t ts = now_ts();+ const QString uid = uid_from_creds(creds);++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["actid"] = uid;++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/TradeBook").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_trade_book failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject())+ return {true, doc.object(), "", ts};++ QJsonObject wrapper;+ wrapper["trades"] = doc.array();+ return {true, wrapper, "", ts};+}++// ---------- get_positions ----------++ApiResponse<QVector<BrokerPosition>> FlattradeBroker::get_positions(const BrokerCredentials& creds) {+ int64_t ts = now_ts();+ const QString uid = uid_from_creds(creds);++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["actid"] = uid;++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/PositionBook").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());++ if (doc.isObject()) {+ QString emsg = doc.object().value("emsg").toString().toLower();+ if (emsg.contains("no data") || emsg.contains("no position") || emsg.contains("empty"))+ return {true, QVector<BrokerPosition>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, doc.object().value("emsg").toString("get_positions failed")),+ ts};+ }++ if (!doc.isArray())+ return {false, std::nullopt, "get_positions: invalid response", ts};++ QVector<BrokerPosition> positions;++ for (const QJsonValue& v : doc.array()) {+ QJsonObject o = v.toObject();+ int net_qty = o.value("netqty").toString().toInt();+ if (net_qty == 0)+ continue;++ BrokerPosition pos;+ pos.symbol = o.value("tsym").toString();+ pos.exchange = o.value("exch").toString();+ pos.product_type = o.value("prd").toString();+ pos.quantity = net_qty;+ pos.avg_price = o.value("netavgprc").toString().toDouble();+ pos.ltp = o.value("lp").toString().toDouble();+ pos.pnl = o.value("urmtom").toString().toDouble() + o.value("rpnl").toString().toDouble();+ pos.side = net_qty > 0 ? "LONG" : "SHORT";+ positions.append(pos);+ }++ return {true, positions, "", ts};+}++// ---------- get_holdings ----------++ApiResponse<QVector<BrokerHolding>> FlattradeBroker::get_holdings(const BrokerCredentials& creds) {+ int64_t ts = now_ts();+ const QString uid = uid_from_creds(creds);++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["actid"] = uid;+ jdata["prd"] = "C";++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/Holdings").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());++ if (doc.isObject()) {+ QString emsg = doc.object().value("emsg").toString().toLower();+ if (emsg.contains("no data") || emsg.contains("no holding") || emsg.contains("empty"))+ return {true, QVector<BrokerHolding>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, doc.object().value("emsg").toString("get_holdings failed")),+ ts};+ }++ if (!doc.isArray())+ return {false, std::nullopt, "get_holdings: invalid response", ts};++ QVector<BrokerHolding> holdings;++ for (const QJsonValue& v : doc.array()) {+ QJsonObject o = v.toObject();++ QString symbol, exchange;+ QJsonArray exch_tsym = o.value("exch_tsym").toArray();+ if (!exch_tsym.isEmpty()) {+ QJsonObject et = exch_tsym[0].toObject();+ symbol = et.value("tsym").toString();+ exchange = et.value("exch").toString();+ }+ if (symbol.isEmpty())+ continue;++ int btstqty = o.value("btstqty").toString().toInt();+ int holdqty = o.value("holdqty").toString().toInt();+ int brkcolqty = o.value("brkcolqty").toString().toInt();+ int unplgdqty = o.value("unplgdqty").toString().toInt();+ int benqty = o.value("benqty").toString().toInt();+ int npoadqty = o.value("npoadqty").toString().toInt();+ int dpqty = o.value("dpqty").toString().toInt();+ int usedqty = o.value("usedqty").toString().toInt();+ int total_qty = btstqty + holdqty + brkcolqty + unplgdqty + benqty + qMax(npoadqty, dpqty) - usedqty;++ BrokerHolding h;+ h.symbol = symbol;+ h.exchange = exchange;+ h.quantity = total_qty;+ h.avg_price = o.value("upldprc").toString().toDouble();+ h.ltp = 0.0;+ h.invested_value = total_qty * h.avg_price;+ h.current_value = 0.0;+ h.pnl = 0.0;+ h.pnl_pct = 0.0;+ holdings.append(h);+ }++ return {true, holdings, "", ts};+}++// ---------- get_funds ----------++ApiResponse<BrokerFunds> FlattradeBroker::get_funds(const BrokerCredentials& creds) {+ int64_t ts = now_ts();+ const QString uid = uid_from_creds(creds);++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["actid"] = uid;++ auto& http = BrokerHttp::instance();+ auto resp = http.post_raw(QString("%1/Limits").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_funds: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("stat").toString() != "Ok")+ return {false, std::nullopt, checked_error(resp, obj.value("emsg").toString("get_funds failed")), ts};++ const double cash = obj.value("cash").toString().toDouble();+ const double payin = obj.value("payin").toString().toDouble();+ const double payout = obj.value("payout").toString().toDouble();+ const double daycash = obj.value("daycash").toString().toDouble();+ const double rpnl = obj.value("rpnl").toString().toDouble();+ const double margin_used = obj.value("marginused").toString().toDouble();+ const double collateral = obj.value("brkcollamt").toString().toDouble();++ BrokerFunds funds;+ funds.available_balance = cash + payin - payout + daycash - margin_used;+ funds.used_margin = margin_used;+ funds.total_balance = cash + payin - payout + daycash + rpnl;+ funds.collateral = collateral;+ funds.raw_data = obj;++ return {true, funds, "", ts};+}++// ---------- get_quotes ----------+// Symbol format: "NSE:RELIANCE:22" (exchange:name:token). GetQuotes takes the numeric token.++ApiResponse<QVector<BrokerQuote>> FlattradeBroker::get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) {+ int64_t ts = now_ts();+ if (symbols.isEmpty())+ return {true, QVector<BrokerQuote>{}, "", ts};++ const QString uid = uid_from_creds(creds);+ auto& http = BrokerHttp::instance();+ QVector<BrokerQuote> quotes;++ for (const QString& sym : symbols) {+ QStringList parts = sym.split(":");+ QString exchange = (parts.size() >= 1) ? parts[0] : "NSE";+ QString name = (parts.size() >= 2) ? parts[1] : sym;+ QString token = (parts.size() >= 3) ? parts[2] : "";++ if (token.isEmpty())+ continue; // GetQuotes requires numeric token++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["exch"] = exchange;+ jdata["token"] = token;++ auto resp = http.post_raw(QString("%1/GetQuotes").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});+ if (!resp.success)+ continue;++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ continue;++ QJsonObject o = doc.object();+ if (o.value("stat").toString() != "Ok")+ continue;++ BrokerQuote quote;+ quote.symbol = name;+ quote.ltp = o.value("lp").toString().toDouble();+ quote.open = o.value("o").toString().toDouble();+ quote.high = o.value("h").toString().toDouble();+ quote.low = o.value("l").toString().toDouble();+ quote.close = o.value("c").toString().toDouble();+ quote.volume = o.value("v").toString().toLongLong();+ quote.bid = o.value("bp1").toString().toDouble();+ quote.ask = o.value("sp1").toString().toDouble();+ quote.oi = static_cast<qint64>(o.value("oi").toString().toLongLong());+ if (quote.close > 0) {+ quote.change = quote.ltp - quote.close;+ quote.change_pct = (quote.ltp - quote.close) / quote.close * 100.0;+ } else {+ quote.change = 0.0;+ quote.change_pct = 0.0;+ }+ quote.timestamp = ts;+ quotes.append(quote);+ }++ return {true, quotes, "", ts};+}++// ---------- get_history ----------+// Intraday: POST /TPSeries — st/et epoch seconds, intrv in minutes+// Daily: POST /EODChartData — sym="NSE:RELIANCE", from/to epoch seconds++ApiResponse<QVector<BrokerCandle>> FlattradeBroker::get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) {+ int64_t ts = now_ts();+ const QString uid = uid_from_creds(creds);++ QStringList parts = symbol.split(":");+ QString exchange = (parts.size() >= 1) ? parts[0] : "NSE";+ QString name = (parts.size() >= 2) ? parts[1] : symbol;+ QString token = (parts.size() >= 3) ? parts[2] : "";++ QDate from = QDate::fromString(from_date, "yyyy-MM-dd");+ QDate to = QDate::fromString(to_date, "yyyy-MM-dd");+ if (!from.isValid())+ from = QDate::currentDate().addYears(-1);+ if (!to.isValid())+ to = QDate::currentDate();++ int64_t from_epoch = QDateTime(from, QTime(9, 15, 0)).toSecsSinceEpoch();+ int64_t to_epoch = QDateTime(to, QTime(15, 30, 0)).toSecsSinceEpoch();++ bool is_daily = (resolution == "D" || resolution == "1D" || resolution == "W" || resolution == "M");+ auto& http = BrokerHttp::instance();+ QVector<BrokerCandle> candles;++ if (is_daily) {+ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["sym"] = exchange + ":" + name;+ jdata["from"] = QString::number(from_epoch);+ jdata["to"] = QString::number(to_epoch);++ auto resp = http.post_raw(QString("%1/EODChartData").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});+ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject())+ return {false, std::nullopt, doc.object().value("emsg").toString("get_history failed"), ts};+ if (!doc.isArray())+ return {false, std::nullopt, "get_history: invalid response", ts};++ for (const QJsonValue& v : doc.array()) {+ QJsonObject o = v.toObject();+ BrokerCandle c;+ c.timestamp = static_cast<int64_t>(o.value("ssboe").toDouble()) * 1000LL;+ c.open = o.value("into").toString().toDouble();+ c.high = o.value("inth").toString().toDouble();+ c.low = o.value("intl").toString().toDouble();+ c.close = o.value("intc").toString().toDouble();+ c.volume = o.value("intv").toString().toLongLong();+ c.oi = o.value("oi").toString().toDouble();+ candles.append(c);+ }+ } else {+ if (token.isEmpty())+ return {false, std::nullopt, "get_history: numeric token required for intraday (format NSE:SYMBOL:TOKEN)",+ ts};++ static const QMap<QString, QString> interval_map = {+ {"1", "1"}, {"3", "3"}, {"5", "5"}, {"10", "10"}, {"15", "15"},+ {"30", "30"}, {"60", "60"}, {"120", "120"}, {"240", "240"},+ };+ QString intrv = interval_map.value(resolution, "5");++ QJsonObject jdata;+ jdata["uid"] = uid;+ jdata["exch"] = exchange;+ jdata["token"] = token;+ jdata["st"] = QString::number(from_epoch);+ jdata["et"] = QString::number(to_epoch);+ jdata["intrv"] = intrv;++ auto resp = http.post_raw(QString("%1/TPSeries").arg(BASE), make_body(jdata, creds.access_token),+ {{"Content-Type", "application/x-www-form-urlencoded"}});+ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject())+ return {false, std::nullopt, doc.object().value("emsg").toString("get_history failed"), ts};+ if (!doc.isArray())+ return {false, std::nullopt, "get_history: invalid response", ts};++ for (const QJsonValue& v : doc.array()) {+ QJsonObject o = v.toObject();+ // Timestamp format: "DD-MM-YYYY HH:MM:SS"+ QString time_str = o.value("time").toString();+ QDateTime dt = QDateTime::fromString(time_str, "dd-MM-yyyy HH:mm:ss");+ BrokerCandle c;+ c.timestamp = dt.isValid() ? dt.toSecsSinceEpoch() * 1000LL : 0LL;+ c.open = o.value("into").toString().toDouble();+ c.high = o.value("inth").toString().toDouble();+ c.low = o.value("intl").toString().toDouble();+ c.close = o.value("intc").toString().toDouble();+ c.volume = o.value("intv").toString().toLongLong();+ c.oi = o.value("oi").toString().toDouble();+ candles.append(c);+ }+ }++ return {true, candles, "", ts};+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.h b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.hnew file mode 100644index 000000000..b2618e88b--- /dev/null+++ b/fincept-qt/src/trading/brokers/flattrade/FlattradeBroker.h@@ -0,0 +1,96 @@+#pragma once+#include "trading/BrokerInterface.h"+#include "trading/adapter/BrokerEnumMap.h"+#include "trading/brokers/BrokerHttp.h"++namespace fincept::trading {++// Flattrade is a Noren/Omnesys (PiConnect) platform broker — same wire protocol+// as Shoonya. Trading endpoints live at https://piconnect.flattrade.in/PiConnectAPI+// and use the jData=<JSON>&jKey=<token> form-urlencoded protocol.+//+// Credential packing:+// ApiKey = "clientid:::apikey" (client id used as uid/actid; apikey used in auth hash)+// ApiSecret = api_secret (used to build SHA256 security hash, never sent raw)+// AuthCode = request_code (one-time request code from the Flattrade auth redirect)+//+// Auth flow differs from Shoonya: a separate auth host issues the session token.+// POST https://authapi.flattrade.in/trade/apitoken+// body (JSON): {api_key, request_code, api_secret=SHA256(apikey+request_code+secret)}+// → returns {"stat":"Ok","token":"<susertoken>"}++class FlattradeBroker : public IBroker {+ public:+ BrokerId id() const override { return BrokerId::Flattrade; }+ const char* name() const override { return "Flattrade"; }+ const char* base_url() const override { return "https://piconnect.flattrade.in/PiConnectAPI"; }+ const char* ws_adapter_name() const override { return "flattrade"; }++ BrokerProfile profile() const override {+ return BrokerProfile{+ .id = "flattrade",+ .display_name = "Flattrade",+ .region = "IN",+ .currency = "INR",+ .credential_fields =+ {+ {CredentialField::ApiKey, "CLIENT:::APIKEY", "client_id:::api_key", false},+ {CredentialField::ApiSecret, "API SECRET", "Enter API Secret...", true},+ {CredentialField::AuthCode, "REQUEST CODE", "Enter request code...", false},+ },+ .exchanges = {"NSE", "BSE", "NFO", "BFO", "MCX", "CDS"},+ .product_types =+ {+ {"Intraday (MIS)", ProductType::Intraday},+ {"Delivery (CNC)", ProductType::Delivery},+ {"Margin (NRML)", ProductType::Margin},+ },+ .supports_intraday = true,+ .supports_bracket_order = false,+ .supports_cover_order = false,+ .has_native_paper = false,+ .default_paper_balance = 1000000.0,+ .default_watchlist = {"HDFCBANK", "ICICIBANK", "SBIN", "TCS", "INFY", "RELIANCE", "TATAMOTORS",+ "BAJFINANCE", "HINDUNILVR", "ITC"},+ .default_symbol = "RELIANCE",+ .default_exchange = "NSE",+ .brokerage_info = "₹10/order or 0.03%",+ };+ }++ TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) override;+ OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;+ ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) override;+ ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;+ ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;+ ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) override;+ ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) override;++ static bool is_token_expired(const BrokerHttpResponse& resp);+ static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);++ protected:+ // Flattrade uses no auth header — token is passed as jKey form field+ QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;++ private:+ static const BrokerEnumMap<QString>& ft_enum_map();+ static QString ft_status(const QString& s);++ // The Noren uid/actid is the client-id portion of the packed ApiKey (before ":::").+ static QString uid_from_creds(const BrokerCredentials& creds);++ // Build form body: jData=<json>&jKey=<token>+ static QByteArray make_body(const QJsonObject& jdata, const QString& token);+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cppindex d695d7356..859bd5ac7 100644--- a/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp+++ b/fincept-qt/src/trading/brokers/fyers/FyersBroker.cpp@@ -750,4 +750,196 @@ ApiResponse<QJsonObject> FyersBroker::place_multi_order(const BrokerCredentials&return {true, resp.json, "", ts};}+// ============================================================================+// Multi-Quote — POST /data-rest/v2/quotes/+// Body: {"symbols": "NSE:SBIN-EQ,NSE:TCS-EQ"} (comma-separated, max 50)+// Response: {s:"ok", d:[{s:"ok", n:"NSE:SBIN-EQ", v:{lp, open_price, ...}}, ...]}+// ============================================================================++ApiResponse<QVector<BrokerQuote>> FyersBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {++ static constexpr int kBatchSize = 50;+ int64_t ts = now_ts();+ QVector<BrokerQuote> all_quotes;++ for (int batch_start = 0; batch_start < symbols.size(); batch_start += kBatchSize) {+ int batch_end = qMin(batch_start + kBatchSize, symbols.size());++ // Build comma-separated Fyers symbol list and reverse map.+ // If exchange is provided and symbol lacks ':', prepend exchange so+ // to_fyers_sym sees a fully qualified "EXCH:SYMBOL" and passes it through.+ // Plain symbols without exchange default to NSE:-EQ via to_fyers_sym.+ QHash<QString, QPair<QString, QString>> fyers_to_orig;+ QStringList sym_list;+ for (int i = batch_start; i < batch_end; ++i) {+ const auto& [sym, exch] = symbols[i];+ QString input = sym;+ if (!sym.contains(':') && !exch.isEmpty()) {+ // Fyers EQ symbols use -EQ suffix; F&O already have segment in name+ input = exch + ":" + sym;+ if (!sym.contains('-'))+ input += "-EQ";+ }+ const QString fyers_sym = to_fyers_sym(input);+ sym_list.append(fyers_sym);+ fyers_to_orig.insert(fyers_sym, symbols[i]);+ }++ QJsonObject payload;+ payload["symbols"] = sym_list.join(",");++ auto resp = BrokerHttp::instance().post_json(+ QString(base_url()) + "/data-rest/v2/quotes/", payload, auth_headers(creds));++ if (!resp.success)+ return {false, std::nullopt, fyers_check_auth(resp, resp.error), ts};+ if (resp.json.value("s").toString() != "ok")+ return {false, std::nullopt, fyers_check_auth(resp, resp.json.value("message").toString("Failed")), ts};++ auto d_arr = resp.json.value("d").toArray();+ for (const auto& val : d_arr) {+ auto item = val.toObject();+ if (item.value("s").toString() != "ok")+ continue;+ auto v = item.value("v").toObject();+ BrokerQuote q;+ const QString raw_sym = v.value("symbol").toString();+ if (fyers_to_orig.contains(raw_sym)) {+ const auto& orig = fyers_to_orig.value(raw_sym);+ q.symbol = orig.first;+ } else {+ q.symbol = from_fyers_sym(raw_sym);+ }+ q.ltp = v.value("lp").toDouble();+ q.open = v.value("open_price").toDouble();+ q.high = v.value("high_price").toDouble();+ q.low = v.value("low_price").toDouble();+ q.close = v.value("prev_close_price").toDouble();+ q.volume = v.value("volume").toDouble();+ q.change = v.value("ch").toDouble();+ 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() * 1000;+ q.oi = v.value("oi").toVariant().toLongLong();+ q.oi_change_pct = v.value("oichp").toDouble();+ all_quotes.append(q);+ }+ }++ return {true, all_quotes, "", ts};+}++// ============================================================================+// Market Depth — GET /data/depth?symbol=...&ohlcv_flag=1+// Returns 5-level bid/ask depth. Reuses the same endpoint as+// get_historical_quotes_single but maps into MarketDepth struct.+// ============================================================================++ApiResponse<MarketDepth> FyersBroker::get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) {++ Q_UNUSED(exchange);+ const QString url = QString("%1/data/depth?symbol=%2&ohlcv_flag=1")+ .arg(base_url(), to_fyers_sym(symbol));+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));+ int64_t ts = now_ts();++ if (!resp.success)+ return {false, std::nullopt, fyers_check_auth(resp, resp.error), ts};+ if (resp.json.value("s").toString() != "ok")+ return {false, std::nullopt, fyers_check_auth(resp, resp.json.value("message").toString("Failed")), ts};++ // d is a map keyed by symbol: { "NSE:SBIN-EQ": { bids: [...], ask: [...], ... } }+ const auto d = resp.json.value("d").toObject();+ if (d.isEmpty())+ return {false, std::nullopt, "Empty depth response", ts};++ const auto sym_data = d.begin()->toObject();++ MarketDepth md;+ md.symbol = symbol;+ md.exchange = exchange.isEmpty() ? exchange_of(d.begin().key()) : exchange;+ md.ltp = sym_data.value("ltp").toDouble();+ md.volume = sym_data.value("volume").toDouble();+ md.oi = sym_data.value("oi").toDouble();++ const auto bids_arr = sym_data.value("bids").toArray();+ for (const auto& v : bids_arr) {+ auto lvl = v.toObject();+ DepthLevel dl;+ dl.price = lvl.value("price").toDouble();+ dl.quantity = lvl.value("volume").toInt();+ dl.orders = lvl.value("ord").toInt();+ md.bids.append(dl);+ }++ // Fyers uses "ask" (singular) for sell side+ const auto asks_arr = sym_data.value("ask").toArray();+ for (const auto& v : asks_arr) {+ auto lvl = v.toObject();+ DepthLevel dl;+ dl.price = lvl.value("price").toDouble();+ dl.quantity = lvl.value("volume").toInt();+ dl.orders = lvl.value("ord").toInt();+ md.asks.append(dl);+ }++ return {true, md, "", ts};+}++// ============================================================================+// Pre-trade margin calculator — POST /api/v3/multiorder/margin (native)+// Mirrors OpenAlgo broker/fyers/api/margin_api.py + mapping/margin_data.py.+// Payload: {"data":[{symbol, qty, side, type, productType, limitPrice,+// stopLoss, stopPrice, takeProfit}]}+// Response: {"s":"ok","data":{margin_avail, margin_total, margin_new_order}}+// Fyers returns total margin only (no SPAN/Exposure breakdown).+// ============================================================================+ApiResponse<OrderMargin> FyersBroker::get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) {+ int64_t ts = now_ts();++ QJsonObject leg{{"symbol", to_fyers_sym(order.symbol)},+ {"qty", static_cast<int>(order.quantity)},+ {"side", fyers_int_map().side_or(order.side, 1)},+ {"type", fyers_int_map().order_type_or(order.order_type, 2)},+ {"productType", fyers_str_map().product_or(order.product_type, "INTRADAY")},+ {"limitPrice", order.price},+ {"stopLoss", 0.0},+ {"stopPrice", order.stop_price},+ {"takeProfit", 0.0}};++ QJsonObject payload{{"data", QJsonArray{leg}}};++ auto resp = BrokerHttp::instance().post_json(QString(base_url()) + "/api/v3/multiorder/margin", payload,+ auth_headers(creds));+ if (!resp.success)+ return {false, std::nullopt, fyers_check_auth(resp, "Network error"), ts};+ if (resp.json.value("s").toString() != "ok")+ return {false, std::nullopt,+ fyers_check_auth(resp, resp.json.value("message").toString("Margin calculation failed")), ts};++ const auto data = resp.json.value("data").toObject();++ OrderMargin m;+ m.symbol = order.symbol;+ m.exchange = order.exchange;+ m.side = order.side == OrderSide::Buy ? "BUY" : "SELL";+ m.quantity = order.quantity;+ m.price = order.price;+ // margin_new_order = total margin including existing positions (best total estimate).+ m.total = data.value("margin_new_order").toDouble();+ if (m.total <= 0.0)+ m.total = data.value("margin_total").toDouble();+ m.cash = m.total; // no SPAN/Exposure breakdown from Fyers++ const double notional = order.price * order.quantity;+ if (m.total > 0.0 && notional > 0.0)+ m.leverage = notional / m.total;+ return {true, m, "", ts};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/fyers/FyersBroker.h b/fincept-qt/src/trading/brokers/fyers/FyersBroker.hindex 27605db8d..5afea65f3 100644--- a/fincept-qt/src/trading/brokers/fyers/FyersBroker.h+++ b/fincept-qt/src/trading/brokers/fyers/FyersBroker.h@@ -68,6 +68,15 @@ class FyersBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // --- Multi-quote & Market Depth ---+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) override;+// Market depth — GET /data/depth (5-level bid/ask)ApiResponse<QVector<BrokerQuote>> get_historical_quotes_single(const BrokerCredentials& creds,const QString& symbol, const QString& start,@@ -76,6 +85,9 @@ class FyersBroker : public IBroker {// Market clock — GET /api/v3/marketStatus.ApiResponse<MarketClock> get_clock(const BrokerCredentials& creds) override;+ // --- Margin Calculator --- POST /api/v3/multiorder/margin (native; total only, no SPAN breakdown)+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+// GTT — /api/v3/gtt/orders[/sync].GttPlaceResponse gtt_place(const BrokerCredentials& creds, const GttOrder& order) override;ApiResponse<GttOrder> gtt_get(const BrokerCredentials& creds, const QString& gtt_id) override;diff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cppindex 5b67b071d..c9a9cde91 100644--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.cpp@@ -855,6 +855,116 @@ ApiResponse<QVector<BrokerCandle>> GrowwBroker::get_history(const BrokerCredentireturn {true, result, "", ts};}+// ============================================================================+// Batch multi-quotes — get_multi_quotes+// Uses the existing batch helpers (fetch_ltp_batch + fetch_ohlc_batch) which+// call /v1/live-data/ltp and /v1/live-data/ohlc (max 50 per call per segment).+// ============================================================================++ApiResponse<QVector<BrokerQuote>> GrowwBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {+ int64_t ts = now_ts();++ if (symbols.isEmpty())+ return {false, std::nullopt, "No symbols", ts};++ // Convert QPair<symbol,exchange> to SymbolRef, using the exchange from the pair.+ // Group by segment for batching.+ QMap<QString, QVector<SymbolRef>> by_segment;+ for (const auto& [sym, exch] : symbols) {+ SymbolRef ref;+ ref.orig = sym;+ ref.exchange = exch.isEmpty() ? QStringLiteral("NSE") : exch;+ ref.trading_symbol = sym;+ // If sym has "NSE:RELIANCE" format, split it+ const int colon = sym.indexOf(':');+ if (colon != -1) {+ ref.exchange = sym.left(colon);+ ref.trading_symbol = sym.mid(colon + 1);+ } else if (!exch.isEmpty()) {+ ref.exchange = exch;+ }+ ref.segment = groww_segment(ref.exchange);+ ref.exchange_symbol = groww_exchange(ref.exchange) + "_" + ref.trading_symbol;+ by_segment[ref.segment].append(ref);+ }++ QVector<BrokerQuote> quotes;+ for (auto it = by_segment.constBegin(); it != by_segment.constEnd(); ++it) {+ if (!fetch_ltp_batch(creds, it.key(), it.value(), quotes))+ continue; // best-effort — partial batch still returns what succeeded+ fetch_ohlc_batch(creds, it.key(), it.value(), quotes);+ }++ return {true, quotes, "", ts};+}++// ============================================================================+// Market depth — GET /v1/live-data/quote includes bid/ask depth+// The /quote endpoint returns: payload.depth.buy[] and payload.depth.sell[]+// Each level: { price, quantity, orders }+// ============================================================================++ApiResponse<MarketDepth> GrowwBroker::get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) {+ int64_t ts = now_ts();+ auto hdrs = auth_headers(creds);++ QString exch = exchange.isEmpty() ? QStringLiteral("NSE") : exchange;+ QString trading_symbol = symbol;+ const int colon = symbol.indexOf(':');+ if (colon != -1) {+ exch = symbol.left(colon);+ trading_symbol = symbol.mid(colon + 1);+ }++ QString url = QString("https://api.groww.in/v1/live-data/quote"+ "?exchange=%1&segment=%2&trading_symbol=%3")+ .arg(groww_exchange(exch), groww_segment(exch), trading_symbol);+ auto resp = BrokerHttp::instance().get(url, hdrs);++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};++ QJsonObject payload = resp.json["payload"].toObject();++ MarketDepth depth;+ depth.symbol = symbol;+ depth.exchange = exch;+ depth.ltp = payload["last_price"].toDouble();+ depth.volume = payload["volume"].toDouble();+ depth.oi = payload["oi"].toDouble();++ // Parse depth levels — Groww returns { depth: { buy: [...], sell: [...] } }+ QJsonObject depth_obj = payload["depth"].toObject();+ QJsonArray buy_levels = depth_obj["buy"].toArray();+ QJsonArray sell_levels = depth_obj["sell"].toArray();++ for (const auto& v : buy_levels) {+ QJsonObject lvl = v.toObject();+ DepthLevel dl;+ dl.price = lvl["price"].toDouble();+ dl.quantity = lvl["quantity"].toInt();+ dl.orders = lvl["orders"].toInt();+ depth.bids.append(dl);+ }++ for (const auto& v : sell_levels) {+ QJsonObject lvl = v.toObject();+ DepthLevel dl;+ dl.price = lvl["price"].toDouble();+ dl.quantity = lvl["quantity"].toInt();+ dl.orders = lvl["orders"].toInt();+ depth.asks.append(dl);+ }++ return {true, depth, "", ts};+}+// ============================================================================// Pre-trade margin calculator — POST /v1/margins/detail/orders?segment=...// ============================================================================diff --git a/fincept-qt/src/trading/brokers/groww/GrowwBroker.h b/fincept-qt/src/trading/brokers/groww/GrowwBroker.hindex 76cc421b8..68dd1bad4 100644--- a/fincept-qt/src/trading/brokers/groww/GrowwBroker.h+++ b/fincept-qt/src/trading/brokers/groww/GrowwBroker.h@@ -64,6 +64,16 @@ class GrowwBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // Batch multi-quotes — uses /v1/live-data/ltp + /v1/live-data/ohlc (max 50 per call)+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ // Market depth — GET /v1/live-data/quote includes bid/ask depth for single symbol+ ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) override;+// Pre-trade margin calculator — POST /v1/margins/detail/orders?segment=...ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;ApiResponse<BasketMargin> get_basket_margins(const BrokerCredentials& creds,diff --git a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cppindex 415276d55..9407a291d 100644--- a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp+++ b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.cpp@@ -667,4 +667,14 @@ ApiResponse<QVector<BrokerCandle>> IIFLBroker::get_history(const BrokerCredentiareturn {true, candles, "", ts};}+// ============================================================================+// Pre-trade margin calculator — fallback estimator.+// IIFL (XTS) has no margin calculator API (OpenAlgo's broker/iifl/api/margin_api.py+// raises NotImplementedError), so we use the shared heuristic estimator+// (BrokerInterface.h::estimate_order_margin).+// ============================================================================+ApiResponse<OrderMargin> IIFLBroker::get_order_margins(const BrokerCredentials& /*creds*/, const UnifiedOrder& order) {+ return {true, estimate_order_margin(order), "", now_ts()};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.h b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.hindex d668d239d..57647a319 100644--- a/fincept-qt/src/trading/brokers/iifl/IIFLBroker.h+++ b/fincept-qt/src/trading/brokers/iifl/IIFLBroker.h@@ -15,6 +15,7 @@ class IIFLBroker : public IBroker {BrokerId id() const override { return BrokerId::IIFL; }const char* name() const override { return "IIFL"; }const char* base_url() const override { return "https://ttblaze.iifl.com/interactive"; }+ const char* ws_adapter_name() const override { return "iifl"; }BrokerProfile profile() const override {return BrokerProfile{@@ -67,6 +68,9 @@ class IIFLBroker : public IBroker {static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);+ // --- Margin Calculator --- IIFL (XTS) has no margin calculator API → fallback estimator.+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+protected:QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;diff --git a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cppindex 98329a9ed..7e6de00b5 100644--- a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp+++ b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp@@ -745,4 +745,63 @@ ApiResponse<QVector<BrokerCandle>> KotakBroker::get_history(const BrokerCredentireturn {true, QVector<BrokerCandle>{}, "", ts};}+// ============================================================================+// Pre-trade margin calculator — POST {base_url}/quick/user/check-margin (native)+// Mirrors OpenAlgo broker/kotak/api/margin_api.py + mapping/margin_data.py.+// Body: jData=<url-encoded JSON>, single position object with Kotak short keys:+// {brkName:"KOTAK", brnchId:"ONLINE", exSeg, prc, prcTp, prod, qty, tok, trnsTp}+// Response: {stat:"Ok", reqdMrgn, avlMrgn, ordMrgn, ...}+// Kotak returns total required margin only (no SPAN/Exposure breakdown).+// ============================================================================+ApiResponse<OrderMargin> KotakBroker::get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) {+ int64_t ts = now_ts();+ auto p = unpack(creds.access_token);+ if (!p.valid)+ return {false, std::nullopt, "[TOKEN_EXPIRED] Invalid or missing session token", ts};++ const QString tok = lookup_psymbol(order.symbol, order.exchange, creds.broker_id);+ if (tok.isEmpty())+ return {false, std::nullopt, "Token not found for " + order.exchange + ":" + order.symbol, ts};++ QJsonObject jobj;+ jobj["brkName"] = "KOTAK";+ jobj["brnchId"] = "ONLINE";+ jobj["exSeg"] = kotak_exchange(order.exchange);+ jobj["prc"] = QString::number(order.price, 'f', 2);+ jobj["prcTp"] = kotak_enum_map().order_type_or(order.order_type, "MKT");+ jobj["prod"] = kotak_enum_map().product_or(order.product_type, "MIS");+ jobj["qty"] = QString::number(static_cast<int>(order.quantity));+ jobj["tok"] = tok;+ jobj["trnsTp"] = order.side == OrderSide::Buy ? "B" : "S";++ // check-margin uses the v1-era jData=<url-encoded JSON> form wrapper.+ const QByteArray json = QJsonDocument(jobj).toJson(QJsonDocument::Compact);+ QMap<QString, QString> form{{"jData", QString::fromUtf8(json)}};++ auto hdrs = auth_headers(creds);+ auto resp = BrokerHttp::instance().post_form(with_sid("/quick/user/check-margin", p), form, hdrs);++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json.value("stat").toString() != "Ok")+ return {false, std::nullopt, checked_error(resp, "Margin calculation failed"), ts};++ const auto& j = resp.json;+ OrderMargin m;+ m.symbol = order.symbol;+ m.exchange = order.exchange;+ m.side = order.side == OrderSide::Buy ? "BUY" : "SELL";+ m.quantity = order.quantity;+ m.price = order.price;+ // Kotak returns string-or-number fields; toVariant().toDouble() handles both.+ m.total = j.value("reqdMrgn").toVariant().toDouble();+ m.cash = j.value("avlMrgn").toVariant().toDouble();+ const double notional = order.price * order.quantity;+ if (m.total > 0.0 && notional > 0.0)+ m.leverage = notional / m.total;+ return {true, m, "", ts};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/kotak/KotakBroker.h b/fincept-qt/src/trading/brokers/kotak/KotakBroker.hindex f8c9a14d0..b6e7fca5b 100644--- a/fincept-qt/src/trading/brokers/kotak/KotakBroker.h+++ b/fincept-qt/src/trading/brokers/kotak/KotakBroker.h@@ -10,6 +10,7 @@ class KotakBroker : public IBroker {BrokerId id() const override { return BrokerId::Kotak; }const char* name() const override { return "Kotak"; }const char* base_url() const override { return "https://mis.kotaksecurities.com"; }+ const char* ws_adapter_name() const override { return "kotak"; }BrokerProfile profile() const override {return BrokerProfile{@@ -61,6 +62,9 @@ class KotakBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // --- Margin Calculator --- POST {base_url}/quick/user/check-margin (native, single order)+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cppindex 2b9204f17..5cbb4334d 100644--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp@@ -673,4 +673,15 @@ ApiResponse<QJsonObject> MotilalBroker::get_master_contract(const BrokerCredentireturn {true, out, "", ts};}+// ============================================================================+// Pre-trade margin calculator — fallback estimator.+// Motilal Oswal has no margin calculator API (OpenAlgo's+// broker/motilal/api/margin_api.py raises NotImplementedError), so we use the+// shared heuristic estimator (BrokerInterface.h::estimate_order_margin).+// ============================================================================+ApiResponse<OrderMargin> MotilalBroker::get_order_margins(const BrokerCredentials& /*creds*/,+ const UnifiedOrder& order) {+ return {true, estimate_order_margin(order), "", now_ts()};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.h b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.hindex 592556dc6..b47a64610 100644--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.h+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.h@@ -15,6 +15,7 @@ class MotilalBroker : public IBroker {BrokerId id() const override { return BrokerId::Motilal; }const char* name() const override { return "Motilal"; }const char* base_url() const override { return "https://openapi.motilaloswal.com"; }+ const char* ws_adapter_name() const override { return "motilal"; }BrokerProfile profile() const override {return BrokerProfile{@@ -72,6 +73,9 @@ class MotilalBroker : public IBroker {// calls this to seed symbol→scripcode lookups. Result.data["csv"] is the raw body.ApiResponse<QJsonObject> get_master_contract(const BrokerCredentials& creds, const QString& exchange);+ // --- Margin Calculator --- Motilal Oswal has no margin calculator API → fallback estimator.+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+protected:QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;diff --git a/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cppnew file mode 100644index 000000000..7dd5df333--- /dev/null+++ b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp@@ -0,0 +1,553 @@+#include "trading/brokers/paytm/PaytmBroker.h"++#include "trading/brokers/BrokerHttp.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QUrl>++namespace fincept::trading {++static constexpr const char* BASE = "https://developer.paytmmoney.com";++static int64_t now_ts() {+ return QDateTime::currentSecsSinceEpoch();+}++// Pick the first present key from an object (handles Paytm's snake_case vs+// camelCase field aliasing) and return it as a QJsonValue.+static QJsonValue pm_first(const QJsonObject& o, const QString& a, const QString& b) {+ return o.contains(a) ? o.value(a) : o.value(b);+}++// ---------- Static helpers ----------++const BrokerEnumMap<QString>& PaytmBroker::pm_enum_map() {+ static const auto m = [] {+ BrokerEnumMap<QString> x;+ x.set(OrderType::Market, "MKT");+ x.set(OrderType::Limit, "LMT");+ x.set(OrderType::StopLoss, "SLM");+ x.set(OrderType::StopLossLimit, "SL");+ // Paytm product codes: C(NC), M(argin), I(ntraday)+ x.set(ProductType::Intraday, "I");+ x.set(ProductType::Delivery, "C");+ x.set(ProductType::Margin, "M");+ return x;+ }();+ return m;+}++QString PaytmBroker::pm_status(const QString& s) {+ QString sl = s.toLower();+ if (sl == "success" || sl == "successfull" || sl == "complete" || sl == "completed" || sl == "executed" ||+ sl == "traded")+ return "filled";+ if (sl == "open" || sl == "pending" || sl == "trigger pending" || sl == "modified")+ return "open";+ if (sl == "cancelled" || sl == "canceled")+ return "cancelled";+ if (sl == "rejected" || sl == "failure")+ return "rejected";+ return "open";+}++bool PaytmBroker::is_token_expired(const BrokerHttpResponse& resp) {+ if (resp.status_code == 401 || resp.status_code == 403)+ return true;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return false;+ QString msg = doc.object().value("message").toString().toLower();+ return msg.contains("unauthorized") || msg.contains("invalid token") || msg.contains("session") ||+ msg.contains("expired") || msg.contains("jwt");+}++QString PaytmBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {+ if (is_token_expired(resp))+ return "[TOKEN_EXPIRED] Session expired, please re-login";+ if (!resp.success && resp.status_code == 0)+ return resp.error.isEmpty() ? fallback : resp.error;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject()) {+ QJsonObject obj = doc.object();+ QString msg = obj.value("message").toString();+ if (msg.isEmpty()) {+ // Paytm error array: {"errors":[{"message":"..."}]}+ QJsonArray errs = obj.value("errors").toArray();+ if (!errs.isEmpty())+ msg = errs[0].toObject().value("message").toString();+ }+ if (!msg.isEmpty())+ return msg;+ }+ return fallback;+}++// ---------- Auth headers ----------++QMap<QString, QString> PaytmBroker::auth_headers(const BrokerCredentials& creds) const {+ return {{"x-jwt-token", creds.access_token},+ {"Content-Type", "application/json"},+ {"Accept", "application/json"}};+}++// ---------- exchange_token ----------+// ApiKey=api_key, ApiSecret=api_secret, AuthCode=request_token+// POST /accounts/v2/gettoken {api_key, api_secret_key, request_token}+// → {access_token, public_access_token}++TokenExchangeResponse PaytmBroker::exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) {+ if (api_key.isEmpty() || api_secret.isEmpty() || auth_code.isEmpty())+ return {false, "", "", "", "Paytm login: api_key, api_secret and request_token are required", ""};++ QJsonObject payload;+ payload["api_key"] = api_key;+ payload["api_secret_key"] = api_secret;+ payload["request_token"] = auth_code.trimmed();++ auto& http = BrokerHttp::instance();+ auto resp = http.post_json(QString("%1/accounts/v2/gettoken").arg(BASE), payload,+ {{"Content-Type", "application/json"}});++ if (!resp.success && resp.status_code == 0)+ return {false, "", "", "", "Login failed: " + resp.error, ""};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "", "", "Login: invalid response", ""};++ QJsonObject obj = doc.object();+ QString access_token = obj.value("access_token").toString();+ if (access_token.isEmpty())+ return {false, "", "", "", checked_error(resp, "Login failed: no access token"), ""};++ // public_access_token is the WebSocket feed token — stash it in additional_data.+ QString feed_token = obj.value("public_access_token").toString(access_token);+ return {true, access_token, "", "", feed_token, ""};+}++// ---------- place_order ----------+// POST /orders/v1/place/regular (JSON, x-jwt-token)++OrderPlaceResponse PaytmBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {+ // Paytm needs the numeric security_id; the instrument token rides in+ // UnifiedOrder::instrument_token when known, else fall back to symbol.+ const QString security_id = order.instrument_token.isEmpty() ? order.symbol : order.instrument_token;+ const QString segment = (order.exchange == "NSE" || order.exchange == "BSE") ? "E" : "D";+ QString api_exchange = order.exchange;+ if (api_exchange == "NFO")+ api_exchange = "NSE";+ else if (api_exchange == "BFO")+ api_exchange = "BSE";++ QJsonObject payload;+ payload["security_id"] = security_id;+ payload["exchange"] = api_exchange;+ payload["txn_type"] = (order.side == OrderSide::Buy) ? "B" : "S";+ payload["order_type"] = pm_enum_map().order_type_or(order.order_type, "MKT");+ payload["quantity"] = QString::number(static_cast<int>(order.quantity));+ payload["product"] = pm_enum_map().product_or(order.product_type, "I");+ payload["price"] = QString::number(order.price, 'f', 2);+ payload["trigger_price"] = QString::number(order.stop_price, 'f', 2);+ payload["validity"] = "DAY";+ payload["segment"] = segment;+ payload["source"] = "N"; // Android source code; OpenAlgo uses W/M/N/I/R/O+ payload["off_mkt_flag"] = order.amo ? "Y" : "N";++ auto& http = BrokerHttp::instance();+ auto resp = http.post_json(QString("%1/orders/v1/place/regular").arg(BASE), payload, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, "", checked_error(resp, "place_order failed")};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "place_order: invalid response"};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "success")+ return {false, "", checked_error(resp, "place_order failed")};++ QJsonArray data = obj.value("data").toArray();+ QString order_id = data.isEmpty() ? "" : data[0].toObject().value("order_no").toVariant().toString();+ if (order_id.isEmpty())+ return {false, "", "place_order: no order_no in response"};+ return {true, order_id, ""};+}++// ---------- find_order: look up a full order record by id from the order book ----------+// Paytm modify/cancel require serial_no, group_id, and the original order fields.++QJsonObject PaytmBroker::find_order(const BrokerCredentials& creds, const QString& order_id) {+ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/orders/v1/user/orders").arg(BASE), auth_headers(creds));+ if (!resp.success && resp.status_code == 0)+ return {};+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {};+ for (const QJsonValue& v : doc.object().value("data").toArray()) {+ QJsonObject o = v.toObject();+ if (o.value("order_no").toVariant().toString() == order_id)+ return o;+ }+ return {};+}++// ---------- modify_order ----------+// POST /orders/v1/modify/regular — must echo serial_no + group_id from the order book++ApiResponse<QJsonObject> PaytmBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) {+ int64_t ts = now_ts();++ QJsonObject src = find_order(creds, order_id);+ if (src.isEmpty())+ return {false, std::nullopt, "modify_order: order not found in order book", ts};++ const QString price_type = mods.value("orderType").toString();+ QJsonObject payload;+ payload["order_no"] = order_id;+ payload["exchange"] = src.value("exchange");+ payload["segment"] = src.value("segment");+ payload["security_id"] = src.value("security_id");+ payload["quantity"] = mods.contains("quantity") ? QString::number(mods.value("quantity").toInt())+ : src.value("quantity").toVariant().toString();+ payload["price"] = mods.contains("price") ? QString::number(mods.value("price").toDouble(), 'f', 2)+ : src.value("price").toVariant().toString();+ payload["trigger_price"] = mods.contains("triggerPrice")+ ? QString::number(mods.value("triggerPrice").toDouble(), 'f', 2)+ : src.value("trigger_price").toVariant().toString();+ payload["validity"] = "DAY";+ payload["product"] = src.value("product");+ payload["order_type"] = price_type.isEmpty() ? src.value("order_type").toVariant().toString() : price_type;+ payload["txn_type"] = src.value("txn_type");+ payload["source"] = "N";+ payload["off_mkt_flag"] = src.value("off_mkt_flag").toVariant().toString().isEmpty()+ ? "N"+ : src.value("off_mkt_flag").toVariant().toString();+ payload["serial_no"] = src.value("serial_no");+ payload["group_id"] = src.value("group_id");++ auto& http = BrokerHttp::instance();+ auto resp = http.post_json(QString("%1/orders/v1/modify/regular").arg(BASE), payload, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "modify_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "success")+ return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};++ return {true, obj, "", ts};+}++// ---------- cancel_order ----------+// POST /orders/v1/cancel/regular — must echo the full order record fields++ApiResponse<QJsonObject> PaytmBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {+ int64_t ts = now_ts();++ QJsonObject src = find_order(creds, order_id);+ if (src.isEmpty())+ return {false, std::nullopt, "cancel_order: order not found in order book", ts};++ QJsonObject payload;+ payload["order_no"] = order_id;+ payload["source"] = "N";+ payload["txn_type"] = src.value("txn_type");+ payload["exchange"] = src.value("exchange");+ payload["segment"] = src.value("segment");+ payload["product"] = src.value("product");+ payload["security_id"] = src.value("security_id");+ payload["quantity"] = src.value("quantity");+ payload["validity"] = src.value("validity");+ payload["order_type"] = src.value("order_type");+ payload["price"] = src.value("price");+ payload["off_mkt_flag"] = src.value("off_mkt_flag");+ payload["mkt_type"] = src.value("mkt_type");+ payload["serial_no"] = src.value("serial_no");+ payload["group_id"] = src.value("group_id");++ auto& http = BrokerHttp::instance();+ auto resp = http.post_json(QString("%1/orders/v1/cancel/regular").arg(BASE), payload, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "cancel_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "success")+ return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};++ return {true, obj, "", ts};+}++// ---------- get_orders ----------+// GET /orders/v1/user/orders++ApiResponse<QVector<BrokerOrderInfo>> PaytmBroker::get_orders(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/orders/v1/user/orders").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_orders: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "success") {+ // No orders is a non-error empty state for Paytm.+ if (obj.value("data").toArray().isEmpty())+ return {true, QVector<BrokerOrderInfo>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};+ }++ QVector<BrokerOrderInfo> orders;+ for (const QJsonValue& v : obj.value("data").toArray()) {+ QJsonObject o = v.toObject();+ BrokerOrderInfo info;+ info.order_id = o.value("order_no").toVariant().toString();+ info.symbol = o.value("display_name").toString(o.value("security_id").toVariant().toString());+ info.exchange = o.value("exchange").toString();+ info.quantity = o.value("quantity").toVariant().toInt();+ info.filled_qty = o.value("traded_qty").toVariant().toInt();+ info.price = o.value("price").toVariant().toDouble();+ info.stop_price = o.value("trigger_price").toVariant().toDouble();+ info.avg_price = o.value("avg_traded_price").toVariant().toDouble();+ info.status = pm_status(o.value("status").toString());+ info.side = (o.value("txn_type").toString() == "B") ? "buy" : "sell";+ info.order_type = o.value("order_type").toString();+ info.product_type = o.value("product").toString();+ info.timestamp = o.value("order_date_time").toString();+ orders.append(info);+ }++ return {true, orders, "", ts};+}++// ---------- get_trade_book ----------+// Paytm exposes orders only (per-order trade detail needs an order id); return+// the order list as the trade book wrapper.++ApiResponse<QJsonObject> PaytmBroker::get_trade_book(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/orders/v1/user/orders").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_trade_book failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject())+ return {true, doc.object(), "", ts};+ return {false, std::nullopt, "get_trade_book: invalid response", ts};+}++// ---------- get_positions ----------+// GET /orders/v1/position++ApiResponse<QVector<BrokerPosition>> PaytmBroker::get_positions(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/orders/v1/position").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_positions: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "success") {+ if (obj.value("data").toArray().isEmpty())+ return {true, QVector<BrokerPosition>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};+ }++ QVector<BrokerPosition> positions;+ for (const QJsonValue& v : obj.value("data").toArray()) {+ QJsonObject o = v.toObject();+ int net_qty = pm_first(o, "net_qty", "netQty").toVariant().toInt();+ if (net_qty == 0)+ continue;+ BrokerPosition pos;+ pos.symbol = o.value("display_name").toString(o.value("security_id").toVariant().toString());+ pos.exchange = o.value("exchange").toString();+ QString product = o.value("product").toString();+ pos.product_type = (product == "C") ? "CNC" : (product == "I" ? "MIS" : "NRML");+ pos.quantity = net_qty;+ pos.avg_price = pm_first(o, "buy_avg", "cost_price").toVariant().toDouble();+ pos.ltp = pm_first(o, "last_traded_price", "ltp").toVariant().toDouble();+ pos.pnl = o.value("realised_profit").toVariant().toDouble() + o.value("unrealised_profit").toVariant().toDouble();+ pos.side = net_qty > 0 ? "LONG" : "SHORT";+ positions.append(pos);+ }++ return {true, positions, "", ts};+}++// ---------- get_holdings ----------+// GET /holdings/v1/get-user-holdings-data++ApiResponse<QVector<BrokerHolding>> PaytmBroker::get_holdings(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/holdings/v1/get-user-holdings-data").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_holdings: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "success") {+ if (obj.value("data").toObject().value("results").toArray().isEmpty())+ return {true, QVector<BrokerHolding>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};+ }++ QVector<BrokerHolding> holdings;+ for (const QJsonValue& v : obj.value("data").toObject().value("results").toArray()) {+ QJsonObject o = v.toObject();+ BrokerHolding h;+ h.symbol = o.value("display_name").toString(o.value("nse_symbol").toString(o.value("bse_symbol").toString()));+ h.exchange = o.value("exchange").toString("NSE");+ h.quantity = o.value("quantity").toVariant().toDouble();+ h.avg_price = o.value("cost_price").toVariant().toDouble();+ h.ltp = pm_first(o, "last_traded_price", "ltp").toVariant().toDouble();+ h.invested_value = h.quantity * h.avg_price;+ h.current_value = h.quantity * h.ltp;+ h.pnl = (h.ltp - h.avg_price) * h.quantity;+ if (h.avg_price > 0)+ h.pnl_pct = ((h.ltp - h.avg_price) / h.avg_price) * 100.0;+ holdings.append(h);+ }++ return {true, holdings, "", ts};+}++// ---------- get_funds ----------+// GET /accounts/v1/funds/summary?config=true++ApiResponse<BrokerFunds> PaytmBroker::get_funds(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/accounts/v1/funds/summary?config=true").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_funds: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() == "error")+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonObject summary = obj.value("data").toObject().value("funds_summary").toObject();+ BrokerFunds funds;+ funds.available_balance = summary.value("available_cash").toVariant().toDouble();+ funds.used_margin = summary.value("utilised_amount").toVariant().toDouble();+ funds.collateral = summary.value("collaterals").toVariant().toDouble();+ funds.total_balance = funds.available_balance + funds.used_margin;+ funds.raw_data = summary;++ return {true, funds, "", ts};+}++// ---------- get_quotes ----------+// GET /data/v1/price/live?mode=FULL&pref=<EXCHANGE:TOKEN:SEGMENT>+// Symbol format: "EXCHANGE:TOKEN[:SEGMENT]"; SEGMENT defaults to EQUITY.++ApiResponse<QVector<BrokerQuote>> PaytmBroker::get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) {+ int64_t ts = now_ts();+ if (symbols.isEmpty())+ return {true, QVector<BrokerQuote>{}, "", ts};++ auto& http = BrokerHttp::instance();+ QVector<BrokerQuote> quotes;+ QStringList prefs;++ for (const QString& sym : symbols) {+ QStringList parts = sym.split(":");+ if (parts.size() < 2)+ continue; // Paytm requires exchange + numeric token+ QString exchange = parts[0];+ QString token = parts[1];+ QString segment = (parts.size() >= 3) ? parts[2] : "EQUITY";+ prefs.append(QString("%1:%2:%3").arg(exchange, token, segment));+ }+ if (prefs.isEmpty())+ return {false, std::nullopt,+ "Paytm quotes require EXCHANGE:TOKEN format (numeric security_id)", ts};++ QString pref_param = QUrl::toPercentEncoding(prefs.join(",")); // batch in one request+ QString url = QString("%1/data/v1/price/live?mode=FULL&pref=%2").arg(BASE, pref_param);+ auto resp = http.get(url, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_quotes failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_quotes: invalid response", ts};++ for (const QJsonValue& v : doc.object().value("data").toArray()) {+ QJsonObject o = v.toObject();+ QJsonObject ohlc = o.value("ohlc").toObject();+ BrokerQuote bq;+ bq.symbol = o.value("security_id").toVariant().toString();+ bq.ltp = o.value("last_price").toVariant().toDouble();+ bq.open = ohlc.value("open").toVariant().toDouble();+ bq.high = ohlc.value("high").toVariant().toDouble();+ bq.low = ohlc.value("low").toVariant().toDouble();+ bq.close = ohlc.value("close").toVariant().toDouble();+ bq.volume = o.value("volume_traded").toVariant().toDouble();+ bq.oi = static_cast<qint64>(o.value("oi").toVariant().toLongLong());+ if (bq.close > 0) {+ bq.change = bq.ltp - bq.close;+ bq.change_pct = (bq.ltp - bq.close) / bq.close * 100.0;+ }+ bq.timestamp = ts;+ quotes.append(bq);+ }++ return {true, quotes, "", ts};+}++// ---------- get_history ----------+// Paytm Money does not expose a historical-data API. Return an empty result so+// downstream consumers (charts, IV/straddle tooling) render a graceful no-data+// state rather than erroring. Mirrors OpenAlgo's Paytm BrokerData.get_history.++ApiResponse<QVector<BrokerCandle>> PaytmBroker::get_history(const BrokerCredentials& /*creds*/,+ const QString& /*symbol*/, const QString& /*resolution*/,+ const QString& /*from_date*/, const QString& /*to_date*/) {+ return {true, QVector<BrokerCandle>{}, "Paytm Money does not provide a historical data API", now_ts()};+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/paytm/PaytmBroker.h b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.hnew file mode 100644index 000000000..56f3f8f8a--- /dev/null+++ b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.h@@ -0,0 +1,93 @@+#pragma once+#include "trading/BrokerInterface.h"+#include "trading/adapter/BrokerEnumMap.h"+#include "trading/brokers/BrokerHttp.h"++namespace fincept::trading {++// Paytm Money — OAuth2 REST broker on https://developer.paytmmoney.com.+// Authenticated calls carry the JWT in the x-jwt-token header.+//+// Credential packing:+// ApiKey = api_key+// ApiSecret = api_secret+// AuthCode = request_token (from the merchant-login redirect URL)+//+// Auth flow:+// POST /accounts/v2/gettoken {api_key, api_secret_key, request_token}+// → {access_token, public_access_token, read_access_token}+// access_token is persisted; public_access_token (feed token) is stored in+// additional_data for the WebSocket adapter.+//+// Order/quote APIs key off the numeric security_id (instrument token). Symbols+// for quotes/history must therefore be passed as "EXCHANGE:TOKEN[:SEGMENT]".++class PaytmBroker : public IBroker {+ public:+ BrokerId id() const override { return BrokerId::Paytm; }+ const char* name() const override { return "Paytm Money"; }+ const char* base_url() const override { return "https://developer.paytmmoney.com"; }+ const char* ws_adapter_name() const override { return "paytm"; }++ BrokerProfile profile() const override {+ return BrokerProfile{+ .id = "paytm",+ .display_name = "Paytm Money",+ .region = "IN",+ .currency = "INR",+ .credential_fields =+ {+ {CredentialField::ApiKey, "API KEY", "Enter API Key...", false},+ {CredentialField::ApiSecret, "API SECRET", "Enter API Secret...", true},+ {CredentialField::AuthCode, "REQUEST TOKEN", "Enter request token...", false},+ },+ .exchanges = {"NSE", "BSE", "NFO", "BFO"},+ .product_types =+ {+ {"Intraday (MIS)", ProductType::Intraday},+ {"Delivery (CNC)", ProductType::Delivery},+ {"Margin (NRML)", ProductType::Margin},+ },+ .supports_intraday = true,+ .supports_bracket_order = false,+ .supports_cover_order = false,+ .has_native_paper = false,+ .default_paper_balance = 1000000.0,+ .default_watchlist = {"HDFCBANK", "ICICIBANK", "SBIN", "TCS", "INFY", "RELIANCE", "TATAMOTORS",+ "BAJFINANCE", "HINDUNILVR", "ITC"},+ .default_symbol = "RELIANCE",+ .default_exchange = "NSE",+ .brokerage_info = "₹10/order intraday & F&O, 0% delivery",+ };+ }++ TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) override;+ OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;+ ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) override;+ ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;+ ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;+ ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) override;+ ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) override;++ static bool is_token_expired(const BrokerHttpResponse& resp);+ static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);++ protected:+ QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;++ private:+ static const BrokerEnumMap<QString>& pm_enum_map();+ static QString pm_status(const QString& s);+ QJsonObject find_order(const BrokerCredentials& creds, const QString& order_id);+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp b/fincept-qt/src/trading/brokers/samco/SamcoBroker.cppnew file mode 100644index 000000000..4123910f2--- /dev/null+++ b/fincept-qt/src/trading/brokers/samco/SamcoBroker.cpp@@ -0,0 +1,585 @@+#include "trading/brokers/samco/SamcoBroker.h"++#include "trading/brokers/BrokerHttp.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QUrlQuery>++namespace fincept::trading {++static constexpr const char* BASE = "https://tradeapi.samco.in";++static int64_t now_ts() {+ return QDateTime::currentSecsSinceEpoch();+}++static double samco_d(const QJsonValue& v) {+ if (v.isString())+ return v.toString().remove(',').toDouble();+ return v.toDouble();+}+static qint64 samco_i(const QJsonValue& v) {+ if (v.isString())+ return static_cast<qint64>(v.toString().remove(',').toDouble());+ return static_cast<qint64>(v.toDouble());+}+// Pick the first present key from an object (Samco aliases some fields).+static QJsonValue samco_first(const QJsonObject& o, const QString& a, const QString& b) {+ return o.contains(a) ? o.value(a) : o.value(b);+}++// ---------- Static helpers ----------++const BrokerEnumMap<QString>& SamcoBroker::sm_enum_map() {+ static const auto m = [] {+ BrokerEnumMap<QString> x;+ x.set(OrderType::Market, "MKT");+ x.set(OrderType::Limit, "L");+ x.set(OrderType::StopLoss, "SL-M");+ x.set(OrderType::StopLossLimit, "SL");+ x.set(ProductType::Intraday, "MIS");+ x.set(ProductType::Delivery, "CNC");+ x.set(ProductType::Margin, "NRML");+ return x;+ }();+ return m;+}++QString SamcoBroker::sm_status(const QString& s) {+ QString sl = s.toLower();+ if (sl == "complete" || sl == "completed" || sl == "executed" || sl == "filled")+ return "filled";+ if (sl == "open" || sl == "pending" || sl == "ordered" || sl == "trigger pending" ||+ sl == "after market order req received")+ return "open";+ if (sl == "cancelled" || sl == "canceled")+ return "cancelled";+ if (sl == "rejected")+ return "rejected";+ return "open";+}++bool SamcoBroker::is_token_expired(const BrokerHttpResponse& resp) {+ if (resp.status_code == 401 || resp.status_code == 403)+ return true;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return false;+ QJsonObject obj = doc.object();+ if (obj.value("status").toString() == "Success")+ return false;+ QString msg = obj.value("statusMessage").toString().toLower();+ return msg.contains("session") || msg.contains("token") || msg.contains("invalid") || msg.contains("expired") ||+ msg.contains("login");+}++QString SamcoBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {+ if (is_token_expired(resp))+ return "[TOKEN_EXPIRED] Session expired, please re-login";+ if (!resp.success && resp.status_code == 0)+ return resp.error.isEmpty() ? fallback : resp.error;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject()) {+ QString msg = doc.object().value("statusMessage").toString();+ if (!msg.isEmpty())+ return msg;+ }+ return fallback;+}++// ---------- Auth headers ----------++QMap<QString, QString> SamcoBroker::auth_headers(const BrokerCredentials& creds) const {+ return {{"x-session-token", creds.access_token}, {"Accept", "application/json"}};+}++// ---------- exchange_token ----------+// ApiKey=uid, ApiSecret=password, AuthCode=secret_api_key+// POST /accessToken/token {uid, secretApiKey} → accessToken+// POST /login {userId, password, accessToken} → sessionToken++TokenExchangeResponse SamcoBroker::exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) {+ if (api_key.isEmpty() || api_secret.isEmpty() || auth_code.isEmpty())+ return {false, "", "", "", "Samco login: user id, password and secret API key are required", ""};++ auto& http = BrokerHttp::instance();++ // Step 1: access token from the permanent secret API key.+ QJsonObject tok_payload;+ tok_payload["uid"] = api_key;+ tok_payload["secretApiKey"] = auth_code;+ auto tok_resp = http.post_json(QString("%1/accessToken/token").arg(BASE), tok_payload,+ {{"Content-Type", "application/json"}, {"Accept", "application/json"}});+ if (!tok_resp.success && tok_resp.status_code == 0)+ return {false, "", "", "", "Access token request failed: " + tok_resp.error, ""};++ QJsonDocument tok_doc = QJsonDocument::fromJson(tok_resp.raw_body.toUtf8());+ if (!tok_doc.isObject())+ return {false, "", "", "", "Access token: invalid response", ""};+ QJsonObject tok_obj = tok_doc.object();+ if (tok_obj.value("status").toString() != "Success")+ return {false, "", "", "", tok_obj.value("statusMessage").toString("Access token generation failed"), ""};+ QString access_token = tok_obj.value("accessToken").toString();+ if (access_token.isEmpty())+ return {false, "", "", "", "Access token: empty token in response", ""};++ // Step 2: login → sessionToken.+ QJsonObject login_payload;+ login_payload["userId"] = api_key;+ login_payload["password"] = api_secret;+ login_payload["accessToken"] = access_token;+ auto login_resp = http.post_json(QString("%1/login").arg(BASE), login_payload,+ {{"Content-Type", "application/json"}, {"Accept", "application/json"}});+ if (!login_resp.success && login_resp.status_code == 0)+ return {false, "", "", "", "Login failed: " + login_resp.error, ""};++ QJsonDocument login_doc = QJsonDocument::fromJson(login_resp.raw_body.toUtf8());+ if (!login_doc.isObject())+ return {false, "", "", "", "Login: invalid response", ""};+ QJsonObject login_obj = login_doc.object();+ if (login_obj.value("status").toString() != "Success")+ return {false, "", "", "", login_obj.value("statusMessage").toString("Login failed"), ""};+ QString session = login_obj.value("sessionToken").toString();+ if (session.isEmpty())+ return {false, "", "", "", "Login: no sessionToken in response", ""};++ return {true, session, "", api_key, "", ""};+}++// ---------- place_order ----------+// POST /order/placeOrder (JSON, x-session-token)++OrderPlaceResponse SamcoBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {+ const QString order_type = sm_enum_map().order_type_or(order.order_type, "MKT");++ QJsonObject payload;+ payload["symbolName"] = order.symbol;+ payload["exchange"] = order.exchange;+ payload["transactionType"] = (order.side == OrderSide::Buy) ? "BUY" : "SELL";+ payload["orderType"] = order_type;+ payload["quantity"] = QString::number(static_cast<int>(order.quantity));+ payload["disclosedQuantity"] = "0";+ payload["orderValidity"] = "DAY";+ payload["productType"] = sm_enum_map().product_or(order.product_type, "MIS");+ payload["afterMarketOrderFlag"] = order.amo ? "YES" : "NO";+ if (order_type == "L" || order_type == "SL")+ payload["price"] = QString::number(order.price, 'f', 2);+ if (order_type == "SL" || order_type == "SL-M")+ payload["triggerPrice"] = QString::number(order.stop_price, 'f', 2);++ auto& http = BrokerHttp::instance();+ auto resp = http.post_json(QString("%1/order/placeOrder").arg(BASE), payload, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, "", checked_error(resp, "place_order failed")};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "place_order: invalid response"};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success")+ return {false, "", obj.value("statusMessage").toString("place_order failed")};++ return {true, obj.value("orderNumber").toString(), ""};+}++// ---------- modify_order ----------+// PUT /order/modifyOrder/{orderNumber}++ApiResponse<QJsonObject> SamcoBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) {+ int64_t ts = now_ts();++ const QString price_type = mods.value("orderType").toString("L");+ QJsonObject payload;+ payload["orderType"] = price_type;+ payload["quantity"] = QString::number(mods.value("quantity").toInt(0));+ payload["orderValidity"] = "DAY";+ if (price_type == "L" || price_type == "SL")+ payload["price"] = QString::number(mods.value("price").toDouble(0), 'f', 2);+ if (price_type == "SL" || price_type == "SL-M")+ payload["triggerPrice"] = QString::number(mods.value("triggerPrice").toDouble(0), 'f', 2);++ auto& http = BrokerHttp::instance();+ auto resp = http.put_json(QString("%1/order/modifyOrder/%2").arg(BASE, order_id), payload, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "modify_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success")+ return {false, std::nullopt, obj.value("statusMessage").toString("modify_order failed"), ts};++ return {true, obj, "", ts};+}++// ---------- cancel_order ----------+// DELETE /order/cancelOrder?orderNumber=<id>++ApiResponse<QJsonObject> SamcoBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {+ int64_t ts = now_ts();++ QUrlQuery q;+ q.addQueryItem("orderNumber", order_id);+ QString url = QString("%1/order/cancelOrder?%2").arg(BASE, q.toString(QUrl::FullyEncoded));++ auto& http = BrokerHttp::instance();+ auto resp = http.del(url, auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "cancel_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success")+ return {false, std::nullopt, obj.value("statusMessage").toString("cancel_order failed"), ts};++ return {true, obj, "", ts};+}++// ---------- get_orders ----------+// GET /order/orderBook++ApiResponse<QVector<BrokerOrderInfo>> SamcoBroker::get_orders(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/order/orderBook").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_orders: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success") {+ QString msg = obj.value("statusMessage").toString().toLower();+ if (msg.contains("no data") || msg.contains("no order"))+ return {true, QVector<BrokerOrderInfo>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};+ }++ QVector<BrokerOrderInfo> orders;+ for (const QJsonValue& v : obj.value("orderBookDetails").toArray()) {+ QJsonObject o = v.toObject();+ BrokerOrderInfo info;+ info.order_id = o.value("orderNumber").toString();+ info.symbol = o.value("tradingSymbol").toString(o.value("symbol").toString());+ info.exchange = o.value("exchange").toString();+ info.quantity = samco_i(samco_first(o, "totalQuantity", "quantity"));+ info.filled_qty = samco_i(o.value("filledQuantity"));+ info.price = samco_d(samco_first(o, "orderPrice", "price"));+ info.stop_price = samco_d(o.value("triggerPrice"));+ info.avg_price = samco_d(o.value("averagePrice"));+ info.status = sm_status(o.value("orderStatus").toString());+ info.side = o.value("transactionType").toString().toLower();+ info.order_type = o.value("orderType").toString();+ info.product_type = o.value("productCode").toString();+ info.timestamp = o.value("orderTime").toString();+ info.message = o.value("statusMessage").toString();+ orders.append(info);+ }++ return {true, orders, "", ts};+}++// ---------- get_trade_book ----------+// GET /trade/tradeBook++ApiResponse<QJsonObject> SamcoBroker::get_trade_book(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/trade/tradeBook").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_trade_book failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject())+ return {true, doc.object(), "", ts};+ return {false, std::nullopt, "get_trade_book: invalid response", ts};+}++// ---------- get_positions ----------+// GET /position/getPositions?positionType=DAY++ApiResponse<QVector<BrokerPosition>> SamcoBroker::get_positions(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/position/getPositions?positionType=DAY").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_positions: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success") {+ QString msg = obj.value("statusMessage").toString().toLower();+ if (msg.contains("no data") || msg.contains("no position"))+ return {true, QVector<BrokerPosition>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};+ }++ QVector<BrokerPosition> positions;+ for (const QJsonValue& v : obj.value("positionDetails").toArray()) {+ QJsonObject o = v.toObject();+ int net_qty = static_cast<int>(samco_i(o.value("netQuantity")));+ if (net_qty == 0)+ continue;+ // Samco reports a positive netQuantity; transactionType carries the sign.+ if (o.value("transactionType").toString().toUpper() == "SELL" && net_qty > 0)+ net_qty = -net_qty;++ BrokerPosition pos;+ pos.symbol = o.value("tradingSymbol").toString();+ pos.exchange = o.value("exchange").toString();+ pos.product_type = o.value("productCode").toString();+ pos.quantity = net_qty;+ pos.avg_price = samco_d(o.value("averagePrice"));+ pos.ltp = samco_d(o.value("lastTradedPrice"));+ pos.pnl = samco_d(o.value("realizedGainAndLoss")) + samco_d(o.value("mtmGainLoss"));+ pos.side = net_qty > 0 ? "LONG" : "SHORT";+ positions.append(pos);+ }++ return {true, positions, "", ts};+}++// ---------- get_holdings ----------+// GET /holding/getHoldings++ApiResponse<QVector<BrokerHolding>> SamcoBroker::get_holdings(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/holding/getHoldings").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_holdings: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success") {+ QString msg = obj.value("statusMessage").toString().toLower();+ if (msg.contains("no data") || msg.contains("no holding"))+ return {true, QVector<BrokerHolding>{}, "", ts};+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};+ }++ QVector<BrokerHolding> holdings;+ for (const QJsonValue& v : obj.value("holdingDetails").toArray()) {+ QJsonObject o = v.toObject();+ BrokerHolding h;+ h.symbol = o.value("tradingSymbol").toString(o.value("symbol").toString());+ h.exchange = o.value("exchange").toString();+ h.quantity = samco_d(samco_first(o, "holdingsQuantity", "quantity"));+ h.avg_price = samco_d(o.value("averagePrice"));+ h.ltp = samco_d(o.value("lastTradedPrice"));+ h.invested_value = h.quantity * h.avg_price;+ h.current_value = h.quantity * h.ltp;+ h.pnl = (h.ltp - h.avg_price) * h.quantity;+ if (h.avg_price > 0)+ h.pnl_pct = ((h.ltp - h.avg_price) / h.avg_price) * 100.0;+ holdings.append(h);+ }++ return {true, holdings, "", ts};+}++// ---------- get_funds ----------+// GET /limit/getLimits++ApiResponse<BrokerFunds> SamcoBroker::get_funds(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/limit/getLimits").arg(BASE), auth_headers(creds));++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_funds: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success")+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonObject eq = obj.value("equityLimit").toObject();+ BrokerFunds funds;+ funds.available_balance = samco_d(eq.value("netAvailableMargin"));+ funds.used_margin = samco_d(eq.value("marginUsed"));+ funds.collateral = samco_d(eq.value("collateralMarginAgainstShares"));+ funds.total_balance = funds.available_balance + funds.used_margin;+ funds.raw_data = obj;++ return {true, funds, "", ts};+}++// ---------- get_quotes ----------+// GET /quote/getQuote?symbolName=<sym>[&exchange=<exch>]+// Symbol format: "EXCHANGE:SYMBOL" or just the broker symbol.++ApiResponse<QVector<BrokerQuote>> SamcoBroker::get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) {+ int64_t ts = now_ts();+ if (symbols.isEmpty())+ return {true, QVector<BrokerQuote>{}, "", ts};++ auto& http = BrokerHttp::instance();+ QVector<BrokerQuote> quotes;++ for (const QString& sym : symbols) {+ QStringList parts = sym.split(":");+ QString exchange = (parts.size() >= 2) ? parts[0] : "NSE";+ QString name = (parts.size() >= 2) ? parts[1] : sym;++ QUrlQuery q;+ q.addQueryItem("symbolName", name);+ if (!exchange.isEmpty() && exchange != "NSE")+ q.addQueryItem("exchange", exchange);+ QString url = QString("%1/quote/getQuote?%2").arg(BASE, q.toString(QUrl::FullyEncoded));++ auto resp = http.get(url, auth_headers(creds));+ if (!resp.success && resp.status_code == 0)+ continue;++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ continue;+ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success")+ continue;++ QJsonObject quote = obj.value("quoteDetails").toObject();+ BrokerQuote bq;+ bq.symbol = name;+ bq.ltp = samco_d(quote.value("lastTradedPrice"));+ bq.open = samco_d(quote.value("openValue"));+ bq.high = samco_d(quote.value("highValue"));+ bq.low = samco_d(quote.value("lowValue"));+ bq.close = samco_d(quote.value("previousClose"));+ bq.volume = samco_d(quote.value("totalTradedVolume"));+ bq.oi = samco_i(quote.value("openInterest"));+ QJsonArray bids = quote.value("bestBids").toArray();+ QJsonArray asks = quote.value("bestAsks").toArray();+ if (!bids.isEmpty())+ bq.bid = samco_d(bids[0].toObject().value("price"));+ if (!asks.isEmpty())+ bq.ask = samco_d(asks[0].toObject().value("price"));+ if (bq.close > 0) {+ bq.change = bq.ltp - bq.close;+ bq.change_pct = (bq.ltp - bq.close) / bq.close * 100.0;+ }+ bq.timestamp = ts;+ quotes.append(bq);+ }++ return {true, quotes, "", ts};+}++// ---------- get_history ----------+// Daily: GET /history/candleData?symbolName=<sym>&fromDate=<d>&toDate=<d>[&exchange=]+// Intraday: GET /intraday/candleData?symbolName=<sym>&fromDate=<d %H:%M:%S>&toDate=<...>&interval=<min>++ApiResponse<QVector<BrokerCandle>> SamcoBroker::get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) {+ int64_t ts = now_ts();++ QStringList parts = symbol.split(":");+ QString exchange = (parts.size() >= 2) ? parts[0] : "NSE";+ QString name = (parts.size() >= 2) ? parts[1] : symbol;++ QDate from = QDate::fromString(from_date, "yyyy-MM-dd");+ QDate to = QDate::fromString(to_date, "yyyy-MM-dd");+ if (!from.isValid())+ from = QDate::currentDate().addYears(-1);+ if (!to.isValid())+ to = QDate::currentDate();++ bool is_daily = (resolution == "D" || resolution == "1D" || resolution == "W" || resolution == "M");+ auto& http = BrokerHttp::instance();+ QString url, data_key;++ if (is_daily) {+ QUrlQuery q;+ q.addQueryItem("symbolName", name);+ q.addQueryItem("fromDate", from.toString("yyyy-MM-dd"));+ q.addQueryItem("toDate", to.toString("yyyy-MM-dd"));+ if (!exchange.isEmpty() && exchange != "NSE")+ q.addQueryItem("exchange", exchange);+ url = QString("%1/history/candleData?%2").arg(BASE, q.toString(QUrl::FullyEncoded));+ data_key = "historicalCandleData";+ } else {+ static const QMap<QString, QString> interval_map = {+ {"1", "1"}, {"5", "5"}, {"10", "10"}, {"15", "15"}, {"30", "30"}, {"60", "60"},+ };+ QString interval = interval_map.value(resolution, "5");+ QUrlQuery q;+ q.addQueryItem("symbolName", name);+ q.addQueryItem("fromDate", from.toString("yyyy-MM-dd") + " 00:00:00");+ q.addQueryItem("toDate", to.toString("yyyy-MM-dd") + " 23:59:59");+ q.addQueryItem("interval", interval);+ if (!exchange.isEmpty() && exchange != "NSE")+ q.addQueryItem("exchange", exchange);+ url = QString("%1/intraday/candleData?%2").arg(BASE, q.toString(QUrl::FullyEncoded));+ data_key = "intradayCandleData";+ }++ auto resp = http.get(url, auth_headers(creds));+ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_history: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("status").toString() != "Success")+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};++ QVector<BrokerCandle> candles;+ for (const QJsonValue& v : obj.value(data_key).toArray()) {+ QJsonObject o = v.toObject();+ BrokerCandle c;+ // Daily: "date" (yyyy-MM-dd). Intraday: "dateTime" (yyyy-MM-dd HH:mm:ss).+ QString date_str = o.value("dateTime").toString(o.value("date").toString());+ QDateTime dt = QDateTime::fromString(date_str, "yyyy-MM-dd HH:mm:ss");+ if (!dt.isValid())+ dt = QDateTime(QDate::fromString(date_str.left(10), "yyyy-MM-dd"), QTime(0, 0, 0));+ c.timestamp = dt.isValid() ? dt.toSecsSinceEpoch() * 1000LL : 0LL;+ c.open = samco_d(o.value("open"));+ c.high = samco_d(o.value("high"));+ c.low = samco_d(o.value("low"));+ c.close = samco_d(o.value("close"));+ c.volume = samco_d(o.value("volume"));+ candles.append(c);+ }++ return {true, candles, "", ts};+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/samco/SamcoBroker.h b/fincept-qt/src/trading/brokers/samco/SamcoBroker.hnew file mode 100644index 000000000..2b5ae4fbb--- /dev/null+++ b/fincept-qt/src/trading/brokers/samco/SamcoBroker.h@@ -0,0 +1,90 @@+#pragma once+#include "trading/BrokerInterface.h"+#include "trading/adapter/BrokerEnumMap.h"+#include "trading/brokers/BrokerHttp.h"++namespace fincept::trading {++// Samco StockNote API — REST broker on https://tradeapi.samco.in.+// Authenticated calls carry the session token in the x-session-token header.+//+// Credential packing:+// ApiKey = uid (Samco user/client id)+// ApiSecret = password (account password)+// AuthCode = secret_api_key (permanent secret API key generated via the+// one-time OTP → secretKeyGenerator flow)+//+// Auth flow (the OTP/secret-key generation is a one-time out-of-band setup;+// we only run the repeatable session-establishing steps):+// 1. POST /accessToken/token {uid, secretApiKey} → accessToken (24h)+// 2. POST /login {userId, password, accessToken} → sessionToken+// The sessionToken is what we persist as access_token.++class SamcoBroker : public IBroker {+ public:+ BrokerId id() const override { return BrokerId::Samco; }+ const char* name() const override { return "Samco"; }+ const char* base_url() const override { return "https://tradeapi.samco.in"; }+ const char* ws_adapter_name() const override { return "samco"; }++ BrokerProfile profile() const override {+ return BrokerProfile{+ .id = "samco",+ .display_name = "Samco",+ .region = "IN",+ .currency = "INR",+ .credential_fields =+ {+ {CredentialField::ApiKey, "USER ID", "Enter User ID...", false},+ {CredentialField::ApiSecret, "PASSWORD", "Account password", true},+ {CredentialField::AuthCode, "SECRET API KEY", "Permanent secret API key", true},+ },+ .exchanges = {"NSE", "BSE", "NFO", "BFO", "MCX", "CDS"},+ .product_types =+ {+ {"Intraday (MIS)", ProductType::Intraday},+ {"Delivery (CNC)", ProductType::Delivery},+ {"Margin (NRML)", ProductType::Margin},+ },+ .supports_intraday = true,+ .supports_bracket_order = false,+ .supports_cover_order = false,+ .has_native_paper = false,+ .default_paper_balance = 1000000.0,+ .default_watchlist = {"HDFCBANK", "ICICIBANK", "SBIN", "TCS", "INFY", "RELIANCE", "TATAMOTORS",+ "BAJFINANCE", "HINDUNILVR", "ITC"},+ .default_symbol = "RELIANCE",+ .default_exchange = "NSE",+ .brokerage_info = "₹20/order or 0.5% (whichever lower)",+ };+ }++ TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) override;+ OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;+ ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) override;+ ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;+ ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;+ ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) override;+ ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) override;++ static bool is_token_expired(const BrokerHttpResponse& resp);+ static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);++ protected:+ QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;++ private:+ static const BrokerEnumMap<QString>& sm_enum_map();+ static QString sm_status(const QString& s);+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.h b/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.hindex abbc2e580..f9ff221b3 100644--- a/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.h+++ b/fincept-qt/src/trading/brokers/shoonya/ShoonyaBroker.h@@ -18,6 +18,7 @@ class ShoonyaBroker : public IBroker {BrokerId id() const override { return BrokerId::Shoonya; }const char* name() const override { return "Shoonya"; }const char* base_url() const override { return "https://api.shoonya.com/NorenWClientTP"; }+ const char* ws_adapter_name() const override { return "shoonya"; }BrokerProfile profile() const override {return BrokerProfile{diff --git a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cppnew file mode 100644index 000000000..55d6f542b--- /dev/null+++ b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp@@ -0,0 +1,541 @@+#include "trading/brokers/tradejini/TradejiniBroker.h"++#include "trading/brokers/BrokerHttp.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QUrlQuery>++namespace fincept::trading {++static constexpr const char* BASE = "https://api.tradejini.com/v2";++static int64_t now_ts() {+ return QDateTime::currentSecsSinceEpoch();+}++// Pick the first present key from an object and return it as a QJsonValue.+static QJsonValue tj_first(const QJsonObject& o, const QString& a, const QString& b) {+ return o.contains(a) ? o.value(a) : o.value(b);+}++// ---------- Static helpers ----------++QString TradejiniBroker::bearer(const BrokerCredentials& creds) {+ // Header format: "Bearer <api_key>:<access_token>".+ return QString("Bearer %1:%2").arg(creds.api_key, creds.access_token);+}++const BrokerEnumMap<QString>& TradejiniBroker::tj_enum_map() {+ static const auto m = [] {+ BrokerEnumMap<QString> x;+ x.set(OrderType::Market, "market");+ x.set(OrderType::Limit, "limit");+ x.set(OrderType::StopLoss, "stopmarket"); // SL-M+ x.set(OrderType::StopLossLimit, "stoplimit");+ x.set(ProductType::Intraday, "intraday");+ x.set(ProductType::Delivery, "delivery");+ x.set(ProductType::Margin, "normal");+ return x;+ }();+ return m;+}++QString TradejiniBroker::tj_status(const QString& s) {+ QString sl = s.toLower();+ if (sl == "complete" || sl == "completed" || sl == "executed" || sl == "filled" || sl == "traded")+ return "filled";+ if (sl == "open" || sl == "pending" || sl == "trigger pending" || sl == "modified")+ return "open";+ if (sl == "cancelled" || sl == "canceled")+ return "cancelled";+ if (sl == "rejected")+ return "rejected";+ return "open";+}++bool TradejiniBroker::is_token_expired(const BrokerHttpResponse& resp) {+ if (resp.status_code == 401 || resp.status_code == 403)+ return true;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return false;+ QJsonObject obj = doc.object();+ QString msg = obj.value("message").toString().toLower();+ if (msg.isEmpty() && obj.value("d").isObject())+ msg = obj.value("d").toObject().value("msg").toString().toLower();+ return msg.contains("unauthorized") || msg.contains("invalid token") || msg.contains("session") ||+ msg.contains("expired") || msg.contains("token");+}++QString TradejiniBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {+ if (is_token_expired(resp))+ return "[TOKEN_EXPIRED] Session expired, please re-login";+ if (!resp.success && resp.status_code == 0)+ return resp.error.isEmpty() ? fallback : resp.error;+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (doc.isObject()) {+ QJsonObject obj = doc.object();+ QString msg = obj.value("message").toString();+ if (msg.isEmpty() && obj.value("d").isObject())+ msg = obj.value("d").toObject().value("msg").toString();+ if (!msg.isEmpty())+ return msg;+ }+ return fallback;+}++// ---------- Auth headers ----------++QMap<QString, QString> TradejiniBroker::auth_headers(const BrokerCredentials& creds) const {+ return {{"Authorization", bearer(creds)}};+}++// ---------- exchange_token ----------+// ApiKey = api_key (bearer prefix / app secret)+// ApiSecret = password+// AuthCode = totp+// POST /api-gw/oauth/individual-token-v2 (Bearer <api_key>, form: password, twoFa, twoFaTyp=totp)++TokenExchangeResponse TradejiniBroker::exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) {+ if (api_key.isEmpty() || api_secret.isEmpty() || auth_code.isEmpty())+ return {false, "", "", "", "Tradejini login: api_key, password and TOTP are required", ""};++ QMap<QString, QString> params;+ params["password"] = api_secret;+ params["twoFa"] = auth_code.trimmed();+ params["twoFaTyp"] = "totp";++ auto& http = BrokerHttp::instance();+ auto resp = http.post_form(QString("%1/api-gw/oauth/individual-token-v2").arg(BASE), params,+ {{"Authorization", QString("Bearer %1").arg(api_key)}});++ if (!resp.success && resp.status_code == 0)+ return {false, "", "", "", "Login failed: " + resp.error, ""};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "", "", "Login: invalid response", ""};++ QJsonObject obj = doc.object();+ QString token = obj.value("access_token").toString();+ if (token.isEmpty())+ return {false, "", "", "", obj.value("message").toString("Login failed: no access token"), ""};++ return {true, token, "", "", "", ""};+}++// ---------- place_order ----------+// POST /oms/place-order (form-urlencoded)++OrderPlaceResponse TradejiniBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {+ const QString order_type = tj_enum_map().order_type_or(order.order_type, "market");++ QMap<QString, QString> params;+ params["symId"] = order.symbol; // broker symbol id, e.g. "RELIANCE-EQ" / token id+ params["qty"] = QString::number(static_cast<int>(order.quantity));+ params["side"] = (order.side == OrderSide::Buy) ? "buy" : "sell";+ params["type"] = order_type;+ params["product"] = tj_enum_map().product_or(order.product_type, "intraday");+ params["validity"] = (order.validity.compare("IOC", Qt::CaseInsensitive) == 0) ? "ioc" : "day";++ if (order_type == "limit" || order_type == "stoplimit")+ params["limitPrice"] = QString::number(order.price, 'f', 2);+ if (order_type == "stoplimit" || order_type == "stopmarket")+ params["trigPrice"] = QString::number(order.stop_price, 'f', 2);+ if (order_type == "market" || order_type == "stopmarket")+ params["mktProt"] = "2";++ auto& http = BrokerHttp::instance();+ auto resp = http.post_form(QString("%1/oms/place-order").arg(BASE), params, {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, "", checked_error(resp, "place_order failed")};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, "", "place_order: invalid response"};++ QJsonObject obj = doc.object();+ if (obj.value("s").toString() != "ok")+ return {false, "", checked_error(resp, "place_order failed")};++ // orderId may be a string or a number — toVariant().toString() handles both.+ QString order_id = obj.value("d").toObject().value("orderId").toVariant().toString();+ if (order_id.isEmpty())+ return {false, "", "place_order: no orderId in response"};+ return {true, order_id, ""};+}++// ---------- modify_order ----------+// PUT /api/oms/modify-order (form-urlencoded)++ApiResponse<QJsonObject> TradejiniBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) {+ int64_t ts = now_ts();++ const QString price_type = mods.value("orderType").toString("limit").toLower();+ QString tj_type = "limit";+ if (price_type.contains("market") && price_type.contains("stop"))+ tj_type = "stopmarket";+ else if (price_type.contains("stop") || price_type == "sl")+ tj_type = "stoplimit";+ else if (price_type.contains("market"))+ tj_type = "market";++ QMap<QString, QString> params;+ params["symId"] = mods.value("symbol").toString();+ params["orderId"] = order_id;+ params["qty"] = QString::number(mods.value("quantity").toInt(0));+ params["type"] = tj_type;+ params["validity"] = "day";+ params["side"] = mods.value("side").toString("buy").toLower();+ if (tj_type == "limit" || tj_type == "stoplimit")+ params["limitPrice"] = QString::number(mods.value("price").toDouble(0), 'f', 2);+ if (tj_type == "stoplimit" || tj_type == "stopmarket")+ params["trigPrice"] = QString::number(mods.value("triggerPrice").toDouble(0), 'f', 2);++ auto& http = BrokerHttp::instance();+ auto resp = http.put_form(QString("%1/api/oms/modify-order").arg(BASE), params, {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "modify_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("s").toString() != "ok")+ return {false, std::nullopt, checked_error(resp, "modify_order failed"), ts};++ return {true, obj.value("d").toObject(), "", ts};+}++// ---------- cancel_order ----------+// DELETE /api/oms/cancel-order?orderId=<id>++ApiResponse<QJsonObject> TradejiniBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {+ int64_t ts = now_ts();++ QUrlQuery q;+ q.addQueryItem("orderId", order_id);+ QString url = QString("%1/api/oms/cancel-order?%2").arg(BASE, q.toString(QUrl::FullyEncoded));++ auto& http = BrokerHttp::instance();+ auto resp = http.del(url, {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "cancel_order: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("s").toString() != "ok")+ return {false, std::nullopt, checked_error(resp, "cancel_order failed"), ts};++ return {true, obj.value("d").toObject(), "", ts};+}++// ---------- get_orders ----------+// GET /api/oms/orders?symDetails=true++ApiResponse<QVector<BrokerOrderInfo>> TradejiniBroker::get_orders(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/api/oms/orders?symDetails=true").arg(BASE), {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_orders: invalid response", ts};++ QJsonObject obj = doc.object();+ QString s = obj.value("s").toString();+ if (s == "no-data")+ return {true, QVector<BrokerOrderInfo>{}, "", ts};+ if (s != "ok")+ return {false, std::nullopt, checked_error(resp, "get_orders failed"), ts};++ QVector<BrokerOrderInfo> orders;+ for (const QJsonValue& v : obj.value("d").toArray()) {+ QJsonObject o = v.toObject();+ QJsonObject sym = o.value("sym").toObject();+ BrokerOrderInfo info;+ info.order_id = o.value("orderId").toVariant().toString();+ info.symbol = sym.value("trdSym").toString(sym.value("sym").toString());+ info.exchange = sym.value("exch").toString();+ info.quantity = o.value("qty").toVariant().toInt();+ info.filled_qty = o.value("fillQty").toVariant().toInt();+ info.price = o.value("limitPrice").toVariant().toDouble();+ info.stop_price = o.value("trigPrice").toVariant().toDouble();+ info.avg_price = o.value("avgPrice").toVariant().toDouble();+ info.status = tj_status(o.value("status").toString());+ info.side = o.value("side").toString().toLower();+ info.order_type = o.value("type").toString();+ info.product_type = o.value("product").toString();+ info.timestamp = o.value("orderTime").toString();+ orders.append(info);+ }++ return {true, orders, "", ts};+}++// ---------- get_trade_book ----------+// GET /api/oms/trades?symDetails=true++ApiResponse<QJsonObject> TradejiniBroker::get_trade_book(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/api/oms/trades?symDetails=true").arg(BASE), {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_trade_book failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_trade_book: invalid response", ts};++ QJsonObject obj = doc.object();+ QString s = obj.value("s").toString();+ if (s != "ok" && s != "no-data")+ return {false, std::nullopt, checked_error(resp, "get_trade_book failed"), ts};++ QJsonObject wrapper;+ wrapper["trades"] = obj.value("d").toArray();+ return {true, wrapper, "", ts};+}++// ---------- get_positions ----------+// GET /api/oms/positions?symDetails=true++ApiResponse<QVector<BrokerPosition>> TradejiniBroker::get_positions(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/api/oms/positions?symDetails=true").arg(BASE), {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_positions: invalid response", ts};++ QJsonObject obj = doc.object();+ QString s = obj.value("s").toString();+ if (s == "no-data")+ return {true, QVector<BrokerPosition>{}, "", ts};+ if (s != "ok")+ return {false, std::nullopt, checked_error(resp, "get_positions failed"), ts};++ QVector<BrokerPosition> positions;+ for (const QJsonValue& v : obj.value("d").toArray()) {+ QJsonObject o = v.toObject();+ int net_qty = o.value("netQty").toVariant().toInt();+ if (net_qty == 0)+ continue;+ QJsonObject sym = o.value("sym").toObject();+ BrokerPosition pos;+ pos.symbol = sym.value("trdSym").toString(sym.value("sym").toString());+ pos.exchange = sym.value("exch").toString();+ QString product = o.value("product").toString().toLower();+ pos.product_type = (product == "delivery") ? "CNC" : (product == "intraday" ? "MIS" : "NRML");+ pos.quantity = net_qty;+ pos.avg_price = o.value("netAvgPrice").toVariant().toDouble();+ pos.ltp = o.value("ltp").toVariant().toDouble();+ pos.pnl = o.value("realizedPnl").toVariant().toDouble() + o.value("unrealizedPnl").toVariant().toDouble();+ pos.side = net_qty > 0 ? "LONG" : "SHORT";+ positions.append(pos);+ }++ return {true, positions, "", ts};+}++// ---------- get_holdings ----------+// GET /api/oms/holdings?symDetails=true++ApiResponse<QVector<BrokerHolding>> TradejiniBroker::get_holdings(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/api/oms/holdings?symDetails=true").arg(BASE), {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_holdings: invalid response", ts};++ QJsonObject obj = doc.object();+ QString s = obj.value("s").toString();+ if (s == "no-data")+ return {true, QVector<BrokerHolding>{}, "", ts};+ if (s != "ok")+ return {false, std::nullopt, checked_error(resp, "get_holdings failed"), ts};++ // Holdings payload may be an array under "d" or a "holdings" array inside "d".+ QJsonValue d = obj.value("d");+ QJsonArray arr;+ if (d.isArray())+ arr = d.toArray();+ else if (d.isObject())+ arr = d.toObject().value("holdings").toArray();++ QVector<BrokerHolding> holdings;+ for (const QJsonValue& v : arr) {+ QJsonObject o = v.toObject();+ QJsonObject sym = o.value("sym").toObject();+ BrokerHolding h;+ h.symbol = sym.value("trdSym").toString(sym.value("sym").toString(o.value("symbol").toString()));+ h.exchange = sym.value("exch").toString(o.value("exchange").toString());+ h.quantity = tj_first(o, "qty", "quantity").toVariant().toDouble();+ h.avg_price = o.value("avgPrice").toVariant().toDouble();+ h.ltp = o.value("ltp").toVariant().toDouble();+ h.pnl = o.value("pnl").toVariant().toDouble();+ h.pnl_pct = tj_first(o, "pnlPercent", "pnlpercent").toVariant().toDouble();+ h.invested_value = h.quantity * h.avg_price;+ h.current_value = h.quantity * h.ltp;+ holdings.append(h);+ }++ return {true, holdings, "", ts};+}++// ---------- get_funds ----------+// GET /api/oms/limits++ApiResponse<BrokerFunds> TradejiniBroker::get_funds(const BrokerCredentials& creds) {+ int64_t ts = now_ts();++ auto& http = BrokerHttp::instance();+ auto resp = http.get(QString("%1/api/oms/limits").arg(BASE), {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_funds: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("s").toString() != "ok")+ return {false, std::nullopt, checked_error(resp, "get_funds failed"), ts};++ QJsonObject m = obj.value("d").toObject();+ BrokerFunds funds;+ funds.available_balance = m.value("availMargin").toVariant().toDouble();+ funds.used_margin = m.value("marginUsed").toVariant().toDouble();+ funds.collateral = m.value("stockCollateral").toVariant().toDouble();+ funds.total_balance = funds.available_balance + funds.used_margin ++ m.value("realizedPnl").toVariant().toDouble();+ funds.raw_data = m;++ return {true, funds, "", ts};+}++// ---------- get_quotes ----------+// Tradejini exposes real-time quotes only through its WebSocket SDK (NxtradStream),+// not a REST endpoint. Stream live quotes via the ws adapter; this REST method+// has no upstream equivalent.++ApiResponse<QVector<BrokerQuote>> TradejiniBroker::get_quotes(const BrokerCredentials& /*creds*/,+ const QVector<QString>& /*symbols*/) {+ return {false, std::nullopt,+ "Tradejini quotes are WebSocket-only — use the streaming adapter (no REST quote endpoint)", now_ts()};+}++// ---------- get_history ----------+// GET /api/mkt-data/chart/interval-data?id=<symId>&interval=<min>&from=<sec>&to=<sec>++ApiResponse<QVector<BrokerCandle>> TradejiniBroker::get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) {+ int64_t ts = now_ts();++ // Symbol format: "EXCHANGE:SYMID" or just the broker symbol id.+ QStringList parts = symbol.split(":");+ QString sym_id = (parts.size() >= 2) ? parts[1] : symbol;++ QDate from = QDate::fromString(from_date, "yyyy-MM-dd");+ QDate to = QDate::fromString(to_date, "yyyy-MM-dd");+ if (!from.isValid())+ from = QDate::currentDate().addYears(-1);+ if (!to.isValid())+ to = QDate::currentDate();++ int64_t from_epoch = QDateTime(from, QTime(9, 15, 0)).toSecsSinceEpoch();+ int64_t to_epoch = QDateTime(to, QTime(23, 59, 59)).toSecsSinceEpoch();++ // Tradejini intervals are integer minutes; daily is unsupported via this endpoint.+ static const QMap<QString, QString> interval_map = {+ {"1", "1"}, {"5", "5"}, {"15", "15"}, {"30", "30"}, {"60", "60"},+ };+ QString interval = interval_map.value(resolution, "5");++ QUrlQuery q;+ q.addQueryItem("id", sym_id);+ q.addQueryItem("interval", interval);+ q.addQueryItem("from", QString::number(from_epoch));+ q.addQueryItem("to", QString::number(to_epoch));+ QString url = QString("%1/api/mkt-data/chart/interval-data?%2").arg(BASE, q.toString(QUrl::FullyEncoded));++ auto& http = BrokerHttp::instance();+ auto resp = http.get(url, {{"Authorization", bearer(creds)}});++ if (!resp.success && resp.status_code == 0)+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};++ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());+ if (!doc.isObject())+ return {false, std::nullopt, "get_history: invalid response", ts};++ QJsonObject obj = doc.object();+ if (obj.value("s").toString() != "ok")+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};++ QVector<BrokerCandle> candles;+ // Payload "d" is typically an array of candle rows; support both object-rows+ // and column arrays [t, o, h, l, c, v].+ for (const QJsonValue& v : obj.value("d").toArray()) {+ BrokerCandle c;+ if (v.isObject()) {+ QJsonObject o = v.toObject();+ QJsonValue tv = o.contains("timestamp") ? o.value("timestamp") : o.value("time");+ int64_t t = static_cast<int64_t>(tv.toVariant().toLongLong());+ c.timestamp = (t > 1000000000000LL) ? t : t * 1000LL;+ c.open = o.value("open").toVariant().toDouble();+ c.high = o.value("high").toVariant().toDouble();+ c.low = o.value("low").toVariant().toDouble();+ c.close = o.value("close").toVariant().toDouble();+ c.volume = o.value("volume").toVariant().toDouble();+ } else if (v.isArray()) {+ QJsonArray row = v.toArray();+ if (row.size() < 6)+ continue;+ int64_t t = row[0].toVariant().toLongLong();+ c.timestamp = (t > 1000000000000LL) ? t : t * 1000LL;+ c.open = row[1].toVariant().toDouble();+ c.high = row[2].toVariant().toDouble();+ c.low = row[3].toVariant().toDouble();+ c.close = row[4].toVariant().toDouble();+ c.volume = row[5].toVariant().toDouble();+ } else {+ continue;+ }+ candles.append(c);+ }++ return {true, candles, "", ts};+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.h b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.hnew file mode 100644index 000000000..dcbdc3417--- /dev/null+++ b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.h@@ -0,0 +1,94 @@+#pragma once+#include "trading/BrokerInterface.h"+#include "trading/adapter/BrokerEnumMap.h"+#include "trading/brokers/BrokerHttp.h"++namespace fincept::trading {++// Tradejini is a custom REST broker (NOT Noren) on api.tradejini.com/v2.+// All authenticated calls carry Authorization: Bearer <api_key>:<access_token>+// where api_key is the app's API secret (BROKER_API_SECRET in OpenAlgo) and+// access_token is the per-session token returned by the individual-token login.+//+// Credential packing:+// ApiKey = api_key (app API secret used as the bearer prefix / client id)+// ApiSecret = password (user account password)+// AuthCode = totp (6-digit time-based OTP)+//+// Auth flow:+// POST /api-gw/oauth/individual-token-v2 (Bearer <api_key>, form body)+// body: password=<pwd>&twoFa=<totp>&twoFaTyp=totp+// → {access_token, token_type:"Bearer", expires_in}+//+// Response envelope for data endpoints: {"s":"ok","d":<payload>}.++class TradejiniBroker : public IBroker {+ public:+ BrokerId id() const override { return BrokerId::Tradejini; }+ const char* name() const override { return "Tradejini"; }+ const char* base_url() const override { return "https://api.tradejini.com/v2"; }+ const char* ws_adapter_name() const override { return "tradejini"; }++ BrokerProfile profile() const override {+ return BrokerProfile{+ .id = "tradejini",+ .display_name = "Tradejini",+ .region = "IN",+ .currency = "INR",+ .credential_fields =+ {+ {CredentialField::ApiKey, "API KEY", "Enter API Key...", false},+ {CredentialField::ApiSecret, "PASSWORD", "Account password", true},+ {CredentialField::AuthCode, "TOTP", "6-digit TOTP", false},+ },+ .exchanges = {"NSE", "BSE", "NFO", "BFO", "MCX", "CDS"},+ .product_types =+ {+ {"Intraday (MIS)", ProductType::Intraday},+ {"Delivery (CNC)", ProductType::Delivery},+ {"Margin (NRML)", ProductType::Margin},+ },+ .supports_intraday = true,+ .supports_bracket_order = false,+ .supports_cover_order = false,+ .has_native_paper = false,+ .default_paper_balance = 1000000.0,+ .default_watchlist = {"HDFCBANK", "ICICIBANK", "SBIN", "TCS", "INFY", "RELIANCE", "TATAMOTORS",+ "BAJFINANCE", "HINDUNILVR", "ITC"},+ .default_symbol = "RELIANCE",+ .default_exchange = "NSE",+ .brokerage_info = "Flat ₹20/order",+ };+ }++ TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,+ const QString& auth_code) override;+ OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;+ ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,+ const QJsonObject& mods) override;+ ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;+ ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;+ ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;+ ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,+ const QVector<QString>& symbols) override;+ ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,+ const QString& resolution, const QString& from_date,+ const QString& to_date) override;++ static bool is_token_expired(const BrokerHttpResponse& resp);+ static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);++ protected:+ QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;++ private:+ static const BrokerEnumMap<QString>& tj_enum_map();+ static QString tj_status(const QString& s);+ // Bearer value: "<api_key>:<access_token>"+ static QString bearer(const BrokerCredentials& creds);+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cppindex aee91acc3..e28893450 100644--- a/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp+++ b/fincept-qt/src/trading/brokers/tradier/TradierBroker.cpp@@ -578,4 +578,14 @@ ApiResponse<QVector<BrokerCandle>> TradierBroker::get_history(const BrokerCredenreturn {true, candles, "", ts};}+// ============================================================================+// Pre-trade margin calculator — fallback estimator.+// Tradier exposes no per-order margin endpoint, so we use the shared heuristic+// estimator (BrokerInterface.h::estimate_order_margin).+// ============================================================================+ApiResponse<OrderMargin> TradierBroker::get_order_margins(const BrokerCredentials& /*creds*/,+ const UnifiedOrder& order) {+ return {true, estimate_order_margin(order), "", now_ts()};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/tradier/TradierBroker.h b/fincept-qt/src/trading/brokers/tradier/TradierBroker.hindex 2131de4ca..abd71ca63 100644--- a/fincept-qt/src/trading/brokers/tradier/TradierBroker.h+++ b/fincept-qt/src/trading/brokers/tradier/TradierBroker.h@@ -71,6 +71,9 @@ class TradierBroker : public IBroker {static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);+ // --- Margin Calculator --- Tradier has no per-order margin API → fallback estimator.+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+protected:QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;diff --git a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cppindex 3f16ee070..7ee9054dc 100644--- a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp+++ b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.cpp@@ -539,4 +539,196 @@ ApiResponse<QVector<BrokerCandle>> UpstoxBroker::get_history(const BrokerCredentreturn {true, all_candles, "", ts};}+// ── Multi-Quote ──────────────────────────────────────────────────────────────+// GET /v2/market-quote/quotes?instrument_key=NSE_EQ|INE002A01018,BSE_EQ|...+// Full quote endpoint returns last_price, ohlc, volume, net_change, depth.+// Batches in chunks of 500 (Upstox limit).+ApiResponse<QVector<BrokerQuote>> UpstoxBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {++ QVector<BrokerQuote> all_quotes;+ constexpr int kBatchSize = 500;++ for (int start = 0; start < symbols.size(); start += kBatchSize) {+ int end = std::min<int>(start + kBatchSize, static_cast<int>(symbols.size()));++ QStringList keys;+ keys.reserve(end - start);+ for (int i = start; i < end; ++i) {+ const auto& [sym, exch] = symbols[i];+ keys.append(instrument_key(sym, exch.isEmpty() ? "NSE" : exch, creds.broker_id));+ }++ const QString url = "https://api.upstox.com/v2/market-quote/quotes?instrument_key=" + keys.join(",");+ auto& http = BrokerHttp::instance();+ auto resp = http.get(url, auth_headers(creds));+ int64_t ts = now_ts();++ if (!resp.success || resp.json.value("status").toString() != "success")+ return {false, std::nullopt, checked_error(resp, "get_multi_quotes failed"), ts};++ const auto data = resp.json.value("data").toObject();+ for (auto it = data.constBegin(); it != data.constEnd(); ++it) {+ const auto entry = it.value().toObject();+ const auto ohlc = entry.value("ohlc").toObject();++ BrokerQuote q;+ q.symbol = entry.value("symbol").toString();+ if (q.symbol.isEmpty()) {+ const QString key = it.key();+ if (key.contains('|'))+ q.symbol = key.section('|', 1);+ else+ q.symbol = key;+ }+ q.ltp = entry.value("last_price").toDouble();+ q.open = ohlc.value("open").toDouble();+ q.high = ohlc.value("high").toDouble();+ q.low = ohlc.value("low").toDouble();+ q.close = ohlc.value("close").toDouble();+ q.volume = entry.value("volume").toDouble();+ q.change = entry.value("net_change").toDouble();+ q.change_pct = q.close > 0 ? (q.change / q.close) * 100.0 : 0.0;++ // Best bid/ask from depth+ const auto depth = entry.value("depth").toObject();+ const auto buy_arr = depth.value("buy").toArray();+ const auto sell_arr = depth.value("sell").toArray();+ if (!buy_arr.isEmpty()) {+ auto b0 = buy_arr.first().toObject();+ q.bid = b0.value("price").toDouble();+ q.bid_size = b0.value("quantity").toDouble();+ }+ if (!sell_arr.isEmpty()) {+ auto s0 = sell_arr.first().toObject();+ q.ask = s0.value("price").toDouble();+ q.ask_size = s0.value("quantity").toDouble();+ }++ q.oi = static_cast<qint64>(entry.value("oi").toDouble());+ q.timestamp = now_ts();+ all_quotes.append(q);+ }+ }++ return {true, all_quotes, "", now_ts()};+}++// ── Market Depth ─────────────────────────────────────────────────────────────+// GET /v2/market-quote/quotes?instrument_key=... — parse the depth field+// Returns 5 levels of bid/ask with price, quantity, orders.+ApiResponse<MarketDepth> UpstoxBroker::get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) {++ const QString exch = exchange.isEmpty() ? "NSE" : exchange;+ const QString ikey = instrument_key(symbol, exch, creds.broker_id);+ const QString url = "https://api.upstox.com/v2/market-quote/quotes?instrument_key=" + ikey;++ auto& http = BrokerHttp::instance();+ auto resp = http.get(url, auth_headers(creds));+ int64_t ts = now_ts();++ if (!resp.success || resp.json.value("status").toString() != "success")+ return {false, std::nullopt, checked_error(resp, "get_market_depth failed"), ts};++ const auto data = resp.json.value("data").toObject();+ if (data.isEmpty())+ return {false, std::nullopt, "No data returned for " + ikey, ts};++ // Take the first (and only) entry+ const auto entry = data.begin()->toObject();++ MarketDepth md;+ md.symbol = symbol;+ md.exchange = exch;+ md.ltp = entry.value("last_price").toDouble();+ md.volume = entry.value("volume").toDouble();+ md.oi = entry.value("oi").toDouble();++ const auto depth = entry.value("depth").toObject();++ const auto buy_arr = depth.value("buy").toArray();+ for (const auto& level : buy_arr) {+ auto lv = level.toObject();+ DepthLevel dl;+ dl.price = lv.value("price").toDouble();+ dl.quantity = lv.value("quantity").toInt();+ dl.orders = lv.value("orders").toInt();+ md.bids.append(dl);+ }++ const auto sell_arr = depth.value("sell").toArray();+ for (const auto& level : sell_arr) {+ auto lv = level.toObject();+ DepthLevel dl;+ dl.price = lv.value("price").toDouble();+ dl.quantity = lv.value("quantity").toInt();+ dl.orders = lv.value("orders").toInt();+ md.asks.append(dl);+ }++ return {true, md, "", ts};+}++// ============================================================================+// Pre-trade margin calculator — POST /v2/charges/margin (native)+// Mirrors OpenAlgo broker/upstox/api/margin_api.py + mapping/margin_data.py.+// Payload: {"instruments":[{instrument_key, quantity, transaction_type,+// product, price?}]}+// Response: {"status":"success","data":{required_margin, final_margin,+// margins:[{span_margin, exposure_margin}, ...]}}+// ============================================================================+ApiResponse<OrderMargin> UpstoxBroker::get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) {+ int64_t ts = now_ts();++ QJsonObject leg;+ leg["instrument_key"] = instrument_key(order.symbol, order.exchange, creds.broker_id);+ leg["quantity"] = static_cast<int>(order.quantity);+ leg["transaction_type"] = order.side == OrderSide::Buy ? "BUY" : "SELL";+ leg["product"] = upstox_enum_map().product_or(order.product_type, "I");+ if (order.price > 0)+ leg["price"] = order.price;++ QJsonObject payload{{"instruments", QJsonArray{leg}}};++ auto resp = BrokerHttp::instance().post_json("https://api.upstox.com/v2/charges/margin", payload,+ auth_headers(creds));+ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, "Network error"), ts};+ if (is_token_expired(resp))+ return {false, std::nullopt, "[TOKEN_EXPIRED]", ts};+ if (resp.json.value("status").toString() != "success")+ return {false, std::nullopt, checked_error(resp, "Margin calculation failed"), ts};++ const auto data = resp.json.value("data").toObject();++ OrderMargin m;+ m.symbol = order.symbol;+ m.exchange = order.exchange;+ m.side = order.side == OrderSide::Buy ? "BUY" : "SELL";+ m.quantity = order.quantity;+ m.price = order.price;+ m.total = data.value("required_margin").toDouble();++ // Aggregate SPAN / Exposure across instrument breakdown entries.+ double span = 0.0, exposure = 0.0;+ for (const auto& v : data.value("margins").toArray()) {+ const auto mo = v.toObject();+ span += mo.value("span_margin").toDouble();+ exposure += mo.value("exposure_margin").toDouble();+ }+ m.var_margin = span; // SPAN (F&O); 0 for cash+ m.elm = exposure; // Exposure margin+ m.cash = m.total - span - exposure;+ if (m.cash < 0.0)+ m.cash = 0.0;++ const double notional = order.price * order.quantity;+ if (m.total > 0.0 && notional > 0.0)+ m.leverage = notional / m.total;+ return {true, m, "", ts};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.h b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.hindex 8b72641cb..fb51d4e3a 100644--- a/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.h+++ b/fincept-qt/src/trading/brokers/upstox/UpstoxBroker.h@@ -9,6 +9,7 @@ class UpstoxBroker : public IBroker {BrokerId id() const override { return BrokerId::Upstox; }const char* name() const override { return "Upstox"; }const char* base_url() const override { return "https://api.upstox.com/v2"; }+ const char* ws_adapter_name() const override { return "upstox"; }BrokerProfile profile() const override {return BrokerProfile{@@ -59,6 +60,18 @@ class UpstoxBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // --- Multi-quote & Market Depth ---+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) override;++ // --- Margin Calculator --- POST /v2/charges/margin (native)+ ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;+static bool is_token_expired(const BrokerHttpResponse& resp);static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cppindex 862bd6b76..b6e4d015e 100644--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp@@ -11,6 +11,9 @@#include <QJsonArray>#include <QJsonDocument>+#include <algorithm>+#include <cmath>+namespace fincept::trading {QString ZerodhaBroker::kite_login_url(const QString& api_key) {@@ -605,7 +608,76 @@ static GttOrder parse_gtt(const QJsonObject& o) {}GttPlaceResponse ZerodhaBroker::gtt_place(const BrokerCredentials& creds, const GttOrder& order) {- auto resp = BrokerHttp::instance().post_json(QString(base_url()) + "/gtt/triggers", build_gtt_body(order),+ // ── Market-Price-Protection (MPP) ────────────────────────────────────────+ // Zerodha's GTT infrastructure sends a regular order when the trigger fires.+ // If the order_type is MARKET, the execution price is unbounded — a flash+ // crash or spike can fill at an extreme price far from the trigger level.+ //+ // MPP converts Market legs to Limit with a protective buffer:+ // buffer = max(5% of LTP, 5 × tick_size)+ // BUY → limit_price = LTP + buffer (ceiling)+ // SELL → limit_price = LTP - buffer (floor, min 0)+ //+ // This gives the order enough room to fill under normal volatility while+ // capping the worst-case slippage. If the symbol's tick_size is available+ // from InstrumentService we use it; otherwise we fall back to the NSE+ // default of 0.05.+ GttOrder mpp_order = order;+ bool applied_mpp = false;++ for (auto& trigger : mpp_order.triggers) {+ if (trigger.order_type != OrderType::Market)+ continue;++ // Fetch LTP via the quote endpoint+ double ltp = mpp_order.last_price;+ if (ltp <= 0.0) {+ // Try to get a live quote for the symbol+ QVector<QString> syms = {(mpp_order.exchange.isEmpty() ? "NSE" : mpp_order.exchange) + ":" + mpp_order.symbol};+ auto quote_resp = get_quotes(creds, syms);+ if (quote_resp.success && quote_resp.data.has_value() && !quote_resp.data->isEmpty())+ ltp = quote_resp.data->first().ltp;+ }+ if (ltp <= 0.0) {+ LOG_WARN("Zerodha", QString("GTT MPP: could not determine LTP for %1 — sending Market as-is")+ .arg(mpp_order.symbol));+ continue;+ }++ // Determine tick_size from InstrumentService (fall back to 0.05)+ double tick = 0.05;+ auto inst = InstrumentService::instance().find(mpp_order.symbol, mpp_order.exchange.isEmpty() ? "NSE" : mpp_order.exchange, "zerodha");+ if (inst.has_value() && inst->tick_size > 0)+ tick = inst->tick_size;++ // buffer = max(5% of LTP, 5 × tick_size)+ const double buffer = std::max(ltp * 0.05, 5.0 * tick);++ // Convert to Limit with protective price+ trigger.order_type = OrderType::Limit;+ if (trigger.side == OrderSide::Buy)+ trigger.limit_price = ltp + buffer;+ else+ trigger.limit_price = std::max(0.0, ltp - buffer);++ // Round to tick size+ if (tick > 0)+ trigger.limit_price = std::round(trigger.limit_price / tick) * tick;++ applied_mpp = true;+ LOG_INFO("Zerodha", QString("GTT MPP: %1 %2 Market→Limit @ %3 (LTP=%4, buffer=%5, tick=%6)")+ .arg(mpp_order.symbol)+ .arg(trigger.side == OrderSide::Buy ? "BUY" : "SELL")+ .arg(trigger.limit_price, 0, 'f', 2)+ .arg(ltp, 0, 'f', 2)+ .arg(buffer, 0, 'f', 2)+ .arg(tick, 0, 'f', 4));+ }++ if (applied_mpp)+ mpp_order.last_price = mpp_order.last_price > 0 ? mpp_order.last_price : 0;++ auto resp = BrokerHttp::instance().post_json(QString(base_url()) + "/gtt/triggers", build_gtt_body(mpp_order),auth_headers(creds));if (!resp.success || resp.json.value("status").toString() != "success")return {false, "", checked_error(resp, "GTT place failed")};@@ -650,4 +722,129 @@ ApiResponse<QJsonObject> ZerodhaBroker::gtt_cancel(const BrokerCredentials& credreturn {true, resp.json, "", ts};}+// ============================================================================+// Multi-Quote & Market Depth — Zerodha /quote endpoint+// ============================================================================++ApiResponse<QVector<BrokerQuote>> ZerodhaBroker::get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) {++ QVector<BrokerQuote> all_quotes;+ constexpr int kBatchSize = 500;++ for (int start = 0; start < symbols.size(); start += kBatchSize) {+ int end = std::min<int>(start + kBatchSize, static_cast<int>(symbols.size()));++ // Build query string: ?i=EXCHANGE:SYMBOL&i=...+ QString query;+ for (int i = start; i < end; ++i) {+ const auto& [sym, exch] = symbols[i];+ // Try InstrumentService for broker-specific symbol; fall back to raw+ auto br_sym = InstrumentService::instance().to_brsymbol(sym, exch, "zerodha");+ QString key = (exch.isEmpty() ? "NSE" : exch) + ":" + (br_sym.has_value() ? br_sym.value() : sym);+ if (!query.isEmpty())+ query += "&i=";+ query += key;+ }++ auto resp = BrokerHttp::instance().get(+ QString(base_url()) + "/quote?i=" + query, auth_headers(creds));+ int64_t ts = now_ts();++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, resp.error), ts};++ auto data = resp.json.value("data").toObject();+ for (auto it = data.constBegin(); it != data.constEnd(); ++it) {+ auto q_obj = it.value().toObject();+ BrokerQuote q;+ q.symbol = it.key();+ q.ltp = q_obj.value("last_price").toDouble();+ auto ohlc = q_obj.value("ohlc").toObject();+ q.open = ohlc.value("open").toDouble();+ q.high = ohlc.value("high").toDouble();+ q.low = ohlc.value("low").toDouble();+ q.close = ohlc.value("close").toDouble();+ q.volume = q_obj.value("volume").toDouble();+ q.change = q_obj.value("net_change").toDouble();+ q.change_pct = q.close > 0 ? (q.change / q.close) * 100.0 : 0.0;++ auto depth = q_obj.value("depth").toObject();+ const auto buy_arr = depth.value("buy").toArray();+ const auto sell_arr = depth.value("sell").toArray();+ auto buy0 = buy_arr.isEmpty() ? QJsonObject{} : buy_arr.first().toObject();+ auto sell0 = sell_arr.isEmpty() ? QJsonObject{} : sell_arr.first().toObject();+ q.bid = buy0.value("price").toDouble();+ q.bid_size = buy0.value("quantity").toDouble();+ q.ask = sell0.value("price").toDouble();+ q.ask_size = sell0.value("quantity").toDouble();++ q.oi = static_cast<qint64>(q_obj.value("oi").toDouble());+ const double oi_high = q_obj.value("oi_day_high").toDouble();+ const double oi_low = q_obj.value("oi_day_low").toDouble();+ if (oi_high > 0)+ q.oi_change_pct = ((static_cast<double>(q.oi) - oi_low) / oi_high) * 100.0;++ all_quotes.append(q);+ }+ }++ return {true, all_quotes, "", now_ts()};+}++ApiResponse<MarketDepth> ZerodhaBroker::get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) {++ // Resolve broker-specific symbol+ auto br_sym = InstrumentService::instance().to_brsymbol(symbol, exchange, "zerodha");+ QString exch = exchange.isEmpty() ? "NSE" : exchange;+ QString key = exch + ":" + (br_sym.has_value() ? br_sym.value() : symbol);++ auto resp = BrokerHttp::instance().get(+ QString(base_url()) + "/quote?i=" + key, auth_headers(creds));+ int64_t ts = now_ts();++ if (!resp.success)+ return {false, std::nullopt, checked_error(resp, resp.error), ts};++ auto data = resp.json.value("data").toObject();+ auto q_obj = data.value(key).toObject();+ if (q_obj.isEmpty())+ return {false, std::nullopt, "No data returned for " + key, ts};++ MarketDepth md;+ md.symbol = symbol;+ md.exchange = exch;+ md.ltp = q_obj.value("last_price").toDouble();+ md.volume = q_obj.value("volume").toDouble();+ md.oi = q_obj.value("oi").toDouble();++ auto depth = q_obj.value("depth").toObject();++ // Parse 5-level bid/ask depth+ const auto buy_arr = depth.value("buy").toArray();+ for (const auto& level : buy_arr) {+ auto lv = level.toObject();+ DepthLevel dl;+ dl.price = lv.value("price").toDouble();+ dl.quantity = lv.value("quantity").toInt();+ dl.orders = lv.value("orders").toInt();+ md.bids.append(dl);+ }++ const auto sell_arr = depth.value("sell").toArray();+ for (const auto& level : sell_arr) {+ auto lv = level.toObject();+ DepthLevel dl;+ dl.price = lv.value("price").toDouble();+ dl.quantity = lv.value("quantity").toInt();+ dl.orders = lv.value("orders").toInt();+ md.asks.append(dl);+ }++ return {true, md, "", ts};+}+} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.h b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.hindex 629258dbf..c71be49fc 100644--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.h+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.h@@ -77,6 +77,15 @@ class ZerodhaBroker : public IBroker {const QString& resolution, const QString& from_date,const QString& to_date) override;+ // --- Multi-quote & Market Depth ---+ ApiResponse<QVector<BrokerQuote>> get_multi_quotes(+ const BrokerCredentials& creds,+ const QVector<QPair<QString, QString>>& symbols) override;++ ApiResponse<MarketDepth> get_market_depth(+ const BrokerCredentials& creds,+ const QString& symbol, const QString& exchange) override;+// --- Margin ---ApiResponse<OrderMargin> get_order_margins(const BrokerCredentials& creds, const UnifiedOrder& order) override;ApiResponse<BasketMargin> get_basket_margins(const BrokerCredentials& creds,diff --git a/fincept-qt/src/trading/websocket/AliceBlueWebSocket.cpp b/fincept-qt/src/trading/websocket/AliceBlueWebSocket.cppnew file mode 100644index 000000000..c8d510fd6--- /dev/null+++ b/fincept-qt/src/trading/websocket/AliceBlueWebSocket.cpp@@ -0,0 +1,26 @@+#include "trading/websocket/AliceBlueWebSocket.h"++#include <QCryptographicHash>++namespace fincept::trading {++AliceBlueWebSocket::AliceBlueWebSocket(const QString& client_id, const QString& jwt, QObject* parent)+ // user_id / account_id are passed as the bare client_id; connect_uid() /+ // connect_actid() append "_API" for the actual frame. The raw susertoken+ // is the JWT, double-hashed in derive_susertoken().+ : NorenWebSocket(QString::fromLatin1(kWsUrl), client_id, client_id, jwt, parent),+ client_id_(client_id) {+ set_default_exchange("NSE");+}++QString AliceBlueWebSocket::derive_susertoken(const QString& raw) const {+ // susertoken = SHA256(SHA256(jwt)) as lowercase hex, matching the official+ // AliceBlue client: first hash the JWT, then hash the hex digest string.+ const QByteArray first =+ QCryptographicHash::hash(raw.toUtf8(), QCryptographicHash::Sha256).toHex();+ const QByteArray second =+ QCryptographicHash::hash(first, QCryptographicHash::Sha256).toHex();+ return QString::fromLatin1(second);+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/AliceBlueWebSocket.h b/fincept-qt/src/trading/websocket/AliceBlueWebSocket.hnew file mode 100644index 000000000..5fc48564f--- /dev/null+++ b/fincept-qt/src/trading/websocket/AliceBlueWebSocket.h@@ -0,0 +1,40 @@+#pragma once+#include "trading/websocket/NorenWebSocket.h"++#include <QObject>+#include <QString>++namespace fincept::trading {++/// AliceBlueWebSocket — Noren streaming adapter for AliceBlue.+///+/// AliceBlue runs the standard NorenWS protocol (see NorenWebSocket) with two+/// broker-specific quirks handled here:+/// 1. susertoken = SHA256(SHA256(jwt)) hex (the raw session token is the+/// login JWT; the WS connect frame wants the double-hashed digest).+/// 2. uid / actid in the connect frame are "<client_id>_API".+///+/// Usage:+/// auto* ws = new AliceBlueWebSocket(client_id, jwt, this);+/// connect(ws, &AliceBlueWebSocket::tick_received, this, &MyWidget::on_tick);+/// ws->subscribe({"NSE|22", "NSE|2885"});+/// ws->open();+class AliceBlueWebSocket : public NorenWebSocket {+ Q_OBJECT+ public:+ /// @param client_id numeric UCC / client id (used for uid + actid)+ /// @param jwt login JWT session token (hashed for susertoken)+ AliceBlueWebSocket(const QString& client_id, const QString& jwt, QObject* parent = nullptr);++ protected:+ QString derive_susertoken(const QString& raw) const override;+ QString connect_uid() const override { return client_id_ + "_API"; }+ QString connect_actid() const override { return client_id_ + "_API"; }++ private:+ QString client_id_;++ static constexpr const char* kWsUrl = "wss://ws1.aliceblueonline.com/NorenWS/";+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/BrokerWebSocketBase.cpp b/fincept-qt/src/trading/websocket/BrokerWebSocketBase.cppnew file mode 100644index 000000000..8d90406a2--- /dev/null+++ b/fincept-qt/src/trading/websocket/BrokerWebSocketBase.cpp@@ -0,0 +1,79 @@+#include "trading/websocket/BrokerWebSocketBase.h"++namespace fincept::trading {++BrokerWebSocketBase::BrokerWebSocketBase(QObject* parent) : QObject(parent) {+ subscribe_debounce_.setSingleShot(true);+ subscribe_debounce_.setInterval(kSubscribeDebounceMs);+ connect(&subscribe_debounce_, &QTimer::timeout, this, [this]() { flush_subscribe_queue(); });++ connect(&health_timer_, &QTimer::timeout, this, [this]() {+ if (last_tick_ms_ == 0)+ return; // no ticks yet — connection may still be establishing+ qint64 now = QDateTime::currentMSecsSinceEpoch();+ if ((now - last_tick_ms_) > health_timeout_ms_) {+ emit error_occurred(QStringLiteral("Data stall: no ticks for %1ms").arg(now - last_tick_ms_));+ on_data_stall();+ }+ });+}++BrokerQuote BrokerWebSocketBase::merge_tick(const QString& key, const BrokerQuote& partial) {+ auto it = tick_cache_.find(key);+ if (it == tick_cache_.end()) {+ tick_cache_.insert(key, partial);+ return partial;+ }+ BrokerQuote& cached = it.value();+ if (partial.ltp != 0) cached.ltp = partial.ltp;+ if (partial.open != 0) cached.open = partial.open;+ if (partial.high != 0) cached.high = partial.high;+ if (partial.low != 0) cached.low = partial.low;+ if (partial.close != 0) cached.close = partial.close;+ if (partial.volume != 0) cached.volume = partial.volume;+ if (partial.change != 0) cached.change = partial.change;+ if (partial.change_pct != 0) cached.change_pct = partial.change_pct;+ if (partial.bid != 0) cached.bid = partial.bid;+ if (partial.ask != 0) cached.ask = partial.ask;+ if (partial.bid_size != 0) cached.bid_size = partial.bid_size;+ if (partial.ask_size != 0) cached.ask_size = partial.ask_size;+ if (partial.oi != 0) cached.oi = partial.oi;+ if (!partial.symbol.isEmpty()) cached.symbol = partial.symbol;+ if (partial.timestamp != 0) cached.timestamp = partial.timestamp;+ return cached;+}++void BrokerWebSocketBase::clear_tick_cache() {+ tick_cache_.clear();+}++void BrokerWebSocketBase::enqueue_subscribe(const QVector<qint64>& tokens) {+ for (qint64 t : tokens) {+ if (!subscribe_queue_.contains(t))+ subscribe_queue_.append(t);+ }+ if (!subscribe_debounce_.isActive())+ subscribe_debounce_.start();+}++QVector<qint64> BrokerWebSocketBase::take_subscribe_queue() {+ QVector<qint64> out = subscribe_queue_;+ subscribe_queue_.clear();+ return out;+}++void BrokerWebSocketBase::note_tick() {+ last_tick_ms_ = QDateTime::currentMSecsSinceEpoch();+}++void BrokerWebSocketBase::start_health_check(int interval_ms, int timeout_ms) {+ health_timeout_ms_ = timeout_ms;+ last_tick_ms_ = 0;+ health_timer_.start(interval_ms);+}++void BrokerWebSocketBase::stop_health_check() {+ health_timer_.stop();+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/BrokerWebSocketBase.h b/fincept-qt/src/trading/websocket/BrokerWebSocketBase.hnew file mode 100644index 000000000..59c8b7669--- /dev/null+++ b/fincept-qt/src/trading/websocket/BrokerWebSocketBase.h@@ -0,0 +1,82 @@+#pragma once+// BrokerWebSocketBase — shared infrastructure for broker WebSocket adapters.+//+// WebSocketClient (network/websocket) already provides QWebSocket wrapping and+// auto-reconnect. This base adds the broker-streaming concerns that are common+// across adapters: partial-tick merging (preserve last non-zero OHLC fields),+// subscribe debounce (coalesce rapid subscribe calls into one batch), and a+// data-stall health check (force reconnect if no ticks for N seconds).+//+// Concrete adapters subclass this, hold a WebSocketClient*, and implement the+// broker-specific wire protocol. They emit tick_received / depth_received.++#include "trading/TradingTypes.h"++#include <QObject>+#include <QTimer>+#include <QHash>+#include <QVector>+#include <QDateTime>++namespace fincept::trading {++class BrokerWebSocketBase : public QObject {+ Q_OBJECT+ public:+ explicit BrokerWebSocketBase(QObject* parent = nullptr);+ ~BrokerWebSocketBase() override = default;++ virtual void open() = 0;+ virtual void close() = 0;+ virtual bool is_connected() const = 0;++ // Token-based subscribe (Zerodha-style integer tokens). Symbol-based+ // adapters expose their own overloads alongside these.+ virtual void subscribe(const QVector<qint64>& tokens) = 0;+ virtual void unsubscribe() = 0;++ signals:+ void tick_received(const fincept::trading::BrokerQuote& quote);+ void depth_received(const fincept::trading::MarketDepth& depth);+ void connected();+ void disconnected();+ void error_occurred(const QString& error);++ protected:+ // --- Partial tick merging ---+ // Many brokers send incremental ticks where unchanged fields arrive as 0.+ // merge_tick caches the last full tick per key and overlays only non-zero+ // fields so downstream consumers always see a complete quote.+ BrokerQuote merge_tick(const QString& key, const BrokerQuote& partial);+ void clear_tick_cache();++ // --- Subscribe debounce ---+ // Collect tokens for `debounce_ms` then flush as a single batch. Subclass+ // implements flush_subscribe_queue() to send the actual wire message.+ void enqueue_subscribe(const QVector<qint64>& tokens);+ virtual void flush_subscribe_queue() {}+ QVector<qint64> take_subscribe_queue();++ // --- Health check (data stall detection) ---+ // Call note_tick() on every inbound tick. start_health_check arms a timer+ // that calls on_data_stall() (default: emit error + nothing) when no tick+ // has arrived within timeout_ms. Subclass overrides on_data_stall() to+ // force a reconnect.+ void note_tick();+ void start_health_check(int interval_ms = 30000, int timeout_ms = 90000);+ void stop_health_check();+ virtual void on_data_stall() {}++ private:+ QHash<QString, BrokerQuote> tick_cache_;++ QTimer subscribe_debounce_;+ QVector<qint64> subscribe_queue_;+ static constexpr int kSubscribeDebounceMs = 500;++ QTimer health_timer_;+ qint64 last_tick_ms_ = 0;+ int health_timeout_ms_ = 90000;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/DhanWebSocket.cpp b/fincept-qt/src/trading/websocket/DhanWebSocket.cppnew file mode 100644index 000000000..206280c3f--- /dev/null+++ b/fincept-qt/src/trading/websocket/DhanWebSocket.cpp@@ -0,0 +1,489 @@+// DhanWebSocket — Dhan binary market-data streaming adapter.+//+// See the header for the protocol summary. Byte offsets below are transcribed+// directly from the authoritative struct.unpack format strings in+// broker/dhan/streaming/dhan_websocket.py+// All multi-byte fields are little-endian.++#include "trading/websocket/DhanWebSocket.h"++#include "core/logging/Logger.h"+#include "network/websocket/WebSocketClient.h"+#include "trading/instruments/InstrumentService.h"++#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QtEndian>++#include <cstring>++namespace fincept::trading {++static constexpr const char* TAG_DHAN_WS = "DhanWS";++static constexpr const char* kFiveDepthUrl = "wss://api-feed.dhan.co";++// ─────────────────────────────────────────────────────────────────────────────+// Little-endian read helpers (qFromLittleEndian handles unaligned access).+// ─────────────────────────────────────────────────────────────────────────────++quint16 DhanWebSocket::read_u16(const uchar* p) {+ return qFromLittleEndian<quint16>(p);+}++quint32 DhanWebSocket::read_u32(const uchar* p) {+ return qFromLittleEndian<quint32>(p);+}++float DhanWebSocket::read_f32(const uchar* p) {+ // IEEE-754 float is transmitted little-endian; read the raw u32 then bit-cast.+ quint32 bits = qFromLittleEndian<quint32>(p);+ float f;+ std::memcpy(&f, &bits, sizeof(f));+ return f;+}++QString DhanWebSocket::inst_key(const Instrument& i) {+ return i.exchange_segment + QLatin1Char('|') + i.security_id;+}++// ─────────────────────────────────────────────────────────────────────────────+// Segment ↔ exchange mapping (dhan_mapping.py SEGMENT_TO_EXCHANGE / EXCHANGE_MAP)+// ─────────────────────────────────────────────────────────────────────────────++QString DhanWebSocket::segment_code_to_exchange(int code) {+ switch (code) {+ case 0: return QStringLiteral("NSE_INDEX"); // IDX_I (both NSE/BSE index → default NSE)+ case 1: return QStringLiteral("NSE"); // NSE_EQ+ case 2: return QStringLiteral("NFO"); // NSE_FNO+ case 3: return QStringLiteral("CDS"); // NSE_CURRENCY+ case 4: return QStringLiteral("BSE"); // BSE_EQ+ case 5: return QStringLiteral("MCX"); // MCX_COMM+ case 7: return QStringLiteral("BCD"); // BSE_CURRENCY+ case 8: return QStringLiteral("BFO"); // BSE_FNO+ default: return QString();+ }+}++QString DhanWebSocket::exchange_to_segment_string(const QString& exchange) {+ if (exchange == "NSE") return QStringLiteral("NSE_EQ");+ if (exchange == "BSE") return QStringLiteral("BSE_EQ");+ if (exchange == "NFO") return QStringLiteral("NSE_FNO");+ if (exchange == "BFO") return QStringLiteral("BSE_FNO");+ if (exchange == "MCX") return QStringLiteral("MCX_COMM");+ if (exchange == "CDS") return QStringLiteral("NSE_CURRENCY");+ if (exchange == "BCD") return QStringLiteral("BSE_CURRENCY");+ if (exchange == "NSE_INDEX" || exchange == "BSE_INDEX") return QStringLiteral("IDX_I");+ return QStringLiteral("NSE_EQ"); // safe default+}++// ─────────────────────────────────────────────────────────────────────────────+// Construction+// ─────────────────────────────────────────────────────────────────────────────++DhanWebSocket::DhanWebSocket(const QString& access_token, const QString& client_id, QObject* parent)+ : BrokerWebSocketBase(parent), access_token_(access_token), client_id_(client_id) {+ ws_ = new WebSocketClient(this);+ connect(ws_, &WebSocketClient::connected, this, &DhanWebSocket::on_connected);+ connect(ws_, &WebSocketClient::disconnected, this, &DhanWebSocket::on_disconnected);+ connect(ws_, &WebSocketClient::binary_message_received, this, &DhanWebSocket::on_binary_message);+ connect(ws_, &WebSocketClient::error_occurred, this, &DhanWebSocket::error_occurred);+}++// ─────────────────────────────────────────────────────────────────────────────+// Lifecycle+// ─────────────────────────────────────────────────────────────────────────────++void DhanWebSocket::open() {+ // 5-depth endpoint. authType=2 + token + clientId in the query string.+ QString url = QString("%1?version=2&token=%2&clientId=%3&authType=2")+ .arg(QString(kFiveDepthUrl), access_token_, client_id_);+ LOG_INFO(TAG_DHAN_WS, "Connecting to Dhan 5-depth feed");+ ws_->connect_to(url);+ start_health_check();+}++void DhanWebSocket::close() {+ stop_health_check();+ // Dhan honours a JSON disconnect request before the socket teardown.+ if (ws_->is_connected()) {+ QJsonObject msg;+ msg["RequestCode"] = kReqDisconnect;+ ws_->send(QJsonDocument(msg).toJson(QJsonDocument::Compact));+ }+ ws_->disconnect();+}++bool DhanWebSocket::is_connected() const {+ return ws_->is_connected();+}++// ─────────────────────────────────────────────────────────────────────────────+// Public subscribe API+// ─────────────────────────────────────────────────────────────────────────────++void DhanWebSocket::subscribe(const QVector<Instrument>& instruments) {+ QVector<Instrument> fresh;+ for (const Instrument& inst : instruments) {+ if (inst.security_id.isEmpty())+ continue;+ const QString key = inst_key(inst);+ if (!subscribed_.contains(key)) {+ subscribed_.insert(key, inst);+ fresh.append(inst);+ }+ }+ if (fresh.isEmpty())+ return;++ // Coalesce rapid subscribe calls via the base-class debounce; the wire send+ // happens in flush_subscribe_queue(). We can't push Instrument structs+ // through the qint64 queue, so we just arm the debounce with the security+ // ids and rebuild the pending set from subscribed_ on flush.+ QVector<qint64> token_hint;+ token_hint.reserve(fresh.size());+ for (const Instrument& inst : fresh)+ token_hint.append(inst.security_id.toLongLong());+ enqueue_subscribe(token_hint);+}++void DhanWebSocket::subscribe(const QVector<qint64>& tokens) {+ auto& svc = InstrumentService::instance();+ QVector<Instrument> instruments;+ instruments.reserve(tokens.size());+ for (qint64 token : tokens) {+ Instrument inst;+ inst.security_id = QString::number(token);+ inst.exchange_segment = default_segment_;+ auto found = svc.find_by_token(static_cast<quint32>(token), "dhan");+ if (found.has_value()) {+ const QString& ex = found->exchange.isEmpty() ? found->brexchange : found->exchange;+ if (!ex.isEmpty())+ inst.exchange_segment = exchange_to_segment_string(ex);+ }+ instruments.append(inst);+ }+ subscribe(instruments);+}++void DhanWebSocket::unsubscribe() {+ // Dhan has no real unsubscribe — sending the subscribe request again with a+ // different RequestCode does not retire a feed. We mirror the OpenAlgo+ // adapter: drop local tracking and clear the merge cache. The upstream feed+ // stops when the socket closes.+ subscribed_.clear();+ clear_tick_cache();+}++void DhanWebSocket::unsubscribe(const QVector<Instrument>& instruments) {+ for (const Instrument& inst : instruments)+ subscribed_.remove(inst_key(inst));+}++// ─────────────────────────────────────────────────────────────────────────────+// Base-class hooks+// ─────────────────────────────────────────────────────────────────────────────++void DhanWebSocket::flush_subscribe_queue() {+ // The qint64 queue is only used to drive the debounce timer; the source of+ // truth is subscribed_. Drain the queue and (re)send the full set so a+ // burst of subscribe() calls collapses into batched FULL requests.+ take_subscribe_queue();+ if (subscribed_.isEmpty() || !is_connected())+ return;+ send_subscribe(subscribed_.values().toVector(), /*subscribe=*/true);+}++void DhanWebSocket::on_data_stall() {+ LOG_WARN(TAG_DHAN_WS, "Data stall — forcing reconnect");+ ws_->disconnect();+ open();+}++// ─────────────────────────────────────────────────────────────────────────────+// Slots+// ─────────────────────────────────────────────────────────────────────────────++void DhanWebSocket::on_connected() {+ LOG_INFO(TAG_DHAN_WS, "Connected — resubscribing all instruments");+ resubscribe_all();+ emit connected();+}++void DhanWebSocket::on_disconnected() {+ LOG_WARN(TAG_DHAN_WS, "Disconnected");+ emit disconnected();+}++void DhanWebSocket::on_binary_message(const QByteArray& data) {+ note_tick(); // any inbound frame (even a heartbeat) keeps the watchdog happy++ const uchar* buf = reinterpret_cast<const uchar*>(data.constData());+ const int total = data.size();+ int offset = 0;++ // A single frame may pack multiple response packets back-to-back.+ while (offset + 8 <= total) {+ const uchar* hdr = buf + offset;+ const int response_code = int(hdr[0]);+ const int message_length = int(read_u16(hdr + 1)); // total incl. 8-byte header+ const int exchange_segment = int(hdr[3]);+ const quint32 security_id = read_u32(hdr + 4);++ if (message_length < 8 || offset + message_length > total) {+ // Truncated / malformed packet — stop to avoid reading past the buffer.+ LOG_DEBUG(TAG_DHAN_WS, QString("Incomplete packet (code=%1 len=%2 have=%3)")+ .arg(response_code).arg(message_length).arg(total - offset));+ break;+ }++ const uchar* payload = hdr + 8;+ const int payload_len = message_length - 8;+ const QString fallback = QString::number(security_id);++ switch (response_code) {+ case 2: { // TICKER (8B payload: ltp f32, ltt u32)+ BrokerQuote q = parse_ticker(payload, payload_len, exchange_segment, security_id);+ BrokerQuote merged = merge_tick(fallback, q);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit tick_received(merged);+ break;+ }+ case 4: { // QUOTE (42B payload)+ BrokerQuote q = parse_quote(payload, payload_len, exchange_segment, security_id);+ BrokerQuote merged = merge_tick(fallback, q);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit tick_received(merged);+ break;+ }+ case 5: { // OI (4B payload: oi u32)+ if (payload_len >= 4) {+ BrokerQuote q;+ q.symbol = symbol_for_security(security_id, fallback);+ q.oi = qint64(read_u32(payload));+ BrokerQuote merged = merge_tick(fallback, q);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit tick_received(merged);+ }+ break;+ }+ case 6: { // PREV_CLOSE (8B payload: prev_close f32, prev_oi u32)+ if (payload_len >= 4) {+ BrokerQuote q;+ q.symbol = symbol_for_security(security_id, fallback);+ q.close = read_f32(payload); // previous close carried into close field+ BrokerQuote merged = merge_tick(fallback, q);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit tick_received(merged);+ }+ break;+ }+ case 8: { // FULL (154B payload: quote + 5-level depth)+ MarketDepth depth;+ bool has_depth = false;+ BrokerQuote q =+ parse_full(payload, payload_len, exchange_segment, security_id, depth, has_depth);+ BrokerQuote merged = merge_tick(fallback, q);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit tick_received(merged);+ if (has_depth)+ emit depth_received(depth);+ break;+ }+ case 50: // DISCONNECT+ handle_disconnect(payload, payload_len);+ break;+ case 0: // heartbeat / ack — silently ignore+ break;+ default:+ LOG_DEBUG(TAG_DHAN_WS, QString("Unknown response code: %1").arg(response_code));+ break;+ }++ offset += message_length;+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Wire senders+// ─────────────────────────────────────────────────────────────────────────────++void DhanWebSocket::send_subscribe(const QVector<Instrument>& instruments, bool subscribe) {+ if (instruments.isEmpty() || !is_connected())+ return;++ // Dhan has no real unsubscribe; a "false" request is a no-op upstream. We+ // still gate on it so callers can express intent without spamming the wire.+ if (!subscribe)+ return;++ // Batch into <=100 instruments per FULL subscribe message.+ for (int start = 0; start < instruments.size(); start += kBatchSize) {+ const int end = std::min(start + kBatchSize, int(instruments.size()));+ QJsonArray list;+ for (int j = start; j < end; ++j) {+ QJsonObject entry;+ entry["ExchangeSegment"] = instruments[j].exchange_segment;+ entry["SecurityId"] = instruments[j].security_id;+ list.append(entry);+ }+ QJsonObject msg;+ msg["RequestCode"] = kReqMode; // FULL (21)+ msg["InstrumentCount"] = end - start;+ msg["InstrumentList"] = list;+ ws_->send(QJsonDocument(msg).toJson(QJsonDocument::Compact));+ LOG_INFO(TAG_DHAN_WS, QString("Subscribed %1 instruments (FULL)").arg(end - start));+ }+}++void DhanWebSocket::resubscribe_all() {+ if (subscribed_.isEmpty())+ return;+ send_subscribe(subscribed_.values().toVector(), /*subscribe=*/true);+}++// ─────────────────────────────────────────────────────────────────────────────+// Symbol enrichment+// ─────────────────────────────────────────────────────────────────────────────++QString DhanWebSocket::symbol_for_security(quint32 security_id, const QString& fallback) const {+ auto inst = InstrumentService::instance().find_by_token(security_id, "dhan");+ return inst.has_value() && !inst->symbol.isEmpty() ? inst->symbol : fallback;+}++// ─────────────────────────────────────────────────────────────────────────────+// Binary packet parsers — offsets per dhan_websocket.py+// ─────────────────────────────────────────────────────────────────────────────++BrokerQuote DhanWebSocket::parse_ticker(const uchar* payload, int len, int /*segment*/,+ quint32 security_id) const {+ // _parse_ticker_packet: ltp f32 @0, ltt u32 @4 (epoch seconds).+ BrokerQuote q;+ q.symbol = symbol_for_security(security_id, QString::number(security_id));+ if (len < 8)+ return q;+ q.ltp = read_f32(payload + 0);+ const quint32 ltt = read_u32(payload + 4);+ if (ltt != 0)+ q.timestamp = qint64(ltt) * 1000; // seconds → ms+ return q;+}++BrokerQuote DhanWebSocket::parse_quote(const uchar* payload, int len, int /*segment*/,+ quint32 security_id) const {+ // _parse_quote_packet (42 bytes):+ // ltp f32 @0, ltq u16 @4, ltt u32 @6, atp f32 @10, volume u32 @14,+ // total_sell_qty u32 @18, total_buy_qty u32 @22,+ // open f32 @26, close f32 @30, high f32 @34, low f32 @38.+ BrokerQuote q;+ q.symbol = symbol_for_security(security_id, QString::number(security_id));+ if (len < 42)+ return q;+ q.ltp = read_f32(payload + 0);+ // ltq u16 @4 — no dedicated BrokerQuote field; skip.+ const quint32 ltt = read_u32(payload + 6);+ if (ltt != 0)+ q.timestamp = qint64(ltt) * 1000;+ // atp f32 @10 — average traded price; no BrokerQuote field; skip.+ q.volume = read_u32(payload + 14);+ q.ask_size = read_u32(payload + 18); // total_sell_qty+ q.bid_size = read_u32(payload + 22); // total_buy_qty+ q.open = read_f32(payload + 26);+ q.close = read_f32(payload + 30);+ q.high = read_f32(payload + 34);+ q.low = read_f32(payload + 38);+ return q;+}++BrokerQuote DhanWebSocket::parse_full(const uchar* payload, int len, int segment, quint32 security_id,+ MarketDepth& depth_out, bool& has_depth) const {+ // _parse_full_packet (154 bytes):+ // ltp f32 @0, ltq u16 @4, ltt u32 @6, atp f32 @10, volume u32 @14,+ // total_sell_qty u32 @18, total_buy_qty u32 @22, oi u32 @26,+ // oi_high u32 @30, oi_low u32 @34, open f32 @38, close f32 @42,+ // high f32 @46, low f32 @50, then 5×20-byte depth @54.+ // Each depth level: bid_qty u32, ask_qty u32, bid_orders u16,+ // ask_orders u16, bid_price f32, ask_price f32.+ has_depth = false;+ BrokerQuote q;+ q.symbol = symbol_for_security(security_id, QString::number(security_id));+ if (len < 154)+ return q;++ q.ltp = read_f32(payload + 0);+ // ltq u16 @4 — skip.+ const quint32 ltt = read_u32(payload + 6);+ if (ltt != 0)+ q.timestamp = qint64(ltt) * 1000;+ // atp f32 @10 — skip.+ q.volume = read_u32(payload + 14);+ q.ask_size = read_u32(payload + 18); // total_sell_qty+ q.bid_size = read_u32(payload + 22); // total_buy_qty+ q.oi = qint64(read_u32(payload + 26));+ // oi_high u32 @30, oi_low u32 @34 — no BrokerQuote field; skip.+ q.open = read_f32(payload + 38);+ q.close = read_f32(payload + 42);+ q.high = read_f32(payload + 46);+ q.low = read_f32(payload + 50);++ // 5-level depth at offset 54, 20 bytes per level.+ depth_out.symbol = q.symbol;+ depth_out.exchange = segment_code_to_exchange(segment);+ depth_out.ltp = q.ltp;+ depth_out.volume = q.volume;+ depth_out.oi = double(q.oi);+ depth_out.bids.clear();+ depth_out.asks.clear();+ for (int i = 0; i < 5; ++i) {+ const uchar* lvl = payload + 54 + i * 20;+ const quint32 bid_qty = read_u32(lvl + 0);+ const quint32 ask_qty = read_u32(lvl + 4);+ const quint16 bid_orders = read_u16(lvl + 8);+ const quint16 ask_orders = read_u16(lvl + 10);+ const float bid_price = read_f32(lvl + 12);+ const float ask_price = read_f32(lvl + 16);++ DepthLevel bid;+ bid.price = bid_price;+ bid.quantity = int(bid_qty);+ bid.orders = int(bid_orders);+ depth_out.bids.append(bid);++ DepthLevel ask;+ ask.price = ask_price;+ ask.quantity = int(ask_qty);+ ask.orders = int(ask_orders);+ depth_out.asks.append(ask);+ }+ has_depth = true;++ // Surface best bid/ask on the quote too (level 0 of the book).+ if (!depth_out.bids.isEmpty()) {+ q.bid = depth_out.bids.first().price;+ }+ if (!depth_out.asks.isEmpty()) {+ q.ask = depth_out.asks.first().price;+ }+ return q;+}++void DhanWebSocket::handle_disconnect(const uchar* payload, int len) const {+ if (len < 2) {+ LOG_WARN(TAG_DHAN_WS, "Received disconnect packet (no code)");+ return;+ }+ const quint16 code = read_u16(payload);+ QString reason = QStringLiteral("Unknown reason");+ if (code == 805)+ reason = QStringLiteral("Maximum websocket connections exceeded");+ LOG_WARN(TAG_DHAN_WS, QString("Disconnect packet code=%1 (%2)").arg(code).arg(reason));+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/DhanWebSocket.h b/fincept-qt/src/trading/websocket/DhanWebSocket.hnew file mode 100644index 000000000..3be88950f--- /dev/null+++ b/fincept-qt/src/trading/websocket/DhanWebSocket.h@@ -0,0 +1,151 @@+#pragma once+// DhanWebSocket — Dhan market-data streaming adapter (BINARY protocol).+//+// Port of OpenAlgo's dhan_websocket.py + dhan_adapter.py to the Fincept+// BrokerWebSocketBase contract. Dhan pushes little-endian binary frames over a+// standard WebSocket (unlike the JSON-based 5Paisa / Noren feeds).+//+// Reference (authoritative for byte offsets):+// broker/dhan/streaming/dhan_websocket.py (struct.unpack format strings)+// broker/dhan/streaming/dhan_adapter.py (subscribe / normalize logic)+// broker/dhan/streaming/dhan_mapping.py (segment ↔ exchange mapping)+//+// ── Protocol summary ─────────────────────────────────────────────────────────+//+// Two endpoints exist:+// 5-depth : wss://api-feed.dhan.co?version=2&token=TOKEN&clientId=CID&authType=2+// 20-depth : wss://depth-api-feed.dhan.co/twentydepth?token=TOKEN&clientId=CID&authType=2+// Only the 5-depth connection is implemented here; the 20-depth surface is+// stubbed (lazy-init left for a future change) since most consumers want the+// 5-level book that already arrives in the FULL packet.+//+// Subscribe is JSON over the binary socket:+// {"RequestCode":15,"InstrumentCount":n,+// "InstrumentList":[{"ExchangeSegment":"NSE_EQ","SecurityId":"11536"}]}+// RequestCode: 15=TICKER, 17=QUOTE, 21=FULL, 23=20_DEPTH, 12=DISCONNECT.+// We subscribe in FULL (21) mode so a single feed carries LTP + OHLC + depth.+//+// Responses are little-endian binary. 8-byte header per packet:+// byte 0 : response_code (uint8)+// bytes 1-2 : message_length (uint16 LE) — total incl. the 8-byte header+// byte 3 : exchange_segment (uint8)+// bytes 4-7 : security_id (uint32 LE)+// Response codes: 2=TICKER, 4=QUOTE, 5=OI, 6=PREV_CLOSE, 8=FULL, 50=DISCONNECT,+// 0=heartbeat (ignored). Multiple packets may share one frame.++#include "trading/websocket/BrokerWebSocketBase.h"++#include <QHash>+#include <QSet>+#include <QString>+#include <QStringList>+#include <QVector>++namespace fincept {++class WebSocketClient;++namespace trading {++class DhanWebSocket : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// A single instrument to subscribe to. ExchangeSegment is the Dhan string+ /// form ("NSE_EQ", "NSE_FNO", "BSE_EQ", "MCX_COMM", ...); security_id is the+ /// numeric Dhan security id (sent as a string in the subscribe JSON).+ struct Instrument {+ QString exchange_segment; // "NSE_EQ", "NSE_FNO", ...+ QString security_id; // numeric security id as string+ };++ /// @param access_token Dhan OAuth access token (query "token=")+ /// @param client_id Dhan client id (query "clientId=")+ explicit DhanWebSocket(const QString& access_token, const QString& client_id, QObject* parent = nullptr);++ void open() override;+ void close() override;+ bool is_connected() const override;++ /// Symbol/instrument-based subscribe (Dhan native form: segment + securityId).+ /// Subscribes in FULL mode so consumers get quote + 5-level depth. Dedupes.+ void subscribe(const QVector<Instrument>& instruments);++ /// Token-based subscribe (BrokerWebSocketBase contract). Security ids are+ /// resolved to their ExchangeSegment via InstrumentService::find_by_token;+ /// tokens with no mapping fall back to set_default_segment() (default NSE_EQ).+ void subscribe(const QVector<qint64>& tokens) override;++ /// Unsubscribe everything currently subscribed.+ void unsubscribe() override;++ /// Remove a specific set of instruments.+ void unsubscribe(const QVector<Instrument>& instruments);++ /// Default Dhan ExchangeSegment used when a token-based subscribe has no+ /// per-token mapping. Defaults to "NSE_EQ".+ void set_default_segment(const QString& segment) { default_segment_ = segment; }++ // ── Segment ↔ exchange helpers (public for tests / consumers) ────────────+ // Numeric exchange_segment code → Fincept exchange string.+ // 0=IDX, 1=NSE, 2=NFO, 3=CDS, 4=BSE, 5=MCX, 7=BCD, 8=BFO. (dhan_mapping.py)+ static QString segment_code_to_exchange(int code);+ // Fincept exchange string → Dhan ExchangeSegment string ("NSE"→"NSE_EQ").+ static QString exchange_to_segment_string(const QString& exchange);++ protected:+ void flush_subscribe_queue() override;+ void on_data_stall() override;++ private slots:+ void on_connected();+ void on_binary_message(const QByteArray& data);+ void on_disconnected();++ private:+ // Wire senders+ void send_subscribe(const QVector<Instrument>& instruments, bool subscribe);+ void resubscribe_all();++ // Binary packet parsing. `payload` excludes the 8-byte header. Each returns+ // a freshly-built BrokerQuote (callers run it through merge_tick()).+ BrokerQuote parse_ticker(const uchar* payload, int len, int segment, quint32 security_id) const;+ BrokerQuote parse_quote(const uchar* payload, int len, int segment, quint32 security_id) const;+ BrokerQuote parse_full(const uchar* payload, int len, int segment, quint32 security_id,+ MarketDepth& depth_out, bool& has_depth) const;+ void handle_disconnect(const uchar* payload, int len) const;++ // Enrich symbol/exchange for a security id via InstrumentService.+ QString symbol_for_security(quint32 security_id, const QString& fallback) const;++ // little-endian readers+ static quint16 read_u16(const uchar* p);+ static quint32 read_u32(const uchar* p);+ static float read_f32(const uchar* p);++ // unique dedupe key for an instrument+ static QString inst_key(const Instrument& i);++ QString access_token_;+ QString client_id_;+ QString default_segment_ = QStringLiteral("NSE_EQ");++ WebSocketClient* ws_ = nullptr;++ // All instruments we want active, keyed by "SEGMENT|SECID".+ QHash<QString, Instrument> subscribed_;++ // Dhan request codes (dhan_websocket.py REQUEST_CODES).+ static constexpr int kReqTicker = 15;+ static constexpr int kReqQuote = 17;+ static constexpr int kReqFull = 21;+ static constexpr int kReqDisconnect = 12;++ // We always subscribe in FULL mode (LTP + OHLC + 5-level depth in one feed).+ static constexpr int kReqMode = kReqFull;++ // Dhan limits: max 100 instruments per subscribe message.+ static constexpr int kBatchSize = 100;+};++} // namespace trading+} // namespace finceptdiff --git a/fincept-qt/src/trading/websocket/FivePaisaWebSocket.cpp b/fincept-qt/src/trading/websocket/FivePaisaWebSocket.cppnew file mode 100644index 000000000..58dd8e3f9--- /dev/null+++ b/fincept-qt/src/trading/websocket/FivePaisaWebSocket.cpp@@ -0,0 +1,328 @@+// FivePaisaWebSocket — 5Paisa JSON market-data streaming adapter.+//+// See the header for the protocol summary. The OpenAlgo reference is+// broker/fivepaisa/streaming/fivepaisa_websocket.py+// broker/fivepaisa/streaming/fivepaisa_adapter.py++#include "trading/websocket/FivePaisaWebSocket.h"++#include "core/logging/Logger.h"+#include "network/websocket/WebSocketClient.h"+#include "trading/instruments/InstrumentService.h"++#include <QByteArray>+#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QJsonValue>+#include <QRegularExpression>++namespace fincept::trading {++static constexpr const char* TAG_FP_WS = "FivePaisaWS";++// 5Paisa redirect-server → feed host. Mirrors WEBSOCKET_URLS in the py source.+static QString host_for_server(const QString& server) {+ if (server == "A")+ return "wss://aopenfeed.5paisa.com/feeds/api/chat";+ if (server == "B")+ return "wss://bopenfeed.5paisa.com/feeds/api/chat";+ if (server == "C")+ return "wss://openfeed.5paisa.com/feeds/api/chat";+ return "wss://openfeed.5paisa.com/Feeds/api/chat"; // default+}++// ─────────────────────────────────────────────────────────────────────────────+// Static helpers+// ─────────────────────────────────────────────────────────────────────────────++QString FivePaisaWebSocket::decode_redirect_server(const QString& access_token) {+ // JWT = header.payload.signature — decode the base64url payload and read+ // the "RedirectServer" claim. Fall back to "default" on any failure.+ QStringList parts = access_token.split('.');+ if (parts.size() != 3)+ return QStringLiteral("default");++ QByteArray payload = parts[1].toUtf8();+ // base64url → base64 + padding+ payload.replace('-', '+').replace('_', '/');+ int pad = payload.size() % 4;+ if (pad)+ payload.append(4 - pad, '=');++ QByteArray decoded = QByteArray::fromBase64(payload);+ QJsonParseError err;+ QJsonDocument doc = QJsonDocument::fromJson(decoded, &err);+ if (err.error != QJsonParseError::NoError || !doc.isObject())+ return QStringLiteral("default");++ QString server = doc.object().value("RedirectServer").toString();+ return server.isEmpty() ? QStringLiteral("default") : server;+}++QString FivePaisaWebSocket::feed_url_for_token(const QString& access_token) {+ return host_for_server(decode_redirect_server(access_token));+}++QString FivePaisaWebSocket::fp_exchange(const QString& exchange) {+ if (exchange == "BSE" || exchange == "BFO" || exchange == "BCD")+ return QStringLiteral("B");+ if (exchange == "MCX")+ return QStringLiteral("M");+ return QStringLiteral("N"); // NSE, NFO, CDS+}++QString FivePaisaWebSocket::fp_exchange_type(const QString& exchange) {+ if (exchange == "NFO" || exchange == "BFO" || exchange == "MCX")+ return QStringLiteral("D");+ if (exchange == "CDS" || exchange == "BCD")+ return QStringLiteral("U");+ return QStringLiteral("C"); // NSE, BSE+}++int64_t FivePaisaWebSocket::parse_fp_time(const QString& s) {+ if (s.isEmpty())+ return 0;+ // Format: "/Date(1690000000000)/" or "/Date(1690000000000+0530)/"+ static const QRegularExpression re(QStringLiteral("/Date\\((\\d+)"));+ auto m = re.match(s);+ if (m.hasMatch())+ return m.captured(1).toLongLong();+ return 0;+}++// ─────────────────────────────────────────────────────────────────────────────+// Construction+// ─────────────────────────────────────────────────────────────────────────────++FivePaisaWebSocket::FivePaisaWebSocket(const QString& access_token, const QString& client_code, QObject* parent)+ : BrokerWebSocketBase(parent), access_token_(access_token), client_code_(client_code) {+ ws_ = new WebSocketClient(this);+ connect(ws_, &WebSocketClient::connected, this, &FivePaisaWebSocket::on_connected);+ connect(ws_, &WebSocketClient::disconnected, this, &FivePaisaWebSocket::on_disconnected);+ connect(ws_, &WebSocketClient::message_received, this, &FivePaisaWebSocket::on_text_message);+ connect(ws_, &WebSocketClient::error_occurred, this, &FivePaisaWebSocket::error_occurred);+}++// ─────────────────────────────────────────────────────────────────────────────+// Public API+// ─────────────────────────────────────────────────────────────────────────────++void FivePaisaWebSocket::open() {+ QString url =+ QString("%1?Value1=%2|%3").arg(feed_url_for_token(access_token_), access_token_, client_code_);+ LOG_INFO(TAG_FP_WS, "Connecting to 5Paisa feed");+ ws_->connect_to(url);+ start_health_check();+}++void FivePaisaWebSocket::close() {+ stop_health_check();+ ws_->disconnect();+}++bool FivePaisaWebSocket::is_connected() const {+ return ws_->is_connected();+}++void FivePaisaWebSocket::subscribe(const QVector<qint64>& tokens) {+ QVector<qint64> new_tokens;+ for (qint64 t : tokens) {+ if (!subscribed_tokens_.contains(t)) {+ subscribed_tokens_.insert(t);+ new_tokens.append(t);+ }+ }+ // Coalesce rapid subscribe calls via the base-class debounce. The actual+ // wire send happens in flush_subscribe_queue().+ if (!new_tokens.isEmpty())+ enqueue_subscribe(new_tokens);+}++void FivePaisaWebSocket::unsubscribe() {+ if (subscribed_tokens_.isEmpty())+ return;+ QVector<qint64> all(subscribed_tokens_.begin(), subscribed_tokens_.end());+ if (is_connected())+ send_subscribe(all, /*subscribe=*/false);+ subscribed_tokens_.clear();+ clear_tick_cache();+}++void FivePaisaWebSocket::unsubscribe(const QVector<qint64>& tokens) {+ QVector<qint64> to_remove;+ for (qint64 t : tokens) {+ if (subscribed_tokens_.remove(t))+ to_remove.append(t);+ }+ if (!to_remove.isEmpty() && is_connected())+ send_subscribe(to_remove, /*subscribe=*/false);+}++// ─────────────────────────────────────────────────────────────────────────────+// Base-class hooks+// ─────────────────────────────────────────────────────────────────────────────++void FivePaisaWebSocket::flush_subscribe_queue() {+ QVector<qint64> tokens = take_subscribe_queue();+ if (tokens.isEmpty() || !is_connected())+ return;+ send_subscribe(tokens, /*subscribe=*/true);+}++void FivePaisaWebSocket::on_data_stall() {+ LOG_WARN(TAG_FP_WS, "Data stall — forcing reconnect");+ ws_->disconnect();+ open();+}++// ─────────────────────────────────────────────────────────────────────────────+// Slots+// ─────────────────────────────────────────────────────────────────────────────++void FivePaisaWebSocket::on_connected() {+ LOG_INFO(TAG_FP_WS, "Connected — resubscribing all scrips");+ resubscribe_all();+ emit connected();+}++void FivePaisaWebSocket::on_disconnected() {+ LOG_WARN(TAG_FP_WS, "Disconnected");+ emit disconnected();+}++void FivePaisaWebSocket::on_text_message(const QString& msg) {+ QJsonParseError err;+ QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError) {+ LOG_DEBUG(TAG_FP_WS, QString("Non-JSON message: %1").arg(msg.left(120)));+ return;+ }++ // 5Paisa pushes either a single tick object or an array of tick objects.+ if (doc.isArray()) {+ for (const QJsonValue& v : doc.array()) {+ if (v.isObject())+ handle_tick(v.toObject());+ }+ } else if (doc.isObject()) {+ handle_tick(doc.object());+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Wire senders+// ─────────────────────────────────────────────────────────────────────────────++void FivePaisaWebSocket::send_subscribe(const QVector<qint64>& tokens, bool subscribe) {+ if (tokens.isEmpty())+ return;++ auto& svc = InstrumentService::instance();++ // Build MarketFeedData: one {Exch, ExchType, ScripCode} entry per token.+ QJsonArray feed_data;+ for (qint64 token : tokens) {+ QString exch = QStringLiteral("N");+ QString exch_type = QStringLiteral("C");+ auto inst = svc.find_by_token(static_cast<quint32>(token), "fivepaisa");+ if (inst.has_value()) {+ const QString& ex = inst->exchange.isEmpty() ? inst->brexchange : inst->exchange;+ exch = fp_exchange(ex);+ exch_type = fp_exchange_type(ex);+ }+ QJsonObject scrip;+ scrip["Exch"] = exch;+ scrip["ExchType"] = exch_type;+ scrip["ScripCode"] = static_cast<double>(token);+ feed_data.append(scrip);+ }++ QJsonObject req;+ req["Method"] = QString(kMethodMarketFeed);+ req["Operation"] = subscribe ? QStringLiteral("Subscribe") : QStringLiteral("Unsubscribe");+ req["ClientCode"] = client_code_;+ req["MarketFeedData"] = feed_data;++ ws_->send(QJsonDocument(req).toJson(QJsonDocument::Compact));+ LOG_INFO(TAG_FP_WS, QString("%1 %2 scrips")+ .arg(subscribe ? "Subscribed" : "Unsubscribed")+ .arg(tokens.size()));+}++void FivePaisaWebSocket::resubscribe_all() {+ if (subscribed_tokens_.isEmpty())+ return;+ QVector<qint64> all(subscribed_tokens_.begin(), subscribed_tokens_.end());+ send_subscribe(all, /*subscribe=*/true);+}++// ─────────────────────────────────────────────────────────────────────────────+// Tick handling+// ─────────────────────────────────────────────────────────────────────────────++void FivePaisaWebSocket::handle_tick(const QJsonObject& obj) {+ if (!obj.contains("Token"))+ return; // not a market-data tick (could be an ack/control message)++ note_tick();++ const qint64 token = static_cast<qint64>(obj.value("Token").toDouble());+ const QString key = QString::number(token);++ // Build a partial BrokerQuote from this tick. Fields that are 0 will be+ // back-filled from the cached last-known-good values in merge_tick().+ BrokerQuote partial;+ partial.ltp = obj.value("LastRate").toDouble();+ partial.open = obj.value("OpenRate").toDouble();+ partial.high = obj.value("High").toDouble();+ partial.low = obj.value("Low").toDouble();+ partial.close = obj.value("PClose").toDouble();+ partial.volume = obj.value("TotalQty").toDouble();+ partial.bid = obj.value("BidRate").toDouble();+ partial.ask = obj.value("OffRate").toDouble();+ partial.bid_size = obj.value("BidQty").toDouble();+ partial.ask_size = obj.value("OffQty").toDouble();+ partial.timestamp = parse_fp_time(obj.value("TickDt").toString());++ // Enrich with the normalised symbol (fall back to numeric token).+ auto& svc = InstrumentService::instance();+ auto inst = svc.find_by_token(static_cast<quint32>(token), "fivepaisa");+ partial.symbol = inst.has_value() ? inst->symbol : key;++ // OHLC carryforward — merge against cached non-zero values.+ BrokerQuote merged = merge_tick(key, partial);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();++ emit tick_received(merged);++ // 5-level depth (present in MarketDepthService payloads under "Details").+ if (obj.contains("Details") && obj.value("Details").isArray()) {+ MarketDepth depth;+ depth.symbol = merged.symbol;+ depth.exchange = inst.has_value() ? inst->exchange : QString();+ depth.ltp = merged.ltp;+ depth.volume = merged.volume;++ for (const QJsonValue& dv : obj.value("Details").toArray()) {+ if (!dv.isObject())+ continue;+ QJsonObject d = dv.toObject();+ DepthLevel lvl;+ lvl.price = d.value("Price").toDouble();+ lvl.quantity = d.value("Quantity").toInt();+ lvl.orders = d.value("NumberOfOrders").toInt();+ // BbBuySellFlag: 66 ('B') = buy, 83 ('S') = sell.+ const int flag = d.value("BbBuySellFlag").toInt();+ if (flag == 66 && depth.bids.size() < 5)+ depth.bids.append(lvl);+ else if (flag == 83 && depth.asks.size() < 5)+ depth.asks.append(lvl);+ }+ emit depth_received(depth);+ }+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/FivePaisaWebSocket.h b/fincept-qt/src/trading/websocket/FivePaisaWebSocket.hnew file mode 100644index 000000000..1c3195548--- /dev/null+++ b/fincept-qt/src/trading/websocket/FivePaisaWebSocket.h@@ -0,0 +1,97 @@+#pragma once+// FivePaisaWebSocket — 5Paisa market-data streaming adapter (JSON protocol).+//+// Port of OpenAlgo's fivepaisa_websocket.py + fivepaisa_adapter.py to the+// Fincept BrokerWebSocketBase contract. Unlike Zerodha/Angel One (binary), the+// 5Paisa feed is plain JSON over a standard WebSocket.+//+// Protocol summary:+// 1. WS URL is selected from the "RedirectServer" claim in the JWT access+// token (A/B/C/default → distinct host). Connection URL:+// wss://<host>/feeds/api/chat?Value1=<access_token>|<client_code>+// 2. Subscribe by sending a JSON envelope:+// { "Method":"MarketFeedV3", "Operation":"Subscribe",+// "ClientCode":"<code>", "MarketFeedData":[ {Exch,ExchType,ScripCode} ] }+// 3. Ticks arrive as a JSON object (or array of objects) carrying Token,+// LastRate (ltp), OpenRate, High, Low, PClose, TotalQty (volume),+// BidRate, OffRate (ask), AvgRate, plus 5-level depth under "Details".+// 4. OHLC carryforward: 5Paisa often sends 0 for unchanged fields, so we+// route every tick through merge_tick() to preserve last non-zero values.+//+// Subscription is keyed by numeric ScripCode (= instrument_token). The Exch /+// ExchType wire codes are resolved per-token from InstrumentService (matching+// FivePaisaBroker's fp_exchange / fp_exchange_type mapping).++#include "trading/websocket/BrokerWebSocketBase.h"++#include <QHash>+#include <QSet>+#include <QString>+#include <QVector>++namespace fincept {++class WebSocketClient;++namespace trading {++class FivePaisaWebSocket : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// access_token: JWT login token (also encodes the redirect server).+ /// client_code: demat client code (the third ":::"-delimited part of the+ /// packed ApiKey, falling back to user_id when absent).+ explicit FivePaisaWebSocket(const QString& access_token, const QString& client_code, QObject* parent = nullptr);++ void open() override;+ void close() override;+ bool is_connected() const override;++ /// Subscribe by numeric scrip code (= instrument_token). Exchange code/type+ /// is resolved per token via InstrumentService. Deduplicates internally.+ void subscribe(const QVector<qint64>& tokens) override;++ /// Unsubscribe everything currently subscribed.+ void unsubscribe() override;++ /// Remove a specific set of scrip codes.+ void unsubscribe(const QVector<qint64>& tokens);++ protected:+ void flush_subscribe_queue() override;+ void on_data_stall() override;++ private slots:+ void on_connected();+ void on_text_message(const QString& msg);+ void on_disconnected();++ private:+ // Resolve the host from the JWT "RedirectServer" claim, then build the full+ // connection URL with the Value1 auth query parameter.+ static QString feed_url_for_token(const QString& access_token);+ static QString decode_redirect_server(const QString& access_token);++ // Map a Fincept exchange string to 5Paisa wire codes (matches FivePaisaBroker).+ static QString fp_exchange(const QString& exchange); // N / B / M+ static QString fp_exchange_type(const QString& exchange); // C / D / U++ // Parse the Microsoft "/Date(1690000000000)/" format → epoch ms (0 on failure).+ static int64_t parse_fp_time(const QString& s);++ void send_subscribe(const QVector<qint64>& tokens, bool subscribe);+ void resubscribe_all();+ void handle_tick(const QJsonObject& obj);++ QString access_token_;+ QString client_code_;++ WebSocketClient* ws_;+ QSet<qint64> subscribed_tokens_;++ static constexpr const char* kMethodMarketFeed = "MarketFeedV3";+ static constexpr const char* kMethodMarketDepth = "MarketDepthService";+};++} // namespace trading+} // namespace finceptdiff --git a/fincept-qt/src/trading/websocket/IIFLWebSocket.cpp b/fincept-qt/src/trading/websocket/IIFLWebSocket.cppnew file mode 100644index 000000000..bdef762c1--- /dev/null+++ b/fincept-qt/src/trading/websocket/IIFLWebSocket.cpp@@ -0,0 +1,412 @@+// IIFLWebSocket — IIFL XTS Socket.IO market-data adapter.+//+// See the header for the protocol summary. OpenAlgo references:+// broker/iifl/streaming/iifl_websocket.py+// broker/iifl/streaming/iifl_adapter.py+// broker/iifl/streaming/iifl_mapping.py (exchange segment codes)++#include "trading/websocket/IIFLWebSocket.h"++#include "core/logging/Logger.h"+#include "network/websocket/WebSocketClient.h"+#include "trading/instruments/InstrumentService.h"++#include <QByteArray>+#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QJsonValue>+#include <QNetworkAccessManager>+#include <QNetworkReply>+#include <QNetworkRequest>+#include <QUrl>++namespace fincept::trading {++static constexpr const char* TAG_IIFL_WS = "IIFLWS";++// ─────────────────────────────────────────────────────────────────────────────+// Construction+// ─────────────────────────────────────────────────────────────────────────────++IIFLWebSocket::IIFLWebSocket(const QString& market_token, const QString& user_id, QObject* parent)+ : BrokerWebSocketBase(parent), market_token_(market_token), user_id_(user_id) {+ ws_ = new WebSocketClient(this);+ connect(ws_, &WebSocketClient::connected, this, &IIFLWebSocket::on_ws_connected);+ connect(ws_, &WebSocketClient::disconnected, this, &IIFLWebSocket::on_ws_disconnected);+ connect(ws_, &WebSocketClient::message_received, this, &IIFLWebSocket::on_ws_message);+ connect(ws_, &WebSocketClient::error_occurred, this, &IIFLWebSocket::error_occurred);++ // Dedicated NAM so each subscription request can carry its own+ // Authorization header without mutating the shared HttpClient singleton.+ nam_ = new QNetworkAccessManager(this);+}++IIFLWebSocket::~IIFLWebSocket() = default;++// ─────────────────────────────────────────────────────────────────────────────+// Lifecycle+// ─────────────────────────────────────────────────────────────────────────────++void IIFLWebSocket::open() {+ sio_connected_ = false;+ // Engine.IO v4 over WebSocket. token + userID authenticate the feed; XTS+ // publishes JSON in FULL broadcast mode.+ const QString url =+ QString("wss://ttblaze.iifl.com/apimarketdata/socket.io/"+ "?EIO=4&transport=websocket&token=%1&userID=%2&publishFormat=JSON&broadcastMode=Full")+ .arg(QString::fromUtf8(QUrl::toPercentEncoding(market_token_)),+ QString::fromUtf8(QUrl::toPercentEncoding(user_id_)));+ LOG_INFO(TAG_IIFL_WS, "Connecting to IIFL XTS Socket.IO");+ ws_->connect_to(url);+ start_health_check();+}++void IIFLWebSocket::close() {+ stop_health_check();+ sio_connected_ = false;+ // Polite Socket.IO disconnect ("41"), then drop the transport.+ if (ws_->is_connected())+ ws_->send(QStringLiteral("41"));+ ws_->disconnect();+}++bool IIFLWebSocket::is_connected() const {+ return ws_->is_connected() && sio_connected_;+}++// ─────────────────────────────────────────────────────────────────────────────+// Subscription+// ─────────────────────────────────────────────────────────────────────────────++void IIFLWebSocket::subscribe(const QVector<qint64>& tokens) {+ QVector<qint64> new_tokens;+ for (qint64 t : tokens) {+ if (!subscribed_tokens_.contains(t)) {+ subscribed_tokens_.insert(t);+ new_tokens.append(t);+ }+ }+ if (new_tokens.isEmpty())+ return;+ // XTS subscription is an HTTP call; only valid once the SIO channel is up so+ // the resulting stream has somewhere to land.+ if (sio_connected_)+ http_subscription(new_tokens, /*subscribe=*/true);+}++void IIFLWebSocket::unsubscribe() {+ if (subscribed_tokens_.isEmpty())+ return;+ QVector<qint64> all(subscribed_tokens_.begin(), subscribed_tokens_.end());+ if (sio_connected_)+ http_subscription(all, /*subscribe=*/false);+ subscribed_tokens_.clear();+ clear_tick_cache();+}++void IIFLWebSocket::unsubscribe(const QVector<qint64>& tokens) {+ QVector<qint64> to_remove;+ for (qint64 t : tokens) {+ if (subscribed_tokens_.remove(t))+ to_remove.append(t);+ }+ if (!to_remove.isEmpty() && sio_connected_)+ http_subscription(to_remove, /*subscribe=*/false);+}++void IIFLWebSocket::on_data_stall() {+ LOG_WARN(TAG_IIFL_WS, "Data stall — forcing reconnect");+ sio_connected_ = false;+ ws_->disconnect();+ open();+}++void IIFLWebSocket::http_subscription(const QVector<qint64>& tokens, bool subscribe) {+ if (tokens.isEmpty())+ return;++ QJsonArray instruments;+ for (qint64 t : tokens) {+ QJsonObject inst;+ inst["exchangeSegment"] = segment_for_token(t);+ // XTS expects the instrument id as a string.+ inst["exchangeInstrumentID"] = QString::number(t);+ instruments.append(inst);+ }++ // Subscribe both Quote (1501) and Depth (1502) so consumers get quotes + book.+ for (int code : {kCodeQuote, kCodeDepth}) {+ QJsonObject body;+ body["instruments"] = instruments;+ body["xtsMessageCode"] = code;++ QNetworkRequest req{QUrl(QString::fromUtf8(kSubscriptionUrl))};+ req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");+ req.setRawHeader("Authorization", market_token_.toUtf8());++ const QByteArray payload = QJsonDocument(body).toJson(QJsonDocument::Compact);+ QNetworkReply* reply = subscribe ? nam_->post(req, payload)+ : nam_->sendCustomRequest(req, "PUT", payload);++ // `this` as context: Qt auto-disconnects on destruction (safe — see P8).+ connect(reply, &QNetworkReply::finished, this, [this, reply, subscribe, code]() {+ const int status =+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();+ if (reply->error() != QNetworkReply::NoError || status != 200) {+ LOG_WARN(TAG_IIFL_WS,+ QString("%1 (code %2) failed: HTTP %3 %4")+ .arg(subscribe ? "Subscribe" : "Unsubscribe")+ .arg(code)+ .arg(status)+ .arg(reply->errorString()));+ } else {+ LOG_INFO(TAG_IIFL_WS, QString("%1 ok (xtsCode %2)")+ .arg(subscribe ? "Subscribed" : "Unsubscribed")+ .arg(code));+ }+ reply->deleteLater();+ });+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Engine.IO / Socket.IO framing+// ─────────────────────────────────────────────────────────────────────────────++void IIFLWebSocket::on_ws_connected() {+ // Transport is up; the Engine.IO handshake ("0{...}") drives the rest. We+ // emit BrokerWebSocketBase::connected() only after the SIO namespace+ // connect ("40") is acknowledged.+ LOG_INFO(TAG_IIFL_WS, "WebSocket transport open — awaiting Engine.IO handshake");+}++void IIFLWebSocket::on_ws_disconnected() {+ LOG_WARN(TAG_IIFL_WS, "Disconnected");+ sio_connected_ = false;+ emit disconnected();+}++void IIFLWebSocket::on_ws_message(const QString& message) {+ if (message.isEmpty())+ return;+ handle_engineio(message);+}++void IIFLWebSocket::handle_engineio(const QString& packet) {+ // Engine.IO packet type is the first character.+ const QChar type = packet.at(0);+ const QString rest = packet.mid(1);++ switch (type.toLatin1()) {+ case '0': // open — server announced sid/ping config; join the namespace.+ LOG_DEBUG(TAG_IIFL_WS, "Engine.IO open — sending Socket.IO connect (40)");+ ws_->send(QStringLiteral("40"));+ break;+ case '2': // ping → reply pong.+ ws_->send(QStringLiteral("3"));+ break;+ case '3': // pong (we don't initiate pings) — ignore.+ break;+ case '4': { // Socket.IO message; second char is the SIO packet type.+ if (rest.isEmpty())+ break;+ const QChar sio_type = rest.at(0);+ const QString sio_rest = rest.mid(1);+ switch (sio_type.toLatin1()) {+ case '0': // CONNECT ack — namespace joined.+ LOG_INFO(TAG_IIFL_WS, "Socket.IO namespace connected");+ sio_connected_ = true;+ emit connected();+ // (Re)subscribe everything we already wanted.+ if (!subscribed_tokens_.isEmpty()) {+ QVector<qint64> all(subscribed_tokens_.begin(), subscribed_tokens_.end());+ http_subscription(all, /*subscribe=*/true);+ }+ break;+ case '1': // DISCONNECT+ LOG_WARN(TAG_IIFL_WS, "Socket.IO namespace disconnected");+ sio_connected_ = false;+ break;+ case '2': // EVENT — payload is a JSON array ["event", data].+ handle_socketio_event(sio_rest);+ break;+ case '4': // CONNECT_ERROR+ LOG_ERROR(TAG_IIFL_WS, QString("Socket.IO connect error: %1").arg(sio_rest));+ emit error_occurred(QStringLiteral("IIFL Socket.IO connect error"));+ break;+ default:+ break;+ }+ break;+ }+ default:+ break;+ }+}++void IIFLWebSocket::handle_socketio_event(const QString& payload) {+ // payload is the JSON array immediately following "42", optionally prefixed+ // by an ack id (digits) which we don't use.+ int start = 0;+ while (start < payload.size() && payload.at(start).isDigit())+ ++start;+ const QString json_str = payload.mid(start);++ QJsonParseError err;+ QJsonDocument doc = QJsonDocument::fromJson(json_str.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError || !doc.isArray()) {+ LOG_DEBUG(TAG_IIFL_WS, QString("Unparseable SIO event: %1").arg(json_str.left(120)));+ return;+ }++ const QJsonArray arr = doc.array();+ if (arr.isEmpty())+ return;++ const QString event = arr.at(0).toString();+ const QJsonValue data = arr.size() > 1 ? arr.at(1) : QJsonValue();++ // XTS market-data events are named "<code>-json-full" / "<code>-json-partial".+ if (event.contains(QStringLiteral("-json-")))+ handle_market_data(event, data);+}++// ─────────────────────────────────────────────────────────────────────────────+// Market-data parsing+// ─────────────────────────────────────────────────────────────────────────────++void IIFLWebSocket::handle_market_data(const QString& event, const QJsonValue& data) {+ // The data value may be a JSON object or a JSON string holding an object.+ QJsonObject obj;+ if (data.isObject()) {+ obj = data.toObject();+ } else if (data.isString()) {+ QJsonParseError err;+ QJsonDocument d = QJsonDocument::fromJson(data.toString().toUtf8(), &err);+ if (err.error != QJsonParseError::NoError || !d.isObject())+ return;+ obj = d.object();+ } else {+ return;+ }++ note_tick();++ const int segment = obj.value("ExchangeSegment").toInt();+ const qint64 instrument_id = qint64(obj.value("ExchangeInstrumentID").toDouble());+ const int message_code =+ obj.contains("MessageCode")+ ? obj.value("MessageCode").toInt()+ : event.section('-', 0, 0).toInt(); // fall back to the event prefix++ const QString key = QString::number(instrument_id);++ // Enrich with the normalised symbol; fall back to the numeric id.+ QString symbol = key;+ QString exchange = segment_to_exchange(segment);+ auto inst = InstrumentService::instance().find_by_token(static_cast<quint32>(instrument_id), "iifl");+ if (inst.has_value()) {+ symbol = inst->symbol;+ if (!inst->exchange.isEmpty())+ exchange = inst->exchange;+ }++ // For Depth (1502) the quote fields live under "Touchline"; otherwise root.+ QJsonObject tl =+ (message_code == kCodeDepth && obj.value("Touchline").isObject()) ? obj.value("Touchline").toObject() : obj;++ BrokerQuote partial;+ partial.symbol = symbol;+ partial.ltp = tl.value("LastTradedPrice").toDouble();+ partial.open = tl.value("Open").toDouble();+ partial.high = tl.value("High").toDouble();+ partial.low = tl.value("Low").toDouble();+ partial.close = tl.value("Close").toDouble();+ partial.volume = tl.value("TotalTradedQuantity").toDouble();+ partial.oi = qint64(obj.value("OpenInterest").toDouble());+ partial.timestamp = QDateTime::currentMSecsSinceEpoch();++ // XTS partial frames omit unchanged fields → preserve via merge_tick.+ BrokerQuote merged = merge_tick(key, partial);+ emit tick_received(merged);++ // Depth: "Bids"/"Asks" arrays with Price/Size/TotalOrders entries.+ if (message_code == kCodeDepth && obj.value("Bids").isArray() && obj.value("Asks").isArray()) {+ MarketDepth depth;+ depth.symbol = symbol;+ depth.exchange = exchange;+ depth.ltp = merged.ltp;+ depth.volume = merged.volume;+ depth.oi = double(merged.oi);++ const QJsonArray bids = obj.value("Bids").toArray();+ const QJsonArray asks = obj.value("Asks").toArray();+ for (int i = 0; i < bids.size() && depth.bids.size() < 5; ++i) {+ const QJsonObject b = bids.at(i).toObject();+ DepthLevel lvl;+ lvl.price = b.value("Price").toDouble();+ lvl.quantity = b.value("Size").toInt();+ lvl.orders = b.value("TotalOrders").toInt();+ depth.bids.append(lvl);+ }+ for (int i = 0; i < asks.size() && depth.asks.size() < 5; ++i) {+ const QJsonObject a = asks.at(i).toObject();+ DepthLevel lvl;+ lvl.price = a.value("Price").toDouble();+ lvl.quantity = a.value("Size").toInt();+ lvl.orders = a.value("TotalOrders").toInt();+ depth.asks.append(lvl);+ }+ emit depth_received(depth);+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Exchange segment mapping (IiflExchangeMapper)+// ─────────────────────────────────────────────────────────────────────────────++int IIFLWebSocket::xts_segment(const QString& exchange) {+ if (exchange == "NFO" || exchange == "NSEFO")+ return 2;+ if (exchange == "BSE" || exchange == "BSECM" || exchange == "BSE_INDEX")+ return 11;+ if (exchange == "BFO" || exchange == "BSEFO")+ return 12;+ if (exchange == "MCX" || exchange == "MCXFO")+ return 51;+ if (exchange == "CDS" || exchange == "NSECD")+ return 3;+ return 1; // NSE / NSECM / NSE_INDEX+}++QString IIFLWebSocket::segment_to_exchange(int segment) {+ switch (segment) {+ case 2:+ return QStringLiteral("NFO");+ case 3:+ return QStringLiteral("CDS");+ case 11:+ return QStringLiteral("BSE");+ case 12:+ return QStringLiteral("BFO");+ case 51:+ return QStringLiteral("MCX");+ default:+ return QStringLiteral("NSE");+ }+}++int IIFLWebSocket::segment_for_token(qint64 token) const {+ QString exchange = default_exchange_;+ auto inst = InstrumentService::instance().find_by_token(static_cast<quint32>(token), "iifl");+ if (inst.has_value()) {+ const QString& ex = inst->brexchange.isEmpty() ? inst->exchange : inst->brexchange;+ if (!ex.isEmpty())+ exchange = ex;+ }+ return xts_segment(exchange);+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/IIFLWebSocket.h b/fincept-qt/src/trading/websocket/IIFLWebSocket.hnew file mode 100644index 000000000..6fdab570d--- /dev/null+++ b/fincept-qt/src/trading/websocket/IIFLWebSocket.h@@ -0,0 +1,122 @@+#pragma once+// IIFLWebSocket — IIFL XTS market-data adapter (Socket.IO / Engine.IO v4).+//+// Port of OpenAlgo's iifl_websocket.py + iifl_adapter.py onto the Fincept+// BrokerWebSocketBase contract.+//+// IMPORTANT — how XTS streaming actually works (verified against the py source):+// - The realtime channel is Socket.IO (Engine.IO v4) over a raw WebSocket. We+// speak the Engine.IO/Socket.IO framing directly on QWebSocket (no SIO lib):+// open: server sends "0{json}" (sid + pingInterval/pingTimeout)+// connect: client sends "40"; server replies "40{...sid...}"+// ping: server sends "2" → client replies "3" (pong)+// event: server sends "42[\"<event>\",<data>]"+// - SUBSCRIPTION IS NOT A SOCKET.IO EMIT. XTS subscribes via an HTTP POST to+// {MARKET_DATA_URL}/instruments/subscription+// with header Authorization: <market_token> and body+// { "instruments":[{exchangeSegment,exchangeInstrumentID}], "xtsMessageCode":<code> }+// Unsubscribe is the same endpoint via HTTP PUT. The Socket.IO connection is+// used only to *receive* the resulting data stream.+// - Market data arrives as Socket.IO events named per XTS message code:+// 1512 = LTP, 1501 = Quote/Touchline, 1502 = Market Depth, 1510 = OI.+// Each fires as "<code>-json-full" / "<code>-json-partial"; the payload is a+// JSON object (or JSON string) describing the instrument + fields.+//+// Auth: XTS market-data streaming needs a market-data session token and the+// resolved userID. The Fincept broker layer resolves these (via the XTS+// marketdata login) and passes them to the constructor, so this adapter does+// not perform the login itself.+//+// Subscribe contract: tokens are exchangeInstrumentIDs. The exchangeSegment is+// resolved per token from InstrumentService (brexchange → XTS segment code);+// tokens with no mapping default to set_default_exchange().++#include "trading/websocket/BrokerWebSocketBase.h"++#include <QHash>+#include <QSet>+#include <QString>+#include <QVector>++class QNetworkAccessManager;++namespace fincept {++class WebSocketClient;++namespace trading {++class IIFLWebSocket : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// @param market_token XTS market-data session token (sent as the WS `token`+ /// query param and as the subscription Authorization header)+ /// @param user_id resolved XTS userID (sent as the WS `userID` query param)+ explicit IIFLWebSocket(const QString& market_token, const QString& user_id,+ QObject* parent = nullptr);+ ~IIFLWebSocket() override;++ void open() override;+ void close() override;+ bool is_connected() const override;++ /// Subscribe by exchangeInstrumentID. Subscribes Quote (1501) + Depth (1502)+ /// so consumers receive both a quote stream and the order book.+ void subscribe(const QVector<qint64>& tokens) override;++ void unsubscribe() override;+ void unsubscribe(const QVector<qint64>& tokens);++ /// Default exchange used when a token has no InstrumentService mapping.+ void set_default_exchange(const QString& exchange) { default_exchange_ = exchange; }++ protected:+ void on_data_stall() override;++ private slots:+ void on_ws_connected();+ void on_ws_message(const QString& message);+ void on_ws_disconnected();++ private:+ // Engine.IO / Socket.IO framing.+ void handle_engineio(const QString& packet);+ void handle_socketio_event(const QString& payload); // payload after the "42" prefix++ // HTTP subscription (POST = subscribe, PUT = unsubscribe).+ void http_subscription(const QVector<qint64>& tokens, bool subscribe);++ // Map Fincept/broker exchange → XTS exchangeSegment code.+ static int xts_segment(const QString& exchange);+ // Map XTS exchangeSegment code → normalised exchange string.+ static QString segment_to_exchange(int segment);++ int segment_for_token(qint64 token) const;++ // Parse one XTS market-data JSON object and emit tick/depth.+ void handle_market_data(const QString& event, const class QJsonValue& data);++ QString market_token_;+ QString user_id_;+ QString default_exchange_ = "NSE";++ WebSocketClient* ws_ = nullptr;+ QNetworkAccessManager* nam_ = nullptr; // dedicated NAM for the per-request Authorization header+ bool sio_connected_ = false;++ QSet<qint64> subscribed_tokens_;++ // XTS message codes.+ static constexpr int kCodeLtp = 1512;+ static constexpr int kCodeQuote = 1501;+ static constexpr int kCodeDepth = 1502;+ static constexpr int kCodeOi = 1510;++ static constexpr const char* kBaseUrl = "https://ttblaze.iifl.com";+ static constexpr const char* kMarketDataPath = "/apimarketdata";+ static constexpr const char* kSubscriptionUrl =+ "https://ttblaze.iifl.com/apimarketdata/instruments/subscription";+};++} // namespace trading+} // namespace finceptdiff --git a/fincept-qt/src/trading/websocket/KotakWebSocket.cpp b/fincept-qt/src/trading/websocket/KotakWebSocket.cppnew file mode 100644index 000000000..e7ee59252--- /dev/null+++ b/fincept-qt/src/trading/websocket/KotakWebSocket.cpp@@ -0,0 +1,605 @@+// KotakWebSocket — Kotak Neo HSI binary market-data adapter.+//+// See the header for the protocol summary. OpenAlgo references:+// broker/kotak/streaming/HSWebSocketLib.py (binary framing — authoritative)+// broker/kotak/streaming/kotak_websocket.py (JSON→binary glue + tick parsing)+// broker/kotak/streaming/kotak_adapter.py (batch/merge/mode handling)++#include "trading/websocket/KotakWebSocket.h"++#include "core/logging/Logger.h"+#include "network/websocket/WebSocketClient.h"+#include "trading/instruments/InstrumentService.h"++#include <QDateTime>+#include <QStringList>++#include <cmath>++namespace fincept::trading {++static constexpr const char* TAG_KOTAK_WS = "KotakWS";++// ── HSI protocol constants (from HSWebSocketLib.py) ─────────────────────────+namespace {+constexpr quint8 CONNECTION_TYPE = 1;+constexpr quint8 DATA_TYPE = 6;+constexpr quint8 SUBSCRIBE_TYPE = 4;+constexpr quint8 UNSUBSCRIBE_TYPE = 5;++constexpr quint8 RESP_SNAP = 83; // 'S'+constexpr quint8 RESP_UPDATE = 85; // 'U'++// HSI's "trash"/invalid long value — fields carrying it are ignored.+constexpr qint64 TRASH_VAL = -2147483648LL;++// SCRIP feed field indices (SCRIP_MAPPING in the py source).+constexpr int SC_VOLUME = 4;+constexpr int SC_LTP = 5;+constexpr int SC_BP = 9; // best bid price+constexpr int SC_SP = 10; // best ask price+constexpr int SC_BQ = 11; // best bid qty+constexpr int SC_BS = 12; // best ask qty+constexpr int SC_LOW = 14; // "lo"+constexpr int SC_HIGH = 15; // "h"+constexpr int SC_OPEN = 20; // "op"+constexpr int SC_CLOSE = 21; // "c" (prev close)+constexpr int SC_OI = 22;+constexpr int SC_MULT = 23;+constexpr int SC_PREC = 24;++// INDEX feed field indices (INDEX_MAPPING).+constexpr int IX_LTP = 2; // "iv"+constexpr int IX_CLOSE = 3; // "ic"+constexpr int IX_HIGH = 5;+constexpr int IX_LOW = 6;+constexpr int IX_OPEN = 7;+constexpr int IX_MULT = 8;+constexpr int IX_PREC = 9;++// DEPTH feed field indices (DEPTH_MAPPING). bp/bp1..bp4 bids, sp/sp1..sp4 asks.+constexpr int DP_BP0 = 2; // bp, bp1, bp2, bp3, bp4 → 2..6+constexpr int DP_SP0 = 7; // sp, sp1, sp2, sp3, sp4 → 7..11+constexpr int DP_BQ0 = 12; // bq, bq1..bq4 → 12..16+constexpr int DP_BS0 = 17; // bs(ask qty l0), bs1..bs4 → 17..21+constexpr int DP_BNO0 = 22; // bid orders bno1..bno5 → 22..26+constexpr int DP_SNO0 = 27; // ask orders sno1..sno5 → 27..31+constexpr int DP_MULT = 32;+constexpr int DP_PREC = 33;++// Shared string field indices (STRING_INDEX).+constexpr int STR_NAME = 51;+constexpr int STR_SYMBOL = 52; // token ("tk")+constexpr int STR_EXCHG = 53; // exchange ("e")+constexpr int STR_TSYMBOL = 54; // trading symbol ("ts")++// Big-endian readers over a const uchar*.+quint16 be16(const uchar* p) { return quint16((quint16(p[0]) << 8) | p[1]); }+quint32 be32(const uchar* p) {+ return (quint32(p[0]) << 24) | (quint32(p[1]) << 16) | (quint32(p[2]) << 8) | p[3];+}++// Append helpers for binary frame construction (big-endian).+void put8(QByteArray& b, quint8 v) { b.append(char(v)); }+void put16(QByteArray& b, quint16 v) {+ b.append(char((v >> 8) & 0xFF));+ b.append(char(v & 0xFF));+}+void put32(QByteArray& b, quint32 v) {+ b.append(char((v >> 24) & 0xFF));+ b.append(char((v >> 16) & 0xFF));+ b.append(char((v >> 8) & 0xFF));+ b.append(char(v & 0xFF));+}+} // namespace++// ─────────────────────────────────────────────────────────────────────────────+// Construction+// ─────────────────────────────────────────────────────────────────────────────++KotakWebSocket::KotakWebSocket(const QString& auth_token, const QString& sid,+ const QString& hs_server_id, const QString& access_token,+ QObject* parent)+ : BrokerWebSocketBase(parent), auth_token_(auth_token), sid_(sid),+ hs_server_id_(hs_server_id), access_token_(access_token) {+ ws_ = new WebSocketClient(this);+ connect(ws_, &WebSocketClient::connected, this, &KotakWebSocket::on_connected);+ connect(ws_, &WebSocketClient::disconnected, this, &KotakWebSocket::on_disconnected);+ connect(ws_, &WebSocketClient::binary_message_received, this, &KotakWebSocket::on_binary_message);+ connect(ws_, &WebSocketClient::error_occurred, this, &KotakWebSocket::error_occurred);+}++// ─────────────────────────────────────────────────────────────────────────────+// Lifecycle+// ─────────────────────────────────────────────────────────────────────────────++void KotakWebSocket::open() {+ auth_ok_ = false;+ LOG_INFO(TAG_KOTAK_WS, "Connecting to Kotak HSI feed");+ ws_->connect_to(QString::fromLatin1(kWsUrl));+ start_health_check();+}++void KotakWebSocket::close() {+ stop_health_check();+ auth_ok_ = false;+ ws_->disconnect();+}++bool KotakWebSocket::is_connected() const {+ return ws_->is_connected() && auth_ok_;+}++// ─────────────────────────────────────────────────────────────────────────────+// Subscription management+// ─────────────────────────────────────────────────────────────────────────────++void KotakWebSocket::subscribe(const QVector<qint64>& tokens) {+ QVector<qint64> new_tokens;+ for (qint64 t : tokens) {+ if (!subscribed_tokens_.contains(t)) {+ subscribed_tokens_.insert(t);+ new_tokens.append(t);+ }+ }+ // Debounce a burst of subscribe() calls (e.g. an option-chain load) into one+ // batch; the wire send happens in flush_subscribe_queue().+ if (!new_tokens.isEmpty())+ enqueue_subscribe(new_tokens);+}++void KotakWebSocket::unsubscribe() {+ if (subscribed_tokens_.isEmpty())+ return;+ QVector<qint64> all(subscribed_tokens_.begin(), subscribed_tokens_.end());+ if (is_connected())+ send_subscribe(all, /*subscribe=*/false);+ subscribed_tokens_.clear();+ clear_tick_cache();+ topics_.clear();+}++void KotakWebSocket::unsubscribe(const QVector<qint64>& tokens) {+ QVector<qint64> to_remove;+ for (qint64 t : tokens) {+ if (subscribed_tokens_.remove(t))+ to_remove.append(t);+ }+ if (!to_remove.isEmpty() && is_connected())+ send_subscribe(to_remove, /*subscribe=*/false);+}++void KotakWebSocket::flush_subscribe_queue() {+ QVector<qint64> tokens = take_subscribe_queue();+ if (tokens.isEmpty() || !is_connected())+ return;+ send_subscribe(tokens, /*subscribe=*/true);+}++void KotakWebSocket::on_data_stall() {+ LOG_WARN(TAG_KOTAK_WS, "Data stall — forcing reconnect");+ auth_ok_ = false;+ ws_->disconnect();+ open();+}++// ─────────────────────────────────────────────────────────────────────────────+// Slots+// ─────────────────────────────────────────────────────────────────────────────++void KotakWebSocket::on_connected() {+ LOG_INFO(TAG_KOTAK_WS, "Transport open — sending HSI connection request");+ // Wait for the connection ack before flushing subscriptions; the cn frame+ // carries the JWT (auth_token) as "Authorization" and sid as "Sid".+ ws_->send_binary(build_connection_request(auth_token_, sid_));+}++void KotakWebSocket::on_disconnected() {+ LOG_WARN(TAG_KOTAK_WS, "Disconnected");+ auth_ok_ = false;+ emit disconnected();+}++// ─────────────────────────────────────────────────────────────────────────────+// Wire builders (binary, big-endian) — port of HSWebSocketLib.py+// ─────────────────────────────────────────────────────────────────────────────++QByteArray KotakWebSocket::build_connection_request(const QString& jwt, const QString& sid) {+ // prepareConnectionRequest2(jwt, redis_key):+ // [len:2][type=1][sub=3][seg=1][short jwtLen][jwt][2][short redisLen][redis]+ // [3][short srcLen]["JS_API"]+ // markStartOfMsg reserves the leading 2 length bytes; markEndOfMsg fills them+ // with (bytes_written_after_length_field).+ const QByteArray jwt_b = jwt.toUtf8();+ const QByteArray sid_b = sid.toUtf8();+ static const QByteArray src = QByteArrayLiteral("JS_API");++ QByteArray body;+ put8(body, CONNECTION_TYPE);+ put8(body, 3);+ put8(body, 1);+ put16(body, quint16(jwt_b.size()));+ body.append(jwt_b);+ put8(body, 2);+ put16(body, quint16(sid_b.size()));+ body.append(sid_b);+ put8(body, 3);+ put16(body, quint16(src.size()));+ body.append(src);++ QByteArray frame;+ put16(frame, quint16(body.size())); // length prefix = body length+ frame.append(body);+ return frame;+}++QByteArray KotakWebSocket::build_subs_request(const QString& scrips_amp, int subscribe_type,+ const QString& prefix, int channel_num) {+ // getScripByteArray: prefix every "<exch>|<token>" scrip with "<prefix>|",+ // then [count:2] then per scrip [len:1][chars].+ QStringList scrips = scrips_amp.split('&', Qt::SkipEmptyParts);+ QByteArray data_arr;+ put16(data_arr, quint16(scrips.size()));+ for (const QString& s : scrips) {+ const QByteArray full = (prefix + "|" + s).toUtf8();+ put8(data_arr, quint8(full.size() & 0xFF));+ data_arr.append(full);+ }++ // prepareSubsUnSubsRequest:+ // [len:2][type][2][1][short dataLen][dataArr][2][short 1][channel]+ QByteArray body;+ put8(body, quint8(subscribe_type));+ put8(body, 2);+ put8(body, 1);+ put16(body, quint16(data_arr.size()));+ body.append(data_arr);+ put8(body, 2);+ put16(body, 1);+ put8(body, quint8(channel_num));++ QByteArray frame;+ put16(frame, quint16(body.size()));+ frame.append(body);+ return frame;+}++QByteArray KotakWebSocket::build_ack_request(qint32 msg_num) {+ // get_acknowledgement_req: [len:2][ACK_TYPE=3][1][1][short 4][int msg_num]+ QByteArray body;+ put8(body, 3); // ACK_TYPE+ put8(body, 1);+ put8(body, 1);+ put16(body, 4);+ put32(body, quint32(msg_num));++ QByteArray frame;+ put16(frame, quint16(body.size()));+ frame.append(body);+ return frame;+}++void KotakWebSocket::send_subscribe(const QVector<qint64>& tokens, bool subscribe) {+ if (tokens.isEmpty())+ return;++ const int type = subscribe ? SUBSCRIBE_TYPE : UNSUBSCRIBE_TYPE;++ // Build "<exch>|<token>" scrips, batched at kMaxScripsPerFrame. For each+ // batch we send a scrip ("sf", quotes) and a depth ("dp", order book) frame.+ QStringList scrip_list;+ scrip_list.reserve(tokens.size());+ for (qint64 t : tokens) {+ const QString s = scrip_for_token(t);+ if (!s.isEmpty())+ scrip_list.append(s);+ }+ if (scrip_list.isEmpty())+ return;++ for (int i = 0; i < scrip_list.size(); i += kMaxScripsPerFrame) {+ const QStringList chunk = scrip_list.mid(i, kMaxScripsPerFrame);+ const QString joined = chunk.join('&');+ ws_->send_binary(build_subs_request(joined, type, QStringLiteral("sf"), 1));+ ws_->send_binary(build_subs_request(joined, type, QStringLiteral("dp"), 1));+ }+ LOG_INFO(TAG_KOTAK_WS, QString("%1 %2 scrips")+ .arg(subscribe ? "Subscribed" : "Unsubscribed")+ .arg(scrip_list.size()));+}++void KotakWebSocket::resubscribe_all() {+ if (subscribed_tokens_.isEmpty())+ return;+ QVector<qint64> all(subscribed_tokens_.begin(), subscribed_tokens_.end());+ send_subscribe(all, /*subscribe=*/true);+}++QString KotakWebSocket::scrip_for_token(qint64 token) const {+ QString exchange = default_exchange_;+ auto inst = InstrumentService::instance().find_by_token(static_cast<quint32>(token), "kotak");+ if (inst.has_value()) {+ const QString& ex = inst->brexchange.isEmpty() ? inst->exchange : inst->brexchange;+ if (!ex.isEmpty())+ exchange = ex;+ }+ return QString("%1|%2").arg(exchange).arg(token);+}++// ─────────────────────────────────────────────────────────────────────────────+// Inbound decode — port of HSWrapper.parseData+// ─────────────────────────────────────────────────────────────────────────────++void KotakWebSocket::on_binary_message(const QByteArray& data) {+ parse_data(data);+}++void KotakWebSocket::parse_data(const QByteArray& data) {+ const int total = data.size();+ if (total < 3)+ return;+ const uchar* e = reinterpret_cast<const uchar*>(data.constData());++ int pos = 0;+ pos += 2; // packetsCount (unused)+ const quint8 type = e[pos];+ pos += 1;++ // Defensive bounds-checked reads: any out-of-range index aborts the frame.+ auto avail = [&](int need) { return pos + need <= total; };++ if (type == CONNECTION_TYPE) {+ // Connection ack: field count, then field(s) carrying the "K"/"N" status.+ if (!avail(1))+ return;+ const int fcount = e[pos];+ pos += 1;+ QString status;+ if (fcount >= 1) {+ if (!avail(1))+ return;+ pos += 1; // field id+ if (!avail(2))+ return;+ const int vlen = be16(e + pos);+ pos += 2;+ if (!avail(vlen))+ return;+ status = QString::fromUtf8(reinterpret_cast<const char*>(e + pos), vlen);+ pos += vlen;+ // Second field (ack count) present when fcount >= 2.+ if (fcount >= 2 && avail(3)) {+ pos += 1; // field id+ const int alen = be16(e + pos);+ pos += 2;+ if (avail(alen)) {+ qint64 ack = 0;+ for (int i = 0; i < alen; ++i)+ ack = (ack << 8) | e[pos + i];+ ack_num_ = int(ack);+ pos += alen;+ }+ }+ }+ if (status == QStringLiteral("K")) {+ LOG_INFO(TAG_KOTAK_WS, "HSI connection acknowledged — flushing subscriptions");+ auth_ok_ = true;+ ack_counter_ = 0;+ emit connected();+ resubscribe_all();+ } else {+ LOG_ERROR(TAG_KOTAK_WS, QString("HSI connection failed (status=%1)").arg(status));+ emit error_occurred(QStringLiteral("Kotak HSI authentication failed"));+ }+ return;+ }++ if (type != DATA_TYPE)+ return; // subscribe/snapshot acks — ignore (subscription is best-effort)++ note_tick();++ // Optional ack handshake: when ack_num_>0 the server prefixes a 4-byte+ // message number and expects an ACK frame once we've seen ack_num_ messages.+ if (ack_num_ > 0) {+ if (!avail(4))+ return;+ ack_counter_ += 1;+ const qint32 msg_num = qint32(be32(e + pos));+ pos += 4;+ if (ack_counter_ >= ack_num_) {+ ws_->send_binary(build_ack_request(msg_num));+ ack_counter_ = 0;+ }+ }++ if (!avail(2))+ return;+ const int rec_count = be16(e + pos);+ pos += 2;++ for (int r = 0; r < rec_count; ++r) {+ if (!avail(2))+ return;+ const int sub_len = be16(e + pos);+ pos += 2;+ const int sub_start = pos;+ if (sub_len <= 0 || sub_start + sub_len > total)+ return;++ const quint8 resp = e[pos];+ pos += 1;++ TopicRecord* rec = nullptr;+ qint64 topic_id = 0;++ if (resp == RESP_SNAP) {+ if (!avail(4)) { pos = sub_start + sub_len; continue; }+ topic_id = be32(e + pos);+ pos += 4;+ if (!avail(1)) { pos = sub_start + sub_len; continue; }+ const int name_len = e[pos];+ pos += 1;+ if (!avail(name_len)) { pos = sub_start + sub_len; continue; }+ const QString topic_name =+ QString::fromUtf8(reinterpret_cast<const char*>(e + pos), name_len);+ pos += name_len;++ // topic_name is "<feed>|<exch>|<token>" — feed is the prefix.+ const QString feed = topic_name.section('|', 0, 0);++ // Evict oldest topic if at cap (mirrors the py _max_topics guard).+ if (topics_.size() >= kMaxTopics && !topics_.contains(topic_id))+ topics_.erase(topics_.begin());++ TopicRecord& tr = topics_[topic_id];+ tr.feed_type = feed;+ rec = &tr;++ // Long field block: fcount1 × (4-byte value), index = field id.+ if (!avail(1)) { pos = sub_start + sub_len; continue; }+ int fcount = e[pos];+ pos += 1;+ for (int k = 0; k < fcount; ++k) {+ if (!avail(4)) { pos = sub_start + sub_len; break; }+ const qint64 v = qint64(qint32(be32(e + pos)));+ pos += 4;+ if (v != TRASH_VAL)+ tr.fields[k] = v;+ }+ // Pull multiplier/precision out so FLOAT32 fields decode correctly.+ const int mult_idx = (feed == "if") ? IX_MULT : (feed == "dp") ? DP_MULT : SC_MULT;+ const int prec_idx = (feed == "if") ? IX_PREC : (feed == "dp") ? DP_PREC : SC_PREC;+ if (tr.fields.contains(mult_idx) && tr.fields[mult_idx] > 0)+ tr.multiplier = double(tr.fields[mult_idx]);+ if (tr.fields.contains(prec_idx) && tr.fields[prec_idx] >= 0) {+ tr.precision = int(tr.fields[prec_idx]);+ tr.precision_value = std::pow(10.0, tr.precision);+ }++ // String field block: fcount2 × (1-byte fid, 1-byte len, chars).+ if (avail(1)) {+ int scount = e[pos];+ pos += 1;+ for (int k = 0; k < scount; ++k) {+ if (!avail(2)) break;+ const int fid = e[pos];+ pos += 1;+ const int dlen = e[pos];+ pos += 1;+ if (!avail(dlen)) break;+ const QString sval =+ QString::fromUtf8(reinterpret_cast<const char*>(e + pos), dlen);+ pos += dlen;+ if (fid == STR_SYMBOL)+ tr.token = sval;+ else if (fid == STR_EXCHG)+ tr.exchange = sval;+ else if (fid == STR_TSYMBOL)+ tr.tsymbol = sval;+ }+ }+ } else if (resp == RESP_UPDATE) {+ if (!avail(4)) { pos = sub_start + sub_len; continue; }+ topic_id = be32(e + pos);+ pos += 4;+ auto it = topics_.find(topic_id);+ if (it == topics_.end()) {+ // Unknown topic — skip its long block to stay frame-aligned.+ pos = sub_start + sub_len;+ continue;+ }+ rec = &it.value();+ if (!avail(1)) { pos = sub_start + sub_len; continue; }+ int fcount = e[pos];+ pos += 1;+ for (int k = 0; k < fcount; ++k) {+ if (!avail(4)) break;+ const qint64 v = qint64(qint32(be32(e + pos)));+ pos += 4;+ if (v != TRASH_VAL)+ rec->fields[k] = v;+ }+ } else {+ // Unknown response type — skip the whole sub-message.+ pos = sub_start + sub_len;+ continue;+ }++ // Keep pos aligned to the declared sub-message length regardless of any+ // trailing bytes we didn't consume.+ pos = sub_start + sub_len;++ if (!rec)+ continue;++ // ── Emit ──────────────────────────────────────────────────────────+ const QString key = QString::number(topic_id);+ const double divisor = rec->multiplier * rec->precision_value;+ auto fval = [&](int idx) -> double {+ auto it = rec->fields.constFind(idx);+ if (it == rec->fields.constEnd())+ return 0.0;+ return divisor != 0.0 ? double(it.value()) / divisor : double(it.value());+ };+ auto lval = [&](int idx) -> qint64 {+ auto it = rec->fields.constFind(idx);+ return it == rec->fields.constEnd() ? 0 : it.value();+ };++ const QString sym = !rec->tsymbol.isEmpty() ? rec->tsymbol+ : !rec->token.isEmpty() ? rec->token+ : key;++ if (rec->feed_type == "dp") {+ MarketDepth depth;+ depth.symbol = sym;+ depth.exchange = rec->exchange;+ for (int lvl = 0; lvl < 5; ++lvl) {+ DepthLevel bid;+ bid.price = fval(DP_BP0 + lvl);+ bid.quantity = int(lval(DP_BQ0 + lvl));+ bid.orders = int(lval(DP_BNO0 + lvl));+ depth.bids.append(bid);++ DepthLevel ask;+ ask.price = fval(DP_SP0 + lvl);+ ask.quantity = int(lval(DP_BS0 + lvl));+ ask.orders = int(lval(DP_SNO0 + lvl));+ depth.asks.append(ask);+ }+ emit depth_received(depth);+ continue;+ }++ BrokerQuote partial;+ partial.symbol = sym;+ if (rec->feed_type == "if") {+ partial.ltp = fval(IX_LTP);+ partial.open = fval(IX_OPEN);+ partial.high = fval(IX_HIGH);+ partial.low = fval(IX_LOW);+ partial.close = fval(IX_CLOSE);+ } else { // "sf" scrip / quote+ partial.ltp = fval(SC_LTP);+ partial.open = fval(SC_OPEN);+ partial.high = fval(SC_HIGH);+ partial.low = fval(SC_LOW);+ partial.close = fval(SC_CLOSE);+ partial.volume = double(lval(SC_VOLUME));+ partial.bid = fval(SC_BP);+ partial.ask = fval(SC_SP);+ partial.bid_size = double(lval(SC_BQ));+ partial.ask_size = double(lval(SC_BS));+ partial.oi = lval(SC_OI);+ }+ partial.timestamp = QDateTime::currentMSecsSinceEpoch();++ // HSI sends incremental updates with unchanged fields absent (= 0 here),+ // so route through merge_tick to preserve last non-zero OHLC.+ BrokerQuote merged = merge_tick(key, partial);+ emit tick_received(merged);+ }+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/KotakWebSocket.h b/fincept-qt/src/trading/websocket/KotakWebSocket.hnew file mode 100644index 000000000..ff7ca55ff--- /dev/null+++ b/fincept-qt/src/trading/websocket/KotakWebSocket.h@@ -0,0 +1,140 @@+#pragma once+// KotakWebSocket — Kotak Neo (HSI / High-Speed Interface) market-data adapter.+//+// Port of OpenAlgo's HSWebSocketLib.py + kotak_websocket.py + kotak_adapter.py+// onto the Fincept BrokerWebSocketBase contract.+//+// IMPORTANT — protocol reality (verified against HSWebSocketLib.py):+// The HSI protocol is NOT JSON-over-WebSocket. It is a *binary* protocol in+// BOTH directions, framed big-endian:+// - The connection handshake and every subscribe/unsubscribe frame is a+// packed binary buffer (see prepareConnectionRequest2 / prepareSubsUnSubsRequest).+// - Inbound market data arrives as binary frames decoded by HSWrapper.parseData+// into per-topic field arrays; FLOAT32 fields are integers that must be+// divided by (multiplier * 10^precision).+// The Python `kotak_websocket.py` layer only *looks* JSON because hs_send()+// accepts a JSON dict then translates it to the binary wire format internally.+// This C++ port replicates that binary framing directly on QWebSocket.+//+// Connection handshake (binary):+// On open we send a CONNECTION_TYPE frame built from (auth_token, sid) where+// auth_token is the JWT ("Authorization") and sid is the redis key ("Sid").+// The broker replies with a CONNECTION_TYPE ack; on "K" (OK) we flush queued+// subscriptions.+//+// Subscribe (binary):+// Scrips are "<exchange>|<token>" joined by '&', each prefixed with the feed+// type prefix ("sf"=scrip/quote, "if"=index, "dp"=depth). Max 100 scrips per+// frame. A 50ms debounce coalesces a burst of subscribe() calls.+//+// Inbound (binary):+// parse_data() decodes DATA_TYPE frames into SNAP/UPDATE topic records and+// emits BrokerQuote (scrip/index) via merge_tick → tick_received, and+// MarketDepth (depth) via depth_received.++#include "trading/websocket/BrokerWebSocketBase.h"++#include <QByteArray>+#include <QHash>+#include <QSet>+#include <QString>+#include <QVector>++namespace fincept {++class WebSocketClient;++namespace trading {++class KotakWebSocket : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// Credentials are the 4 parts of the packed Kotak token+ /// "auth_token:::sid:::hs_server_id:::access_token".+ /// auth_token — JWT, sent as the "Authorization" field of the cn frame+ /// sid — redis session id, sent as the "Sid" field of the cn frame+ /// hs_server_id, access_token — retained for completeness (not needed on the+ /// streaming socket itself; the URL/host already carries auth).+ explicit KotakWebSocket(const QString& auth_token, const QString& sid,+ const QString& hs_server_id, const QString& access_token,+ QObject* parent = nullptr);++ void open() override;+ void close() override;+ bool is_connected() const override;++ /// Token-based subscribe (BrokerWebSocketBase contract). The exchange for each+ /// token is resolved via InstrumentService; tokens with no mapping default to+ /// the exchange set by set_default_exchange(). Subscribes the scrip ("sf")+ /// feed for quotes and the depth ("dp") feed for the order book.+ void subscribe(const QVector<qint64>& tokens) override;++ void unsubscribe() override;+ void unsubscribe(const QVector<qint64>& tokens);++ /// Default exchange ("NSE"/"NFO"/"BSE"/...) used when a token has no+ /// InstrumentService mapping.+ void set_default_exchange(const QString& exchange) { default_exchange_ = exchange; }++ protected:+ void flush_subscribe_queue() override;+ void on_data_stall() override;++ private slots:+ void on_connected();+ void on_binary_message(const QByteArray& data);+ void on_disconnected();++ private:+ // ── Wire builders (binary, big-endian) ──────────────────────────────────+ static QByteArray build_connection_request(const QString& jwt, const QString& sid);+ // subscribe_type: 4 = SUBSCRIBE_TYPE, 5 = UNSUBSCRIBE_TYPE.+ // prefix: "sf" / "if" / "dp". channel_num: HSI channel (default 1).+ static QByteArray build_subs_request(const QString& scrips_amp, int subscribe_type,+ const QString& prefix, int channel_num);+ static QByteArray build_ack_request(qint32 msg_num);++ // ── Inbound decode ──────────────────────────────────────────────────────+ void parse_data(const QByteArray& data);+ void send_subscribe(const QVector<qint64>& tokens, bool subscribe);+ void resubscribe_all();++ // Resolve "<exchange>|<token>" for a numeric token via InstrumentService.+ QString scrip_for_token(qint64 token) const;++ QString auth_token_;+ QString sid_;+ QString hs_server_id_;+ QString access_token_;+ QString default_exchange_ = "NSE";++ WebSocketClient* ws_ = nullptr;+ bool auth_ok_ = false;++ QSet<qint64> subscribed_tokens_;++ // Per-topic decode state (topic_id → record), mirrors HSWrapper.topic_list.+ // Holds the last-known field array so UPDATE frames (which omit unchanged+ // string fields like symbol/exchange) can be back-filled. Capped to avoid+ // unbounded growth from unsolicited topics.+ struct TopicRecord {+ QString feed_type; // "sf" / "if" / "dp"+ QString exchange;+ QString token; // numeric token as string (the "tk" field)+ QString tsymbol; // trading symbol name (the "ts" field)+ double multiplier = 1.0;+ double precision_value = 100.0; // 10^precision+ int precision = 2;+ QHash<int, qint64> fields; // field index → raw long value (last seen)+ };+ QHash<qint64, TopicRecord> topics_;+ int ack_num_ = 0;+ int ack_counter_ = 0;++ static constexpr int kMaxScripsPerFrame = 100; // HSI MAX_SCRIPS+ static constexpr int kMaxTopics = 5000;+ static constexpr const char* kWsUrl = "wss://mlhsm.kotaksecurities.com";+};++} // namespace trading+} // namespace finceptdiff --git a/fincept-qt/src/trading/websocket/MotilalPoller.cpp b/fincept-qt/src/trading/websocket/MotilalPoller.cppnew file mode 100644index 000000000..3d0d904fe--- /dev/null+++ b/fincept-qt/src/trading/websocket/MotilalPoller.cpp@@ -0,0 +1,141 @@+// MotilalPoller — periodic REST-quote poller masquerading as a streaming adapter.+//+// Reference: broker/motilal/streaming/motilal_adapter.py (which polls the+// MotilalWebSocket client's internal quote dictionaries on a 500ms cadence).+// Here there is no usable real-time feed, so we poll MotilalBroker::get_quotes+// directly and fan each BrokerQuote out via tick_received.++#include "trading/websocket/MotilalPoller.h"++#include "core/logging/Logger.h"+#include "trading/BrokerRegistry.h"++#include <QDateTime>+#include <QMetaObject>+#include <QtConcurrent/QtConcurrent>++namespace fincept::trading {++static constexpr const char* TAG_MO_POLL = "MotilalPoller";++MotilalPoller::MotilalPoller(const BrokerCredentials& creds, QObject* parent)+ : BrokerWebSocketBase(parent), creds_(creds) {+ // P3: never start the timer in the constructor — only configure it. open()+ // starts it; close() stops it.+ poll_timer_.setInterval(kPollIntervalMs);+ connect(&poll_timer_, &QTimer::timeout, this, &MotilalPoller::poll_once);+}++// ─────────────────────────────────────────────────────────────────────────────+// Lifecycle+// ─────────────────────────────────────────────────────────────────────────────++void MotilalPoller::open() {+ if (poll_timer_.isActive())+ return;+ LOG_INFO(TAG_MO_POLL, "Starting Motilal quote polling");+ poll_timer_.start();+ start_health_check();+ emit connected();+ // Kick an immediate first poll so consumers don't wait a full interval.+ if (!symbols_.isEmpty())+ poll_once();+}++void MotilalPoller::close() {+ if (!poll_timer_.isActive())+ return;+ LOG_INFO(TAG_MO_POLL, "Stopping Motilal quote polling");+ poll_timer_.stop();+ stop_health_check();+ emit disconnected();+}++bool MotilalPoller::is_connected() const {+ return poll_timer_.isActive();+}++// ─────────────────────────────────────────────────────────────────────────────+// Subscription+// ─────────────────────────────────────────────────────────────────────────────++void MotilalPoller::subscribe(const QVector<qint64>& tokens) {+ // Motilal quotes are symbol-keyed, so numeric tokens carry no meaning here.+ Q_UNUSED(tokens);+ LOG_DEBUG(TAG_MO_POLL, "Token-based subscribe ignored — use subscribe(QStringList)");+}++void MotilalPoller::subscribe(const QStringList& symbols) {+ QSet<QString> set(symbols_.begin(), symbols_.end());+ for (const QString& s : symbols) {+ if (!s.isEmpty())+ set.insert(s);+ }+ symbols_ = QStringList(set.begin(), set.end());+ LOG_INFO(TAG_MO_POLL, QString("Subscribed %1 symbols").arg(symbols_.size()));+}++void MotilalPoller::unsubscribe() {+ symbols_.clear();+ clear_tick_cache();+}++// ─────────────────────────────────────────────────────────────────────────────+// Polling+// ─────────────────────────────────────────────────────────────────────────────++void MotilalPoller::poll_once() {+ if (symbols_.isEmpty())+ return;++ // Skip if a previous fetch is still running — Motilal's REST endpoint can be+ // slower than the 200ms cadence, and we must not stack overlapping calls.+ bool expected = false;+ if (!fetching_.compare_exchange_strong(expected, true))+ return;++ const BrokerCredentials creds = creds_;+ const QVector<QString> symbols(symbols_.begin(), symbols_.end());++ // P8: QPointer guard — the poller may be destroyed before the worker+ // lambda runs; bail out instead of dereferencing a dangling this.+ QPointer<MotilalPoller> self = this;+ QtConcurrent::run([self, creds, symbols]() {+ IBroker* broker = BrokerRegistry::instance().get("motilal");+ ApiResponse<QVector<BrokerQuote>> resp;+ if (broker)+ resp = broker->get_quotes(creds, symbols);+ else+ resp.error = QStringLiteral("motilal broker not registered");++ if (!self) {+ return; // poller gone — nothing to deliver+ }++ QMetaObject::invokeMethod(+ self,+ [self, resp]() {+ if (!self)+ return;+ self->fetching_.store(false);++ if (!resp.success || !resp.data.has_value()) {+ if (!resp.error.isEmpty())+ LOG_WARN(TAG_MO_POLL, QString("Quote poll failed: %1").arg(resp.error));+ return;+ }++ for (BrokerQuote q : resp.data.value()) {+ self->note_tick();+ // OHLC carryforward — preserve last non-zero values.+ BrokerQuote merged = self->merge_tick(q.symbol, q);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit self->tick_received(merged);+ }+ },+ Qt::QueuedConnection);+ });+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/MotilalPoller.h b/fincept-qt/src/trading/websocket/MotilalPoller.hnew file mode 100644index 000000000..6f99e2257--- /dev/null+++ b/fincept-qt/src/trading/websocket/MotilalPoller.h@@ -0,0 +1,67 @@+#pragma once+// MotilalPoller — Motilal Oswal market-data adapter (REST polling, not a WS).+//+// Motilal Oswal's market-data WebSocket uses an opaque binary protocol that the+// OpenAlgo reference can only partially decode, and it provides no reliable+// real-time push for most field types. OpenAlgo's adapter therefore polls the+// REST quote endpoint on a fixed cadence. We replicate that here: a QTimer ticks+// every kPollIntervalMs and triggers a (background) REST fetch via the registered+// MotilalBroker, emitting tick_received(BrokerQuote) for each quote.+//+// This subclasses BrokerWebSocketBase so AccountDataStream can treat it like any+// other streaming adapter (same tick_received / depth_received / connected+// signals), even though no socket is involved. is_connected() reflects whether+// the poll timer is running.+//+// Threading: the REST call is wrapped in QtConcurrent::run with a QPointer guard+// (P8) so a slow/blocking broker call never freezes the UI thread, and results+// are posted back via QMetaObject::invokeMethod (Qt::QueuedConnection).++#include "trading/TradingTypes.h"+#include "trading/websocket/BrokerWebSocketBase.h"++#include <QPointer>+#include <QSet>+#include <QString>+#include <QStringList>+#include <QTimer>+#include <QVector>++#include <atomic>++namespace fincept::trading {++class MotilalPoller : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// creds: stored so the poller can call MotilalBroker::get_quotes itself.+ explicit MotilalPoller(const BrokerCredentials& creds, QObject* parent = nullptr);++ void open() override; // starts the poll timer+ void close() override; // stops the poll timer+ bool is_connected() const override;++ /// Token-based subscribe is part of the base contract but Motilal quotes are+ /// keyed by symbol, so this is a no-op kept for interface compatibility.+ void subscribe(const QVector<qint64>& tokens) override;+ void unsubscribe() override;++ /// Symbol-based subscription — this is the API callers should use.+ void subscribe(const QStringList& symbols);++ private slots:+ void poll_once();++ private:+ BrokerCredentials creds_;+ QTimer poll_timer_;+ QStringList symbols_;++ // Guards against overlapping fetches when a poll takes longer than the+ // interval (set true while a background fetch is in flight).+ std::atomic<bool> fetching_{false};++ static constexpr int kPollIntervalMs = 200;+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/NorenWebSocket.cpp b/fincept-qt/src/trading/websocket/NorenWebSocket.cppnew file mode 100644index 000000000..980f24621--- /dev/null+++ b/fincept-qt/src/trading/websocket/NorenWebSocket.cpp@@ -0,0 +1,436 @@+#include "trading/websocket/NorenWebSocket.h"++#include "core/logging/Logger.h"++#include <QDateTime>+#include <QJsonDocument>+#include <QJsonObject>+#include <QJsonValue>++namespace fincept::trading {++// ────────────────────────────────────────────────────────────────────────────+// Field helpers — Noren sends numeric fields as JSON strings ("1234.50"). These+// coerce string-or-number-or-missing into the target type, treating absent /+// blank / "NA" as 0 so partial frames don't clobber cached values via merge_tick.+// ────────────────────────────────────────────────────────────────────────────++namespace {++double field_double(const QJsonObject& o, const char* key) {+ if (!o.contains(QLatin1String(key)))+ return 0.0;+ const QJsonValue v = o.value(QLatin1String(key));+ if (v.isDouble())+ return v.toDouble();+ if (v.isString()) {+ bool ok = false;+ double d = v.toString().toDouble(&ok);+ return ok ? d : 0.0;+ }+ return 0.0;+}++qint64 field_i64(const QJsonObject& o, const char* key) {+ if (!o.contains(QLatin1String(key)))+ return 0;+ const QJsonValue v = o.value(QLatin1String(key));+ if (v.isDouble())+ return static_cast<qint64>(v.toDouble());+ if (v.isString()) {+ bool ok = false;+ // Volumes / OI can arrive as "1234" or "1234.0" — parse as double then truncate.+ double d = v.toString().toDouble(&ok);+ return ok ? static_cast<qint64>(d) : 0;+ }+ return 0;+}++int field_int(const QJsonObject& o, const char* key) {+ return static_cast<int>(field_i64(o, key));+}++QString field_str(const QJsonObject& o, const char* key) {+ const QJsonValue v = o.value(QLatin1String(key));+ return v.isString() ? v.toString() : QString();+}++} // namespace++// ────────────────────────────────────────────────────────────────────────────+// Construction+// ────────────────────────────────────────────────────────────────────────────++NorenWebSocket::NorenWebSocket(const QString& ws_url, const QString& user_id, const QString& account_id,+ const QString& susertoken, QObject* parent)+ : BrokerWebSocketBase(parent),+ ws_url_(ws_url),+ user_id_(user_id),+ account_id_(account_id),+ susertoken_raw_(susertoken) {+ ws_ = new WebSocketClient(this);+ connect(ws_, &WebSocketClient::connected, this, &NorenWebSocket::on_ws_connected);+ connect(ws_, &WebSocketClient::disconnected, this, &NorenWebSocket::on_ws_disconnected);+ connect(ws_, &WebSocketClient::message_received, this, &NorenWebSocket::on_ws_message);+ connect(ws_, &WebSocketClient::error_occurred, this, &NorenWebSocket::error_occurred);++ heartbeat_timer_.setInterval(kHeartbeatMs);+ connect(&heartbeat_timer_, &QTimer::timeout, this, &NorenWebSocket::send_heartbeat);+}++// ────────────────────────────────────────────────────────────────────────────+// Public API+// ────────────────────────────────────────────────────────────────────────────++void NorenWebSocket::open() {+ LOG_INFO("NorenWS", QString("Connecting to %1").arg(ws_url_));+ auth_ok_ = false;+ ws_->connect_to(ws_url_);+}++void NorenWebSocket::close() {+ heartbeat_timer_.stop();+ stop_health_check();+ auth_ok_ = false;+ ws_->disconnect();+}++bool NorenWebSocket::is_connected() const {+ // Usable only once the broker has acked our connect frame.+ return ws_ && ws_->is_connected() && auth_ok_;+}++void NorenWebSocket::subscribe(const QStringList& scrips) {+ QStringList added;+ for (const QString& s : scrips) {+ const QString scrip = s.trimmed();+ if (scrip.isEmpty())+ continue;+ if (!subscribed_scrips_.contains(scrip)) {+ subscribed_scrips_.insert(scrip);+ added.append(scrip);+ }+ }+ if (added.isEmpty())+ return;++ if (is_connected()) {+ // Send only the newly-added scrips; existing ones are already streaming.+ const int count = static_cast<int>(added.size());+ for (int start = 0; start < count; start += kSubscribeBatch) {+ const int end = std::min(start + kSubscribeBatch, count);+ const QString key = QStringList(added.mid(start, end - start)).join('#');++ QJsonObject touchline;+ touchline["t"] = "t";+ touchline["k"] = key;+ ws_->send(QString::fromUtf8(QJsonDocument(touchline).toJson(QJsonDocument::Compact)));++ QJsonObject depth;+ depth["t"] = "d";+ depth["k"] = key;+ ws_->send(QString::fromUtf8(QJsonDocument(depth).toJson(QJsonDocument::Compact)));+ }+ LOG_INFO("NorenWS", QString("Subscribed %1 scrips").arg(added.size()));+ }+}++void NorenWebSocket::subscribe(const QVector<qint64>& tokens) {+ QStringList scrips;+ scrips.reserve(tokens.size());+ for (qint64 t : tokens)+ scrips.append(scrip_for_token(t));+ subscribe(scrips);+}++void NorenWebSocket::unsubscribe() {+ if (subscribed_scrips_.isEmpty())+ return;+ unsubscribe(QStringList(subscribed_scrips_.begin(), subscribed_scrips_.end()));+}++void NorenWebSocket::unsubscribe(const QStringList& scrips) {+ QStringList removed;+ for (const QString& s : scrips) {+ const QString scrip = s.trimmed();+ if (subscribed_scrips_.remove(scrip))+ removed.append(scrip);+ }+ if (removed.isEmpty())+ return;++ if (is_connected()) {+ const int count = static_cast<int>(removed.size());+ for (int start = 0; start < count; start += kSubscribeBatch) {+ const int end = std::min(start + kSubscribeBatch, count);+ const QString key = QStringList(removed.mid(start, end - start)).join('#');++ QJsonObject touchline;+ touchline["t"] = "u"; // unsubscribe touchline+ touchline["k"] = key;+ ws_->send(QString::fromUtf8(QJsonDocument(touchline).toJson(QJsonDocument::Compact)));++ QJsonObject depth;+ depth["t"] = "ud"; // unsubscribe depth+ depth["k"] = key;+ ws_->send(QString::fromUtf8(QJsonDocument(depth).toJson(QJsonDocument::Compact)));+ }+ LOG_INFO("NorenWS", QString("Unsubscribed %1 scrips").arg(removed.size()));+ }+}++void NorenWebSocket::set_exchange_for_token(qint64 token, const QString& exchange) {+ token_exchange_.insert(token, exchange);+}++// ────────────────────────────────────────────────────────────────────────────+// Slots+// ────────────────────────────────────────────────────────────────────────────++void NorenWebSocket::on_ws_connected() {+ LOG_INFO("NorenWS", "Socket open — sending connect frame");+ auth_ok_ = false;+ send_connect_frame();+ // Heartbeat + health check are armed on auth ack so we don't ping a socket+ // the broker hasn't accepted yet.+}++void NorenWebSocket::on_ws_disconnected() {+ LOG_WARN("NorenWS", "Disconnected");+ auth_ok_ = false;+ heartbeat_timer_.stop();+ stop_health_check();+ emit disconnected();+}++void NorenWebSocket::on_ws_message(const QString& message) {+ QJsonParseError err{};+ const QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError || !doc.isObject()) {+ LOG_WARN("NorenWS", QString("Non-JSON / parse error: %1").arg(err.errorString()));+ return;+ }+ const QJsonObject obj = doc.object();+ const QString type = obj.value("t").toString();++ if (type == "ck" || type == "cf" || type == "ak") {+ // Connect acknowledgment. Status lives in "s" (AliceBlue/Shoonya) or+ // "k" (some Noren docs). Treat "OK" (any case) as success.+ const QString status = obj.contains("s") ? field_str(obj, "s") : field_str(obj, "k");+ if (status.compare("OK", Qt::CaseInsensitive) == 0) {+ LOG_INFO("NorenWS", "Authenticated");+ auth_ok_ = true;+ heartbeat_timer_.start();+ start_health_check(kHeartbeatMs, /*timeout_ms=*/90000);+ resubscribe_all();+ emit connected();+ } else {+ LOG_ERROR("NorenWS", QString("Auth failed: %1")+ .arg(QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact))));+ emit error_occurred(QStringLiteral("Authentication failed"));+ }+ return;+ }++ if (type == "tk") {+ handle_touchline(obj, /*full=*/true);+ } else if (type == "tf") {+ handle_touchline(obj, /*full=*/false);+ } else if (type == "dk") {+ handle_depth(obj, /*full=*/true);+ } else if (type == "df") {+ handle_depth(obj, /*full=*/false);+ } else if (type == "h") {+ // Heartbeat echo — ignore.+ } else {+ LOG_DEBUG("NorenWS", QString("Unhandled message type '%1'").arg(type));+ }+}++// ────────────────────────────────────────────────────────────────────────────+// Send helpers+// ────────────────────────────────────────────────────────────────────────────++void NorenWebSocket::send_connect_frame() {+ QJsonObject msg;+ msg["t"] = "c";+ msg["uid"] = connect_uid();+ msg["actid"] = connect_actid();+ msg["susertoken"] = derive_susertoken(susertoken_raw_);+ msg["source"] = "API";+ ws_->send(QString::fromUtf8(QJsonDocument(msg).toJson(QJsonDocument::Compact)));+}++void NorenWebSocket::send_heartbeat() {+ if (!ws_ || !ws_->is_connected())+ return;+ QJsonObject msg;+ msg["t"] = "h";+ ws_->send(QString::fromUtf8(QJsonDocument(msg).toJson(QJsonDocument::Compact)));+ LOG_DEBUG("NorenWS", "Heartbeat sent");+}++void NorenWebSocket::resubscribe_all() {+ if (subscribed_scrips_.isEmpty())+ return;+ const QStringList all(subscribed_scrips_.begin(), subscribed_scrips_.end());+ LOG_INFO("NorenWS", QString("Resubscribing %1 scrips after auth").arg(all.size()));+ const int count = static_cast<int>(all.size());+ for (int start = 0; start < count; start += kSubscribeBatch) {+ const int end = std::min(start + kSubscribeBatch, count);+ const QString key = QStringList(all.mid(start, end - start)).join('#');++ QJsonObject touchline;+ touchline["t"] = "t";+ touchline["k"] = key;+ ws_->send(QString::fromUtf8(QJsonDocument(touchline).toJson(QJsonDocument::Compact)));++ QJsonObject depth;+ depth["t"] = "d";+ depth["k"] = key;+ ws_->send(QString::fromUtf8(QJsonDocument(depth).toJson(QJsonDocument::Compact)));+ }+}++void NorenWebSocket::flush_subscribe_queue() {+ // Token debounce queue from the base class — drain and route through the+ // string-based path so token and scrip subscribes share one wire format.+ const QVector<qint64> tokens = take_subscribe_queue();+ if (tokens.isEmpty())+ return;+ QStringList scrips;+ scrips.reserve(tokens.size());+ for (qint64 t : tokens)+ scrips.append(scrip_for_token(t));+ subscribe(scrips);+}++void NorenWebSocket::on_data_stall() {+ LOG_WARN("NorenWS", "Data stall detected — forcing reconnect");+ // Drop and re-open; WebSocketClient handles backoff, and resubscribe_all+ // fires again on the next auth ack.+ auth_ok_ = false;+ heartbeat_timer_.stop();+ ws_->disconnect();+ ws_->connect_to(ws_url_);+}++// ────────────────────────────────────────────────────────────────────────────+// Tick / depth parsing+// ────────────────────────────────────────────────────────────────────────────++void NorenWebSocket::handle_touchline(const QJsonObject& obj, bool full) {+ // `full` distinguishes tk (full snapshot) from tf (partial); merge_tick+ // handles the partial-overlay uniformly, so both are processed the same way.+ Q_UNUSED(full);+ const QString exchange = field_str(obj, "e");+ const QString token = field_str(obj, "tk");+ if (token.isEmpty())+ return;+ const QString key = exchange + "|" + token; // matches the scrip form++ BrokerQuote q;+ q.symbol = field_str(obj, "ts"); // present on full (tk) frames; blank on partial+ q.ltp = field_double(obj, "lp");+ q.open = field_double(obj, "o");+ q.high = field_double(obj, "h");+ q.low = field_double(obj, "l");+ q.close = field_double(obj, "c");+ q.volume = static_cast<double>(field_i64(obj, "v"));+ q.change_pct = field_double(obj, "pc");+ q.oi = field_i64(obj, "toi");+ // Feed time (ft) is an epoch-seconds string when present.+ const qint64 ft = field_i64(obj, "ft");+ q.timestamp = ft > 0 ? ft * 1000 : QDateTime::currentMSecsSinceEpoch();++ // Partial (tf) frames carry only changed fields; merge against last full tick.+ const BrokerQuote merged = merge_tick(key, q);+ note_tick();+ emit tick_received(merged);+}++void NorenWebSocket::handle_depth(const QJsonObject& obj, bool full) {+ // `full` distinguishes dk (full snapshot) from df (partial); merge_tick+ // handles the partial-overlay uniformly, so both are processed the same way.+ Q_UNUSED(full);+ const QString exchange = field_str(obj, "e");+ const QString token = field_str(obj, "tk");+ if (token.isEmpty())+ return;+ const QString key = exchange + "|" + token;++ // A depth frame also carries the touchline scalars (lp/o/h/l/c/v/pc/toi),+ // so feed them through merge_tick too — keeps the quote fresh for consumers+ // that subscribe to depth-only.+ BrokerQuote q;+ q.symbol = field_str(obj, "ts");+ q.ltp = field_double(obj, "lp");+ q.open = field_double(obj, "o");+ q.high = field_double(obj, "h");+ q.low = field_double(obj, "l");+ q.close = field_double(obj, "c");+ q.volume = static_cast<double>(field_i64(obj, "v"));+ q.change_pct = field_double(obj, "pc");+ q.oi = field_i64(obj, "toi");+ if (obj.contains("bp1"))+ q.bid = field_double(obj, "bp1");+ if (obj.contains("sp1"))+ q.ask = field_double(obj, "sp1");+ if (obj.contains("bq1"))+ q.bid_size = static_cast<double>(field_i64(obj, "bq1"));+ if (obj.contains("sq1"))+ q.ask_size = static_cast<double>(field_i64(obj, "sq1"));+ const qint64 ft = field_i64(obj, "ft");+ q.timestamp = ft > 0 ? ft * 1000 : QDateTime::currentMSecsSinceEpoch();++ const BrokerQuote merged = merge_tick(key, q);+ note_tick();+ emit tick_received(merged);++ // Build the 5-level order book. Partial (df) frames send only changed+ // levels; absent levels coerce to 0 and are skipped below, so a partial+ // book is still emitted with whatever changed — consumers that need a full+ // book should hold the last full (dk) snapshot.+ MarketDepth depth;+ depth.symbol = merged.symbol;+ depth.exchange = exchange;+ depth.ltp = merged.ltp;+ depth.volume = merged.volume;+ depth.oi = static_cast<double>(merged.oi);++ for (int i = 1; i <= 5; ++i) {+ const QByteArray bp = QByteArray("bp") + QByteArray::number(i);+ const QByteArray bq = QByteArray("bq") + QByteArray::number(i);+ const QByteArray bo = QByteArray("bo") + QByteArray::number(i);+ const QByteArray sp = QByteArray("sp") + QByteArray::number(i);+ const QByteArray sq = QByteArray("sq") + QByteArray::number(i);+ const QByteArray so = QByteArray("so") + QByteArray::number(i);++ const double bid_price = field_double(obj, bp.constData());+ if (bid_price > 0.0) {+ DepthLevel lvl;+ lvl.price = bid_price;+ lvl.quantity = field_int(obj, bq.constData());+ lvl.orders = field_int(obj, bo.constData());+ depth.bids.append(lvl);+ }+ const double ask_price = field_double(obj, sp.constData());+ if (ask_price > 0.0) {+ DepthLevel lvl;+ lvl.price = ask_price;+ lvl.quantity = field_int(obj, sq.constData());+ lvl.orders = field_int(obj, so.constData());+ depth.asks.append(lvl);+ }+ }++ if (!depth.bids.isEmpty() || !depth.asks.isEmpty())+ emit depth_received(depth);+}++QString NorenWebSocket::scrip_for_token(qint64 token) const {+ const QString exch = token_exchange_.value(token, default_exchange_);+ return exch + "|" + QString::number(token);+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/NorenWebSocket.h b/fincept-qt/src/trading/websocket/NorenWebSocket.hnew file mode 100644index 000000000..68f826ece--- /dev/null+++ b/fincept-qt/src/trading/websocket/NorenWebSocket.h@@ -0,0 +1,118 @@+#pragma once+#include "network/websocket/WebSocketClient.h"+#include "trading/websocket/BrokerWebSocketBase.h"++#include <QHash>+#include <QObject>+#include <QSet>+#include <QString>+#include <QStringList>+#include <QTimer>+#include <QVector>++namespace fincept::trading {++/// NorenWebSocket — shared base for brokers on the Noren / Omnesys platform.+///+/// AliceBlue and Shoonya both expose the same JSON-over-WebSocket "NorenWS"+/// streaming protocol, so the wire handling lives here once. Concrete brokers+/// subclass this and supply only the WS URL and (for AliceBlue) the susertoken+/// derivation.+///+/// Wire protocol (text frames, JSON):+/// Connect: {"t":"c","uid":<uid>,"actid":<actid>,"susertoken":<tok>,"source":"API"}+/// Ack: {"t":"ck"|"cf"|"ak","s":"OK"} (connect ok) — then we flush subs.+/// Touchline: {"t":"t","k":"NSE|12345#NSE|67890"} (# separated EXCH|TOKEN)+/// Depth: {"t":"d","k":"NSE|12345"}+/// Unsub: {"t":"u","k":...} touchline / {"t":"ud","k":...} depth+/// Heartbeat: {"t":"h"} every ~30s (broker requires one within ~50s)+/// Ticks: t = "tk"/"tf" (touchline full/partial), "dk"/"df" (depth full/partial)+/// tk=token, e=exchange, ts=symbol, lp=ltp, o/h/l/c, v=volume,+/// ap=avg, pc=pct change, toi=OI, bp1..bp5/bq1..bq5/bo1..bo5 (bid),+/// sp1..sp5/sq1..sq5/so1..so5 (ask). Partial (tf/df) frames carry+/// only changed fields — filled via BrokerWebSocketBase::merge_tick().+///+/// Usage:+/// auto* ws = new AliceBlueWebSocket(uid, actid, jwt, this); // or ShoonyaWebSocket+/// connect(ws, &NorenWebSocket::tick_received, this, &MyWidget::on_tick);+/// ws->subscribe({"NSE|22", "NSE|2885"});+/// ws->open();+class NorenWebSocket : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// @param ws_url broker NorenWS endpoint+ /// @param user_id uid sent in the connect frame+ /// @param account_id actid sent in the connect frame+ /// @param susertoken session token (raw); derive_susertoken() may transform it+ NorenWebSocket(const QString& ws_url, const QString& user_id, const QString& account_id,+ const QString& susertoken, QObject* parent = nullptr);++ void open() override;+ void close() override;+ bool is_connected() const override;++ // Symbol-based subscribe — scrips are "EXCHANGE|TOKEN" strings (Noren native form).+ // Subscribes both touchline and depth so consumers get quotes + order book.+ void subscribe(const QStringList& scrips);++ // Token-based subscribe (BrokerWebSocketBase contract). Tokens are mapped to+ // scrips via the exchange supplied with set_exchange_for_tokens(); when no+ // mapping exists they default to the exchange set by set_default_exchange().+ void subscribe(const QVector<qint64>& tokens) override;++ void unsubscribe() override;+ void unsubscribe(const QStringList& scrips);++ /// Default exchange used when a token-based subscribe has no per-token mapping.+ void set_default_exchange(const QString& exchange) { default_exchange_ = exchange; }++ /// Provide the exchange for specific tokens so subscribe(QVector<qint64>) can+ /// build "EXCHANGE|TOKEN" scrips.+ void set_exchange_for_token(qint64 token, const QString& exchange);++ protected:+ /// Derive the susertoken sent in the connect frame from the raw session+ /// token. Default is identity (Shoonya). AliceBlue overrides with double+ /// SHA256 of the JWT.+ virtual QString derive_susertoken(const QString& raw) const { return raw; }++ /// uid value for the connect frame. AliceBlue overrides to append "_API".+ virtual QString connect_uid() const { return user_id_; }++ /// actid value for the connect frame. AliceBlue overrides to append "_API".+ virtual QString connect_actid() const { return account_id_; }++ void on_data_stall() override;+ void flush_subscribe_queue() override;++ private slots:+ void on_ws_connected();+ void on_ws_disconnected();+ void on_ws_message(const QString& message);++ private:+ void send_connect_frame();+ void send_heartbeat();+ void resubscribe_all();+ void handle_touchline(const QJsonObject& obj, bool full);+ void handle_depth(const QJsonObject& obj, bool full);+ QString scrip_for_token(qint64 token) const;++ QString ws_url_;+ QString user_id_;+ QString account_id_;+ QString susertoken_raw_;+ QString default_exchange_ = "NSE";++ WebSocketClient* ws_ = nullptr;+ QTimer heartbeat_timer_;+ bool auth_ok_ = false;++ QSet<QString> subscribed_scrips_; // all "EXCHANGE|TOKEN" we want active+ QHash<qint64, QString> token_exchange_; // token → exchange override++ static constexpr int kHeartbeatMs = 30000; // send {"t":"h"} every 30s+ static constexpr int kSubscribeBatch = 100; // # scrips per touchline/depth frame+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/ShoonyaWebSocket.cpp b/fincept-qt/src/trading/websocket/ShoonyaWebSocket.cppnew file mode 100644index 000000000..f958da2e7--- /dev/null+++ b/fincept-qt/src/trading/websocket/ShoonyaWebSocket.cpp@@ -0,0 +1,13 @@+#include "trading/websocket/ShoonyaWebSocket.h"++namespace fincept::trading {++ShoonyaWebSocket::ShoonyaWebSocket(const QString& user_id, const QString& account_id,+ const QString& susertoken, QObject* parent)+ // Shoonya uses the NorenWS protocol verbatim — no susertoken transform and+ // no "_API" suffix on uid/actid, so the NorenWebSocket defaults apply.+ : NorenWebSocket(QString::fromLatin1(kWsUrl), user_id, account_id, susertoken, parent) {+ set_default_exchange("NSE");+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/ShoonyaWebSocket.h b/fincept-qt/src/trading/websocket/ShoonyaWebSocket.hnew file mode 100644index 000000000..fcf137b07--- /dev/null+++ b/fincept-qt/src/trading/websocket/ShoonyaWebSocket.h@@ -0,0 +1,34 @@+#pragma once+#include "trading/websocket/NorenWebSocket.h"++#include <QObject>+#include <QString>++namespace fincept::trading {++/// ShoonyaWebSocket — Noren streaming adapter for Shoonya (Finvasia).+///+/// Shoonya runs the standard NorenWS protocol (see NorenWebSocket) with no+/// broker-specific transforms: the susertoken sent in the connect frame is the+/// session token returned at login (used verbatim), and uid / actid are the+/// login user id and account id as-is.+///+/// Usage:+/// auto* ws = new ShoonyaWebSocket(user_id, account_id, susertoken, this);+/// connect(ws, &ShoonyaWebSocket::tick_received, this, &MyWidget::on_tick);+/// ws->subscribe({"NSE|22", "NSE|2885"});+/// ws->open();+class ShoonyaWebSocket : public NorenWebSocket {+ Q_OBJECT+ public:+ /// @param user_id Shoonya login user id (uid)+ /// @param account_id Shoonya account id (actid)+ /// @param susertoken session token from login (sent verbatim)+ ShoonyaWebSocket(const QString& user_id, const QString& account_id, const QString& susertoken,+ QObject* parent = nullptr);++ private:+ static constexpr const char* kWsUrl = "wss://api.shoonya.com/NorenWSTP/";+};++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/UpstoxWebSocket.cpp b/fincept-qt/src/trading/websocket/UpstoxWebSocket.cppnew file mode 100644index 000000000..84e8abfa7--- /dev/null+++ b/fincept-qt/src/trading/websocket/UpstoxWebSocket.cpp@@ -0,0 +1,836 @@+// UpstoxWebSocket — Upstox V3 Protobuf3 market-data streaming adapter.+//+// See the header for the protocol summary. OpenAlgo reference:+// broker/upstox/streaming/upstox_websocket.py+// broker/upstox/streaming/upstox_adapter.py+// broker/upstox/streaming/MarketDataFeedV3.proto+//+// Protobuf is NOT linked into the Fincept build, so the FeedResponse message is+// decoded with a minimal hand-rolled wire-format reader (anonymous namespace+// below). All field numbers come straight from MarketDataFeedV3.proto.++#include "trading/websocket/UpstoxWebSocket.h"++#include "core/logging/Logger.h"+#include "network/websocket/WebSocketClient.h"+#include "trading/brokers/BrokerHttp.h"+#include "trading/instruments/InstrumentService.h"++#include <QByteArray>+#include <QDateTime>+#include <QJsonArray>+#include <QJsonDocument>+#include <QJsonObject>+#include <QMap>+#include <QMetaObject>+#include <QPointer>+#include <QUuid>+#include <QtConcurrent/QtConcurrent>++#include <algorithm>+#include <cstdint>+#include <cstring>+#include <vector>++namespace fincept::trading {++static constexpr const char* TAG_UPSTOX_WS = "UpstoxWS";++// ─────────────────────────────────────────────────────────────────────────────+// Minimal Protobuf wire-format reader+//+// Protobuf encodes each field as a varint tag (field_number << 3 | wire_type)+// followed by the value. Wire types:+// 0 = varint (int32/int64/bool/enum)+// 1 = 64-bit (double / fixed64)+// 2 = length-delimited (string / bytes / embedded message / packed)+// 5 = 32-bit (float / fixed32)+//+// We only decode the fields needed to populate BrokerQuote + MarketDepth from+// MarketDataFeedV3.FeedResponse. Submessages are decoded recursively by handing+// each handler the raw byte slice of the embedded message.+// ─────────────────────────────────────────────────────────────────────────────+namespace {++// Decoded LTPC (last traded price + close).+struct PbLtpc {+ double ltp = 0.0; // field 1+ int64_t ltt = 0; // field 2 (epoch ms)+ int64_t ltq = 0; // field 3+ double cp = 0.0; // field 4 (previous close)+ bool present = false;+};++// One level of the bid/ask ladder (MarketDataFeedV3.Quote).+struct PbQuote {+ int64_t bidQ = 0; // field 1+ double bidP = 0.0; // field 2+ int64_t askQ = 0; // field 3+ double askP = 0.0; // field 4+};++// One OHLC bucket (MarketDataFeedV3.OHLC).+struct PbOhlc {+ QString interval; // field 1+ double open = 0.0; // field 2+ double high = 0.0; // field 3+ double low = 0.0; // field 4+ double close = 0.0; // field 5+ int64_t vol = 0; // field 6+ int64_t ts = 0; // field 7+};++// Aggregated decode of a single Feed for one instrument key.+struct PbFeed {+ PbLtpc ltpc;+ double atp = 0.0; // MarketFullFeed.atp (field 5)+ int64_t vtt = 0; // MarketFullFeed.vtt (field 6, volume traded today)+ double oi = 0.0; // MarketFullFeed.oi (field 7)+ double tbq = 0.0; // MarketFullFeed.tbq (field 9)+ double tsq = 0.0; // MarketFullFeed.tsq (field 10)+ std::vector<PbOhlc> ohlc; // MarketOHLC.ohlc (repeated)+ std::vector<PbQuote> bidAsk; // MarketLevel.bidAskQuote (repeated, up to 5)+ bool hasFullFeed = false;+};++class ProtoReader {+ public:+ ProtoReader(const uint8_t* data, size_t len) : p_(data), end_(data + len) {}++ bool at_end() const { return p_ >= end_; }++ // Read the next field tag. Returns false at end / on corruption.+ bool next_tag(uint32_t& field_number, uint32_t& wire_type) {+ if (p_ >= end_)+ return false;+ uint64_t tag = 0;+ if (!read_varint(tag))+ return false;+ field_number = static_cast<uint32_t>(tag >> 3);+ wire_type = static_cast<uint32_t>(tag & 0x7);+ return true;+ }++ bool read_varint(uint64_t& out) {+ out = 0;+ int shift = 0;+ while (p_ < end_ && shift < 64) {+ uint8_t b = *p_++;+ out |= static_cast<uint64_t>(b & 0x7F) << shift;+ if (!(b & 0x80))+ return true;+ shift += 7;+ }+ return false;+ }++ bool read_double(double& out) {+ if (p_ + 8 > end_)+ return false;+ uint64_t bits = 0;+ std::memcpy(&bits, p_, 8); // little-endian on all supported platforms+ std::memcpy(&out, &bits, 8);+ p_ += 8;+ return true;+ }++ bool read_float(float& out) {+ if (p_ + 4 > end_)+ return false;+ uint32_t bits = 0;+ std::memcpy(&bits, p_, 4);+ std::memcpy(&out, &bits, 4);+ p_ += 4;+ return true;+ }++ // Read a length-delimited slice (string / bytes / submessage) without copy.+ bool read_bytes(const uint8_t*& begin, size_t& length) {+ uint64_t len = 0;+ if (!read_varint(len))+ return false;+ if (p_ + len > end_)+ return false;+ begin = p_;+ length = static_cast<size_t>(len);+ p_ += len;+ return true;+ }++ // Skip a field whose value we do not care about, given its wire type.+ bool skip(uint32_t wire_type) {+ switch (wire_type) {+ case 0: { // varint+ uint64_t v;+ return read_varint(v);+ }+ case 1: // 64-bit+ if (p_ + 8 > end_)+ return false;+ p_ += 8;+ return true;+ case 2: { // length-delimited+ const uint8_t* b;+ size_t l;+ return read_bytes(b, l);+ }+ case 5: // 32-bit+ if (p_ + 4 > end_)+ return false;+ p_ += 4;+ return true;+ default:+ return false; // groups (3/4) are not used by this schema+ }+ }++ private:+ const uint8_t* p_;+ const uint8_t* end_;+};++// LTPC { ltp=1 double, ltt=2 int64, ltq=3 int64, cp=4 double }+PbLtpc decode_ltpc(const uint8_t* data, size_t len) {+ PbLtpc out;+ out.present = true;+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ if (fn == 1 && wt == 1) {+ r.read_double(out.ltp);+ } else if (fn == 2 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ out.ltt = static_cast<int64_t>(v);+ } else if (fn == 3 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ out.ltq = static_cast<int64_t>(v);+ } else if (fn == 4 && wt == 1) {+ r.read_double(out.cp);+ } else if (!r.skip(wt)) {+ break;+ }+ }+ return out;+}++// Quote { bidQ=1 int64, bidP=2 double, askQ=3 int64, askP=4 double }+PbQuote decode_quote(const uint8_t* data, size_t len) {+ PbQuote out;+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ if (fn == 1 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ out.bidQ = static_cast<int64_t>(v);+ } else if (fn == 2 && wt == 1) {+ r.read_double(out.bidP);+ } else if (fn == 3 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ out.askQ = static_cast<int64_t>(v);+ } else if (fn == 4 && wt == 1) {+ r.read_double(out.askP);+ } else if (!r.skip(wt)) {+ break;+ }+ }+ return out;+}++// OHLC { interval=1 string, open=2, high=3, low=4, close=5 double, vol=6 int64, ts=7 int64 }+PbOhlc decode_ohlc(const uint8_t* data, size_t len) {+ PbOhlc out;+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ if (fn == 1 && wt == 2) {+ const uint8_t* b;+ size_t l;+ if (r.read_bytes(b, l))+ out.interval = QString::fromUtf8(reinterpret_cast<const char*>(b), int(l));+ } else if (fn == 2 && wt == 1) {+ r.read_double(out.open);+ } else if (fn == 3 && wt == 1) {+ r.read_double(out.high);+ } else if (fn == 4 && wt == 1) {+ r.read_double(out.low);+ } else if (fn == 5 && wt == 1) {+ r.read_double(out.close);+ } else if (fn == 6 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ out.vol = static_cast<int64_t>(v);+ } else if (fn == 7 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ out.ts = static_cast<int64_t>(v);+ } else if (!r.skip(wt)) {+ break;+ }+ }+ return out;+}++// MarketLevel { bidAskQuote=1 repeated Quote }+void decode_market_level(const uint8_t* data, size_t len, PbFeed& feed) {+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ if (fn == 1 && wt == 2) {+ const uint8_t* b;+ size_t l;+ if (r.read_bytes(b, l))+ feed.bidAsk.push_back(decode_quote(b, l));+ } else if (!r.skip(wt)) {+ break;+ }+ }+}++// MarketOHLC { ohlc=1 repeated OHLC }+void decode_market_ohlc(const uint8_t* data, size_t len, PbFeed& feed) {+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ if (fn == 1 && wt == 2) {+ const uint8_t* b;+ size_t l;+ if (r.read_bytes(b, l))+ feed.ohlc.push_back(decode_ohlc(b, l));+ } else if (!r.skip(wt)) {+ break;+ }+ }+}++// MarketFullFeed {+// ltpc=1, marketLevel=2, optionGreeks=3, marketOHLC=4,+// atp=5 double, vtt=6 int64, oi=7 double, iv=8, tbq=9 double, tsq=10 double }+// IndexFullFeed { ltpc=1, marketOHLC=2 } — handled by the same reader because+// the overlapping field numbers (1=ltpc) decode identically and the+// non-overlapping ones (index marketOHLC=2 vs market marketLevel=2) are+// distinguished by their submessage content; for indices we only need ltpc+ohlc.+void decode_full_feed_inner(const uint8_t* data, size_t len, PbFeed& feed, bool is_index) {+ feed.hasFullFeed = true;+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ const uint8_t* b;+ size_t l;+ if (fn == 1 && wt == 2) { // ltpc (both market + index)+ if (r.read_bytes(b, l))+ feed.ltpc = decode_ltpc(b, l);+ } else if (!is_index && fn == 2 && wt == 2) { // MarketFullFeed.marketLevel+ if (r.read_bytes(b, l))+ decode_market_level(b, l, feed);+ } else if (is_index && fn == 2 && wt == 2) { // IndexFullFeed.marketOHLC+ if (r.read_bytes(b, l))+ decode_market_ohlc(b, l, feed);+ } else if (!is_index && fn == 4 && wt == 2) { // MarketFullFeed.marketOHLC+ if (r.read_bytes(b, l))+ decode_market_ohlc(b, l, feed);+ } else if (!is_index && fn == 5 && wt == 1) {+ r.read_double(feed.atp);+ } else if (!is_index && fn == 6 && wt == 0) {+ uint64_t v;+ r.read_varint(v);+ feed.vtt = static_cast<int64_t>(v);+ } else if (!is_index && fn == 7 && wt == 1) {+ r.read_double(feed.oi);+ } else if (!is_index && fn == 9 && wt == 1) {+ r.read_double(feed.tbq);+ } else if (!is_index && fn == 10 && wt == 1) {+ r.read_double(feed.tsq);+ } else if (!r.skip(wt)) {+ break;+ }+ }+}++// FullFeed { oneof { marketFF=1, indexFF=2 } }+void decode_full_feed(const uint8_t* data, size_t len, PbFeed& feed) {+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ const uint8_t* b;+ size_t l;+ if (fn == 1 && wt == 2) { // marketFF+ if (r.read_bytes(b, l))+ decode_full_feed_inner(b, l, feed, /*is_index=*/false);+ } else if (fn == 2 && wt == 2) { // indexFF+ if (r.read_bytes(b, l))+ decode_full_feed_inner(b, l, feed, /*is_index=*/true);+ } else if (!r.skip(wt)) {+ break;+ }+ }+}++// FirstLevelWithGreeks { ltpc=1, firstDepth=2 Quote, optionGreeks=3, vtt=4, oi=5, iv=6 }+void decode_first_level(const uint8_t* data, size_t len, PbFeed& feed) {+ feed.hasFullFeed = true;+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ const uint8_t* b;+ size_t l;+ if (fn == 1 && wt == 2) { // ltpc+ if (r.read_bytes(b, l))+ feed.ltpc = decode_ltpc(b, l);+ } else if (fn == 2 && wt == 2) { // firstDepth (single Quote → one ladder level)+ if (r.read_bytes(b, l))+ feed.bidAsk.push_back(decode_quote(b, l));+ } else if (fn == 4 && wt == 0) { // vtt+ uint64_t v;+ r.read_varint(v);+ feed.vtt = static_cast<int64_t>(v);+ } else if (fn == 5 && wt == 1) { // oi+ r.read_double(feed.oi);+ } else if (!r.skip(wt)) {+ break;+ }+ }+}++// Feed { oneof { ltpc=1, fullFeed=2, firstLevelWithGreeks=3 } requestMode=4 }+PbFeed decode_feed(const uint8_t* data, size_t len) {+ PbFeed feed;+ ProtoReader r(data, len);+ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ const uint8_t* b;+ size_t l;+ if (fn == 1 && wt == 2) { // ltpc (mode=ltpc)+ if (r.read_bytes(b, l))+ feed.ltpc = decode_ltpc(b, l);+ } else if (fn == 2 && wt == 2) { // fullFeed (mode=full)+ if (r.read_bytes(b, l))+ decode_full_feed(b, l, feed);+ } else if (fn == 3 && wt == 2) { // firstLevelWithGreeks (mode=option_greeks)+ if (r.read_bytes(b, l))+ decode_first_level(b, l, feed);+ } else if (!r.skip(wt)) {+ break;+ }+ }+ return feed;+}++} // anonymous namespace++// ─────────────────────────────────────────────────────────────────────────────+// Construction+// ─────────────────────────────────────────────────────────────────────────────++UpstoxWebSocket::UpstoxWebSocket(const QString& access_token, QObject* parent)+ : BrokerWebSocketBase(parent), access_token_(access_token) {+ ws_ = new WebSocketClient(this);+ connect(ws_, &WebSocketClient::connected, this, &UpstoxWebSocket::on_connected);+ connect(ws_, &WebSocketClient::disconnected, this, &UpstoxWebSocket::on_disconnected);+ connect(ws_, &WebSocketClient::binary_message_received, this, &UpstoxWebSocket::on_binary_message);+ connect(ws_, &WebSocketClient::message_received, this, &UpstoxWebSocket::on_text_message);+ connect(ws_, &WebSocketClient::error_occurred, this, &UpstoxWebSocket::error_occurred);+}++UpstoxWebSocket::~UpstoxWebSocket() = default;++// ─────────────────────────────────────────────────────────────────────────────+// Public API+// ─────────────────────────────────────────────────────────────────────────────++void UpstoxWebSocket::open() {+ if (connecting_) {+ LOG_DEBUG(TAG_UPSTOX_WS, "open() ignored — authorize already in flight");+ return;+ }+ connecting_ = true;+ LOG_INFO(TAG_UPSTOX_WS, "Authorizing market-data feed");++ // The authorize REST call (BrokerHttp) is synchronous, so run it on a worker+ // thread and connect on the UI thread (P1 / P8: never block UI, QPointer guard).+ QPointer<UpstoxWebSocket> self = this;+ (void)QtConcurrent::run([self]() {+ if (!self)+ return;+ QString url = self->fetch_ws_url();+ if (!self)+ return;+ QMetaObject::invokeMethod(+ self,+ [self, url]() {+ if (!self)+ return;+ self->connecting_ = false;+ if (url.isEmpty()) {+ LOG_ERROR(TAG_UPSTOX_WS, "Failed to obtain WS URL from authorize endpoint");+ emit self->error_occurred(QStringLiteral("Upstox feed authorize failed"));+ return;+ }+ self->ws_url_ = url;+ LOG_INFO(TAG_UPSTOX_WS, "Connecting to authorized feed URI");+ self->ws_->connect_to(url);+ self->start_health_check();+ },+ Qt::QueuedConnection);+ });+}++void UpstoxWebSocket::close() {+ stop_health_check();+ ws_->disconnect();+}++bool UpstoxWebSocket::is_connected() const {+ return ws_->is_connected();+}++void UpstoxWebSocket::subscribe(const QStringList& instrument_keys, const QString& mode) {+ QStringList fresh;+ for (const QString& key : instrument_keys) {+ if (key.isEmpty())+ continue;+ if (!subscriptions_.contains(key)) {+ subscriptions_.insert(key, mode);+ fresh.append(key);+ }+ }+ if (!fresh.isEmpty() && is_connected())+ send_subscription(fresh, QStringLiteral("sub"), mode);+}++void UpstoxWebSocket::subscribe(const QVector<qint64>& tokens) {+ // Resolve each numeric token to an Upstox instrument key ("SEGMENT|TOKEN").+ auto& svc = InstrumentService::instance();+ QStringList keys;+ for (qint64 token : tokens) {+ auto inst = svc.find_by_token(static_cast<quint32>(token), "upstox");+ if (inst.has_value()) {+ // Build SEGMENT|TOKEN. brexchange is the Upstox segment (NSE_EQ, …);+ // fall back to NSE_EQ when missing.+ QString seg = inst->brexchange.isEmpty() ? QStringLiteral("NSE_EQ") : inst->brexchange;+ keys.append(seg + "|" + QString::number(token));+ } else {+ LOG_WARN(TAG_UPSTOX_WS,+ QString("No instrument for token %1 — skipping subscribe").arg(token));+ }+ }+ if (!keys.isEmpty())+ subscribe(keys, QStringLiteral("full"));+}++void UpstoxWebSocket::unsubscribe() {+ if (subscriptions_.isEmpty())+ return;+ if (is_connected())+ send_subscription(subscriptions_.keys(), QStringLiteral("unsub"), QString());+ subscriptions_.clear();+ clear_tick_cache();+}++void UpstoxWebSocket::unsubscribe(const QStringList& instrument_keys) {+ QStringList removed;+ for (const QString& key : instrument_keys) {+ if (subscriptions_.remove(key))+ removed.append(key);+ }+ if (!removed.isEmpty() && is_connected())+ send_subscription(removed, QStringLiteral("unsub"), QString());+}++// ─────────────────────────────────────────────────────────────────────────────+// Base-class hooks+// ─────────────────────────────────────────────────────────────────────────────++void UpstoxWebSocket::on_data_stall() {+ LOG_WARN(TAG_UPSTOX_WS, "Data stall — forcing reconnect");+ ws_->disconnect();+ open(); // re-authorize: the WS URL is single-use / time-limited+}++// ─────────────────────────────────────────────────────────────────────────────+// Slots+// ─────────────────────────────────────────────────────────────────────────────++void UpstoxWebSocket::on_connected() {+ LOG_INFO(TAG_UPSTOX_WS, "Connected — replaying subscriptions");+ resubscribe_all();+ emit connected();+}++void UpstoxWebSocket::on_disconnected() {+ LOG_WARN(TAG_UPSTOX_WS, "Disconnected");+ emit disconnected();+}++void UpstoxWebSocket::on_binary_message(const QByteArray& data) {+ parse_feed_response(data);+}++void UpstoxWebSocket::on_text_message(const QString& msg) {+ // Upstox normally streams binary protobuf. The only text frames are control+ // / error envelopes: {"status":"failed","error":"...","method":"sub"}.+ QJsonParseError err;+ QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8(), &err);+ if (err.error != QJsonParseError::NoError || !doc.isObject())+ return;+ QJsonObject obj = doc.object();+ if (obj.value("status").toString() == QLatin1String("failed")) {+ const QString method = obj.value("method").toString();+ const QString error = obj.value("error").toString();+ LOG_ERROR(TAG_UPSTOX_WS, QString("%1 failed: %2").arg(method, error));+ emit error_occurred(QString("Upstox %1 failed: %2").arg(method, error));+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// REST authorize+// ─────────────────────────────────────────────────────────────────────────────++QString UpstoxWebSocket::fetch_ws_url() const {+ QMap<QString, QString> headers;+ headers["Accept"] = "application/json";+ headers["Authorization"] = "Bearer " + access_token_;++ BrokerHttpResponse resp = BrokerHttp::instance().get(kAuthEndpoint, headers);+ if (!resp.success) {+ LOG_ERROR(TAG_UPSTOX_WS,+ QString("Authorize HTTP %1: %2").arg(resp.status_code).arg(resp.error));+ return QString();+ }+ // { "status":"success", "data": { "authorized_redirect_uri": "wss://..." } }+ const QString uri =+ resp.json.value("data").toObject().value("authorized_redirect_uri").toString();+ if (uri.isEmpty())+ LOG_ERROR(TAG_UPSTOX_WS, "authorize response missing authorized_redirect_uri");+ return uri;+}++// ─────────────────────────────────────────────────────────────────────────────+// Wire senders+// ─────────────────────────────────────────────────────────────────────────────++void UpstoxWebSocket::send_subscription(const QStringList& instrument_keys, const QString& method,+ const QString& mode) {+ if (instrument_keys.isEmpty())+ return;++ const int total = static_cast<int>(instrument_keys.size());+ for (int start = 0; start < total; start += kSubscribeBatch) {+ QJsonArray keys;+ const int stop = std::min(start + kSubscribeBatch, total);+ for (int i = start; i < stop; ++i)+ keys.append(instrument_keys[i]);++ QJsonObject data;+ data["instrumentKeys"] = keys;+ if (method == QLatin1String("sub") && !mode.isEmpty())+ data["mode"] = mode;++ QJsonObject envelope;+ // guid: first 20 hex chars of a UUID (matches the python client).+ envelope["guid"] = QUuid::createUuid().toString(QUuid::Id128).left(20);+ envelope["method"] = method;+ envelope["data"] = data;++ // Upstox expects the JSON sent as a BINARY frame.+ ws_->send_binary(QJsonDocument(envelope).toJson(QJsonDocument::Compact));+ }+ LOG_INFO(TAG_UPSTOX_WS, QString("%1 %2 instrument(s)%3")+ .arg(method == QLatin1String("sub") ? "Subscribed" : "Unsubscribed")+ .arg(instrument_keys.size())+ .arg(mode.isEmpty() ? QString() : QString(" (%1)").arg(mode)));+}++void UpstoxWebSocket::resubscribe_all() {+ if (subscriptions_.isEmpty())+ return;+ // Group instrument keys by requested mode so each mode collapses to one+ // (or a few, batched) subscribe frame.+ QMap<QString, QStringList> by_mode;+ for (auto it = subscriptions_.cbegin(); it != subscriptions_.cend(); ++it)+ by_mode[it.value()].append(it.key());+ for (auto it = by_mode.cbegin(); it != by_mode.cend(); ++it)+ send_subscription(it.value(), QStringLiteral("sub"), it.key());+}++// ─────────────────────────────────────────────────────────────────────────────+// Protobuf → tick / depth+// ─────────────────────────────────────────────────────────────────────────────++void UpstoxWebSocket::parse_feed_response(const QByteArray& data) {+ // FeedResponse { type=1 enum, feeds=2 map<string,Feed>, currentTs=3 int64,+ // marketInfo=4 }. The feeds map is encoded as a repeated+ // length-delimited entry message { key=1 string, value=2 Feed }.+ const uint8_t* buf = reinterpret_cast<const uint8_t*>(data.constData());+ ProtoReader r(buf, static_cast<size_t>(data.size()));++ int64_t current_ts = 0;+ int feed_count = 0;++ uint32_t fn, wt;+ while (r.next_tag(fn, wt)) {+ const uint8_t* b;+ size_t l;+ if (fn == 2 && wt == 2) { // feeds map entry+ if (!r.read_bytes(b, l))+ break;+ // Decode one map entry: field 1 = key (string), field 2 = Feed.+ ProtoReader entry(b, l);+ QString instrument_key;+ PbFeed feed;+ bool have_feed = false;+ uint32_t efn, ewt;+ while (entry.next_tag(efn, ewt)) {+ const uint8_t* eb;+ size_t el;+ if (efn == 1 && ewt == 2) {+ if (entry.read_bytes(eb, el))+ instrument_key = QString::fromUtf8(reinterpret_cast<const char*>(eb), int(el));+ } else if (efn == 2 && ewt == 2) {+ if (entry.read_bytes(eb, el)) {+ feed = decode_feed(eb, el);+ have_feed = true;+ }+ } else if (!entry.skip(ewt)) {+ break;+ }+ }+ if (have_feed && !instrument_key.isEmpty()) {+ ++feed_count;+ // current_ts may not have been parsed yet (field order in the+ // wire is type → feeds → currentTs), so we defer the emit until+ // after the full pass. To keep things simple we emit inline and+ // fall back to "now" when currentTs is still 0; the merge cache+ // preserves a sensible timestamp regardless.+ QString symbol, exchange;+ enrich_symbol(instrument_key, symbol, exchange);++ note_tick();++ BrokerQuote partial;+ partial.symbol = symbol;+ partial.ltp = feed.ltpc.ltp;+ partial.close = feed.ltpc.cp;+ partial.oi = static_cast<qint64>(feed.oi);+ partial.volume = static_cast<double>(feed.vtt);+ partial.timestamp = feed.ltpc.ltt != 0 ? feed.ltpc.ltt : current_ts;++ if (feed.hasFullFeed) {+ // Prefer the 1d OHLC bucket; fall back to the first bucket.+ const PbOhlc* chosen = nullptr;+ for (const auto& o : feed.ohlc) {+ if (o.interval == QLatin1String("1d")) {+ chosen = &o;+ break;+ }+ }+ if (!chosen && !feed.ohlc.empty())+ chosen = &feed.ohlc.front();+ if (chosen) {+ partial.open = chosen->open;+ partial.high = chosen->high;+ partial.low = chosen->low;+ if (partial.close == 0)+ partial.close = chosen->close;+ if (partial.volume == 0)+ partial.volume = static_cast<double>(chosen->vol);+ if (partial.timestamp == 0)+ partial.timestamp = chosen->ts;+ }+ // Top-of-book bid/ask from the first ladder level.+ if (!feed.bidAsk.empty()) {+ const PbQuote& top = feed.bidAsk.front();+ partial.bid = top.bidP;+ partial.ask = top.askP;+ partial.bid_size = static_cast<double>(top.bidQ);+ partial.ask_size = static_cast<double>(top.askQ);+ }+ }++ BrokerQuote merged = merge_tick(instrument_key, partial);+ if (merged.timestamp == 0)+ merged.timestamp = QDateTime::currentMSecsSinceEpoch();+ emit tick_received(merged);++ // Emit depth when a ladder is present (full mode).+ if (!feed.bidAsk.empty()) {+ MarketDepth depth;+ depth.symbol = symbol;+ depth.exchange = exchange;+ depth.ltp = merged.ltp;+ depth.volume = merged.volume;+ depth.oi = static_cast<double>(merged.oi);+ for (const PbQuote& q : feed.bidAsk) {+ if (q.bidP > 0) {+ DepthLevel lvl;+ lvl.price = q.bidP;+ lvl.quantity = static_cast<int>(q.bidQ);+ lvl.orders = 0; // Upstox V3 ladder does not carry order count+ depth.bids.append(lvl);+ }+ if (q.askP > 0) {+ DepthLevel lvl;+ lvl.price = q.askP;+ lvl.quantity = static_cast<int>(q.askQ);+ lvl.orders = 0;+ depth.asks.append(lvl);+ }+ }+ emit depth_received(depth);+ }+ }+ } else if (fn == 3 && wt == 0) { // currentTs+ uint64_t v;+ if (!r.read_varint(v))+ break;+ current_ts = static_cast<int64_t>(v);+ } else if (!r.skip(wt)) {+ break;+ }+ }++ if (feed_count == 0)+ LOG_DEBUG(TAG_UPSTOX_WS, "FeedResponse with no decodable feeds (control/market-info frame)");+}++void UpstoxWebSocket::enrich_symbol(const QString& instrument_key, QString& symbol,+ QString& exchange) const {+ // instrument_key = "SEGMENT|TOKEN" (e.g. "NSE_EQ|256265" or "NSE_EQ|INE002A01018").+ symbol = instrument_key;+ exchange.clear();++ const int bar = instrument_key.indexOf('|');+ if (bar < 0)+ return;+ const QString seg = instrument_key.left(bar);+ const QString token_part = instrument_key.mid(bar + 1);++ // Canonical exchange from the Upstox segment.+ static const QMap<QString, QString> seg_map = {+ {"NSE_EQ", "NSE"}, {"BSE_EQ", "BSE"}, {"NSE_FO", "NFO"},+ {"BSE_FO", "BFO"}, {"NSE_CD", "CDS"}, {"MCX_FO", "MCX"},+ {"NSE_INDEX", "NSE_INDEX"}, {"BSE_INDEX", "BSE_INDEX"},+ };+ exchange = seg_map.value(seg, seg);++ // Try to resolve the display symbol via InstrumentService when the token+ // part is numeric (an instrument_token).+ bool numeric = false;+ const qlonglong token = token_part.toLongLong(&numeric);+ if (numeric) {+ auto inst = InstrumentService::instance().find_by_token(static_cast<quint32>(token), "upstox");+ if (inst.has_value()) {+ symbol = inst->symbol;+ if (!inst->exchange.isEmpty())+ exchange = inst->exchange;+ return;+ }+ }+ // Non-numeric token part is usually the symbol/ISIN already.+ symbol = token_part;+}++} // namespace fincept::tradingdiff --git a/fincept-qt/src/trading/websocket/UpstoxWebSocket.h b/fincept-qt/src/trading/websocket/UpstoxWebSocket.hnew file mode 100644index 000000000..32bd88b7a--- /dev/null+++ b/fincept-qt/src/trading/websocket/UpstoxWebSocket.h@@ -0,0 +1,115 @@+#pragma once+// UpstoxWebSocket — Upstox V3 market-data streaming adapter (Protobuf3 over WS).+//+// Port of OpenAlgo's upstox_websocket.py + upstox_adapter.py to the Fincept+// BrokerWebSocketBase contract. Unlike the JSON/binary-struct adapters, Upstox+// delivers ticks as binary Protobuf3 (MarketDataFeedV3.FeedResponse) frames.+//+// Protocol summary:+// 1. The WS URL is dynamic. open() does a REST authorize call:+// GET https://api.upstox.com/v3/feed/market-data-feed/authorize+// Authorization: Bearer <access_token>+// The response carries data.authorized_redirect_uri — the pre-authenticated+// wss:// endpoint. We do this blocking REST call on a worker thread+// (QtConcurrent + QPointer guard) and connect on the UI thread.+// 2. Subscribe by sending a *binary* frame whose payload is the JSON bytes:+// {"guid":"<20 hex chars>","method":"sub",+// "data":{"instrumentKeys":["NSE_EQ|INE002A01018"],"mode":"ltpc"|"full"}}+// Upstox expects the JSON as a binary WS frame (not a text frame).+// 3. Ticks arrive as binary Protobuf FeedResponse. `feeds` is a+// map<string instrumentKey, Feed>. Each Feed carries either an LTPC+// (mode=ltpc) or a fullFeed.marketFF (mode=full) with OHLC, volume,+// avg/atp, OI and a 5-level bid/ask depth ladder.+//+// Subscriptions are keyed by Upstox instrument key strings ("SEGMENT|TOKEN").+// The token-based subscribe(QVector<qint64>) override resolves each token to an+// instrument key via InstrumentService (matching UpstoxBroker's mapping); the+// native subscribe(QStringList) takes instrument keys directly.+//+// Protobuf parsing is hand-rolled (no protobuf library is linked into the+// project) — see the anonymous-namespace ProtoReader in the .cpp. Field numbers+// are taken from MarketDataFeedV3.proto.++#include "trading/websocket/BrokerWebSocketBase.h"++#include <QHash>+#include <QSet>+#include <QString>+#include <QStringList>+#include <QVector>++namespace fincept {++class WebSocketClient;++namespace trading {++class UpstoxWebSocket : public BrokerWebSocketBase {+ Q_OBJECT+ public:+ /// @param access_token Upstox V3 OAuth access token (Bearer).+ explicit UpstoxWebSocket(const QString& access_token, QObject* parent = nullptr);+ ~UpstoxWebSocket() override;++ void open() override;+ void close() override;+ bool is_connected() const override;++ /// Native subscribe — instrument keys are "SEGMENT|TOKEN" strings+ /// (e.g. "NSE_EQ|INE002A01018"). `full` mode also yields OHLC + depth;+ /// `ltpc` mode yields only last-traded-price + close. Deduplicates.+ void subscribe(const QStringList& instrument_keys, const QString& mode = QStringLiteral("full"));++ /// Token-based subscribe (BrokerWebSocketBase contract). Tokens are mapped+ /// to instrument keys via InstrumentService; subscribes in "full" mode.+ void subscribe(const QVector<qint64>& tokens) override;++ /// Unsubscribe everything currently subscribed.+ void unsubscribe() override;++ /// Remove a specific set of instrument keys.+ void unsubscribe(const QStringList& instrument_keys);++ protected:+ void on_data_stall() override;++ private slots:+ void on_connected();+ void on_binary_message(const QByteArray& data);+ void on_text_message(const QString& msg);+ void on_disconnected();++ private:+ // Resolve the dynamic WS URL via the REST authorize endpoint (blocking —+ // call on a worker thread). Returns empty on failure.+ QString fetch_ws_url() const;++ // Wire senders. method is "sub" / "unsub". The JSON payload is sent as a+ // binary frame (Upstox requirement).+ void send_subscription(const QStringList& instrument_keys, const QString& method,+ const QString& mode);+ void resubscribe_all();++ // Protobuf FeedResponse → tick/depth signals.+ void parse_feed_response(const QByteArray& data);+ // Map an Upstox instrument key ("SEGMENT|TOKEN") to a display symbol ++ // canonical exchange via InstrumentService (falls back to the key itself).+ void enrich_symbol(const QString& instrument_key, QString& symbol, QString& exchange) const;++ QString access_token_;+ QString ws_url_;++ WebSocketClient* ws_ = nullptr;+ bool connecting_ = false;++ // instrument_key → requested mode ("ltpc" | "full"). Drives replay on+ // reconnect and groups bulk subscribe messages by mode.+ QHash<QString, QString> subscriptions_;++ static constexpr const char* kAuthEndpoint =+ "https://api.upstox.com/v3/feed/market-data-feed/authorize";+ static constexpr int kSubscribeBatch = 100; // instrument keys per sub frame+};++} // namespace trading+} // namespace finceptdiff --git a/fincept-qt/src/ui/navigation/CommandBar.cpp b/fincept-qt/src/ui/navigation/CommandBar.cppindex 2781e3ce1..b7b0a5584 100644--- a/fincept-qt/src/ui/navigation/CommandBar.cpp+++ b/fincept-qt/src/ui/navigation/CommandBar.cpp@@ -155,6 +155,12 @@ void CommandBar::build_commands() {{"algo", "algotrading"},"",{"algo", "algorithmic", "automated"}},+ {"action_center",+ "Action Center",+ "Semi-auto order approval",+ {"actioncenter", "approvals", "pending"},+ "",+ {"approve", "reject", "semiauto", "pending", "orders"}},{"alpha_arena","Alpha Arena","Trading competition platform",diff --git a/fincept-qt/src/ui/navigation/ToolBar.cpp b/fincept-qt/src/ui/navigation/ToolBar.cppindex 041e635b0..aea789933 100644--- a/fincept-qt/src/ui/navigation/ToolBar.cpp+++ b/fincept-qt/src/ui/navigation/ToolBar.cpp@@ -376,6 +376,7 @@ QMenu* ToolBar::build_navigate_menu() {auto* trd = add_sub(tr("Trading & Portfolio"));nav(trd, tr("Equity Trading"), "equity_trading");+ nav(trd, tr("Action Center"), "action_center");nav(trd, tr("Alpha Arena"), "alpha_arena");nav(trd, tr("Prediction Markets"), "polymarket");nav(trd, tr("Derivatives"), "derivatives");diff --git a/fincept-qt/src/ui/theme/StyleSheets.cpp b/fincept-qt/src/ui/theme/StyleSheets.cppindex 93afc0083..c006cd492 100644--- a/fincept-qt/src/ui/theme/StyleSheets.cpp+++ b/fincept-qt/src/ui/theme/StyleSheets.cpp@@ -216,11 +216,16 @@ QString news_screen_styles() {" border: 1px solid %10; font-size: 11px; font-weight: 700; padding: 0 10px; }""#newsDetailAnalyzeBtn:hover { background: %12; color: %1; }""#newsDetailAnalyzeBtn:disabled { color: %6; background: %8; border-color: %3; }"- "#newsDetailAiSummary { color: %7; font-size: 12px; background: transparent; }"+ "#newsDetailAiFetchNote { color: %16; font-size: 10px; background: rgba(217,119,6,0.08); "+ " border-left: 2px solid %16; padding: 3px 6px; }"+ "#newsDetailAiSummary { color: %7; font-size: 12px; line-height: 1.4; background: transparent; }""#newsDetailAiSentiment { font-size: 12px; font-weight: 700; background: transparent; }""#newsDetailAiUrgency { color: %16; font-size: 12px; background: transparent; }"+ "#newsDetailAiConfidence { color: %7; font-size: 12px; background: transparent; }""#newsDetailKeyPoint { color: %7; font-size: 11px; background: transparent; }"- "#newsDetailRisk { color: %11; font-size: 11px; background: transparent; }"+ "#newsDetailRisk { font-size: 11px; background: transparent; }"+ "#newsDetailRiskDetail { color: %6; font-size: 10px; background: transparent; padding-left: 8px; }"+ "#newsDetailEntity { color: %14; font-size: 11px; background: transparent; }""#newsDetailTopicBadge { color: %14; font-size: 10px; background: %8; "" border: 1px solid %3; padding: 1px 6px; }""#newsRelatedBtn { background: transparent; color: %7; font-size: 11px; "diff --git a/fincept-qt/src/ui/widgets/WorldMapWidget.cpp b/fincept-qt/src/ui/widgets/WorldMapWidget.cppindex 6cac3e589..b1f9ec437 100644--- a/fincept-qt/src/ui/widgets/WorldMapWidget.cpp+++ b/fincept-qt/src/ui/widgets/WorldMapWidget.cpp@@ -4,20 +4,25 @@#include "core/config/AppPaths.h"#include <QGeoView/QGVCamera.h>+#include <QGeoView/QGVDrawItem.h>#include <QGeoView/QGVGlobal.h>#include <QGeoView/QGVLayer.h>#include <QGeoView/QGVLayerOSM.h>#include <QGeoView/QGVMap.h>+#include <QGeoView/QGVProjection.h>#include <QGeoView/QGVWidgetScale.h>#include <QGeoView/QGVWidgetZoom.h>#include <QGeoView/Raster/QGVIcon.h>#include <QGraphicsView>+#include <QMouseEvent>#include <QNetworkAccessManager>#include <QNetworkDiskCache>#include <QPainter>+#include <QPainterPath>#include <QResizeEvent>#include <QTimer>#include <QVBoxLayout>+#include <QtMath>namespace fincept::ui {@@ -49,8 +54,74 @@ class ClickableIcon : public QGVIcon {QString tooltip_;std::function<void(int)> on_click_;};+// Great-circle distance in km between two lat/lng points (haversine).+double haversine_km(double lat1, double lng1, double lat2, double lng2) {+ constexpr double kEarthR = 6371.0088;+ const double dlat = qDegreesToRadians(lat2 - lat1);+ const double dlng = qDegreesToRadians(lng2 - lng1);+ const double a = std::sin(dlat / 2) * std::sin(dlat / 2) ++ std::cos(qDegreesToRadians(lat1)) * std::cos(qDegreesToRadians(lat2)) *+ std::sin(dlng / 2) * std::sin(dlng / 2);+ return 2 * kEarthR * std::asin(std::min(1.0, std::sqrt(a)));+}++// ── Shape overlay item ──────────────────────────────────────────────────────+//+// A QGVDrawItem that renders one finalized MapShape (rectangle or circle) as+// a translucent amber overlay. Geometry is expressed in projection space (the+// projShape/projPaint contract), converted from the shape's stored geo bounds+// via the active map projection passed at construction.+class ShapeDrawItem : public QGVDrawItem {+ public:+ ShapeDrawItem(const MapShape& shape, QGVMap* map) : shape_(shape), map_(map) {}++ QPainterPath projShape() const override {+ QPainterPath path;+ auto* proj = map_ ? map_->getProjection() : nullptr;+ if (!proj) return path;+ if (shape_.type == MapShape::Type::Rectangle || shape_.radius_km <= 0.0) {+ const QPointF tl = proj->geoToProj(QGV::GeoPos(shape_.max_lat, shape_.min_lng));+ const QPointF br = proj->geoToProj(QGV::GeoPos(shape_.min_lat, shape_.max_lng));+ path.addRect(QRectF(tl, br).normalized());+ } else {+ // Circle: approximate as the projected bounding box's inscribed+ // ellipse — Web-Mercator keeps small/mid circles visually round.+ const QPointF tl = proj->geoToProj(QGV::GeoPos(shape_.max_lat, shape_.min_lng));+ const QPointF br = proj->geoToProj(QGV::GeoPos(shape_.min_lat, shape_.max_lng));+ path.addEllipse(QRectF(tl, br).normalized());+ }+ return path;+ }++ void projPaint(QPainter* painter) override {+ const QPainterPath path = projShape();+ if (path.isEmpty()) return;+ QColor fill(0xF5, 0x9E, 0x0B, 48); // amber, translucent+ QColor stroke(0xF5, 0x9E, 0x0B, 220);+ painter->setBrush(fill);+ QPen pen(stroke);+ pen.setCosmetic(true); // constant 1.6px regardless of zoom+ pen.setWidthF(1.6);+ painter->setPen(pen);+ painter->drawPath(path);+ }++ private:+ MapShape shape_;+ QGVMap* map_ = nullptr;+};+} // namespace+// ── MapShape ─────────────────────────────────────────────────────────────────+bool MapShape::contains(double lat, double lng) const {+ if (type == Type::Rectangle) {+ return lat >= min_lat && lat <= max_lat && lng >= min_lng && lng <= max_lng;+ }+ // Circle.+ return haversine_km(centre_lat, centre_lng, lat, lng) <= radius_km;+}+// ── One-time network manager setup for QGeoView tile loading ────────────────static void ensure_network_manager() {if (QGV::getNetworkManager())@@ -95,6 +166,16 @@ WorldMapWidget::WorldMapWidget(QWidget* parent) : QWidget(parent) {marker_layer_ = new QGVLayer();map_->addItem(marker_layer_);+ // Shape overlay layer (added after markers so shapes draw on top).+ shape_layer_ = new QGVLayer();+ map_->addItem(shape_layer_);++ // Intercept mouse on the internal graphics view so an active draw tool+ // can drag out a shape without panning the map.+ if (auto* view = map_->findChild<QGraphicsView*>()) {+ view->viewport()->installEventFilter(this);+ }+layout->addWidget(map_);map_ready_ = true;}@@ -131,6 +212,16 @@ QImage WorldMapWidget::make_marker_image(const QColor& color, double radius) conreturn img;}+const QImage& WorldMapWidget::marker_image(const QColor& color, double radius) const {+ // Key on RGBA + radius rounded to whole pixels — sub-pixel radius+ // differences are invisible at icon scale, so rounding maximizes hits.+ const QString key = QString("%1:%2").arg(color.rgba()).arg(qRound(radius));+ auto it = marker_cache_.find(key);+ if (it == marker_cache_.end())+ it = marker_cache_.insert(key, make_marker_image(color, radius));+ return it.value();+}+// ── Pin management ──────────────────────────────────────────────────────────void WorldMapWidget::rebuild_markers() {@@ -155,7 +246,7 @@ void WorldMapWidget::rebuild_markers() {icon = new QGVIcon();}icon->setGeometry(QGV::GeoPos(pin.latitude, pin.longitude), QSizeF(20, 20));- icon->loadImage(make_marker_image(pin.color, pin.radius));+ icon->loadImage(marker_image(pin.color, pin.radius));icon->setFlags(flags);marker_layer_->addItem(icon);}@@ -291,4 +382,131 @@ void WorldMapWidget::fit_to_pins() {map_->flyTo(QGVCameraActions(map_).scaleTo(target));}+// ── Drawing ──────────────────────────────────────────────────────────────────++void WorldMapWidget::set_draw_mode(MapDrawMode mode) {+ draw_mode_ = mode;+ drawing_ = false;+ has_preview_ = false;+ if (!map_) return;+ // While a draw tool is active, disable map mouse panning so a drag draws+ // a shape. Zoom (wheel) stays available. Restore full navigation on None.+ if (mode == MapDrawMode::None) {+ map_->setMouseActions(QGV::MouseAction::All);+ if (auto* view = map_->findChild<QGraphicsView*>())+ view->viewport()->setCursor(Qt::ArrowCursor);+ } else {+ map_->setMouseAction(QGV::MouseAction::Move, false);+ if (auto* view = map_->findChild<QGraphicsView*>())+ view->viewport()->setCursor(Qt::CrossCursor);+ }+ rebuild_shape_overlays();+}++void WorldMapWidget::clear_shapes() {+ shapes_.clear();+ has_preview_ = false;+ rebuild_shape_overlays();+ emit shapes_changed();+}++bool WorldMapWidget::pixel_to_geo(const QPoint& viewport_px, double* out_lat, double* out_lng) const {+ if (!map_) return false;+ auto* proj = map_->getProjection();+ if (!proj) return false;+ // QGVMap::mapToProj expects a position relative to the QGVMap widget. The+ // event filter watches the view's viewport, whose origin matches the map+ // widget's content origin, so the pixel maps through directly.+ const QPointF projPos = const_cast<QGVMap*>(map_)->mapToProj(viewport_px);+ const QGV::GeoPos geo = proj->projToGeo(projPos);+ *out_lat = geo.latitude();+ *out_lng = geo.longitude();+ return true;+}++void WorldMapWidget::rebuild_shape_overlays() {+ if (!map_ready_ || !shape_layer_) return;+ while (shape_layer_->countItems() > 0) {+ auto* item = shape_layer_->getItem(0);+ shape_layer_->removeItem(item);+ delete item;+ }+ for (const auto& s : shapes_)+ shape_layer_->addItem(new ShapeDrawItem(s, map_));+ if (has_preview_)+ shape_layer_->addItem(new ShapeDrawItem(preview_shape_, map_));+}++bool WorldMapWidget::eventFilter(QObject* watched, QEvent* event) {+ if (draw_mode_ == MapDrawMode::None)+ return QWidget::eventFilter(watched, event);++ const QEvent::Type t = event->type();+ if (t != QEvent::MouseButtonPress && t != QEvent::MouseMove &&+ t != QEvent::MouseButtonRelease)+ return QWidget::eventFilter(watched, event);++ auto* me = static_cast<QMouseEvent*>(event);+ if (t == QEvent::MouseButtonPress && me->button() == Qt::LeftButton) {+ if (pixel_to_geo(me->pos(), &drag_start_lat_, &drag_start_lng_)) {+ drawing_ = true;+ has_preview_ = false;+ }+ return true; // consume so the map doesn't start a pan+ }++ if (t == QEvent::MouseMove && drawing_) {+ double cur_lat = 0, cur_lng = 0;+ if (pixel_to_geo(me->pos(), &cur_lat, &cur_lng)) {+ MapShape s;+ s.min_lat = std::min(drag_start_lat_, cur_lat);+ s.max_lat = std::max(drag_start_lat_, cur_lat);+ s.min_lng = std::min(drag_start_lng_, cur_lng);+ s.max_lng = std::max(drag_start_lng_, cur_lng);+ if (draw_mode_ == MapDrawMode::Circle) {+ s.type = MapShape::Type::Circle;+ s.centre_lat = drag_start_lat_;+ s.centre_lng = drag_start_lng_;+ s.radius_km = haversine_km(drag_start_lat_, drag_start_lng_, cur_lat, cur_lng);+ // Bounding box of the circle for union / quick tests.+ const double dlat = (s.radius_km / 111.0);+ const double dlng = s.radius_km /+ (111.320 * std::max(0.05, std::cos(qDegreesToRadians(drag_start_lat_))));+ s.min_lat = drag_start_lat_ - dlat;+ s.max_lat = drag_start_lat_ + dlat;+ s.min_lng = drag_start_lng_ - dlng;+ s.max_lng = drag_start_lng_ + dlng;+ } else {+ s.type = MapShape::Type::Rectangle;+ }+ preview_shape_ = s;+ has_preview_ = true;+ rebuild_shape_overlays();+ }+ return true;+ }++ if (t == QEvent::MouseButtonRelease && drawing_ && me->button() == Qt::LeftButton) {+ drawing_ = false;+ if (has_preview_) {+ // Reject degenerate (zero-area / accidental click) shapes.+ const bool valid = (preview_shape_.type == MapShape::Type::Circle)+ ? preview_shape_.radius_km > 1.0+ : (preview_shape_.max_lat - preview_shape_.min_lat) > 0.01 &&+ (preview_shape_.max_lng - preview_shape_.min_lng) > 0.01;+ has_preview_ = false;+ if (valid) {+ shapes_.append(preview_shape_);+ rebuild_shape_overlays();+ emit shapes_changed();+ } else {+ rebuild_shape_overlays();+ }+ }+ return true;+ }++ return QWidget::eventFilter(watched, event);+}+} // namespace fincept::uidiff --git a/fincept-qt/src/ui/widgets/WorldMapWidget.h b/fincept-qt/src/ui/widgets/WorldMapWidget.hindex 7926afc65..c0f9151a4 100644--- a/fincept-qt/src/ui/widgets/WorldMapWidget.h+++ b/fincept-qt/src/ui/widgets/WorldMapWidget.h@@ -1,6 +1,8 @@// src/ui/widgets/WorldMapWidget.h#pragma once#include <QColor>+#include <QHash>+#include <QImage>#include <QString>#include <QVector>#include <QWidget>@@ -23,6 +25,29 @@ struct MapPin {int id = -1;};+/// A user-drawn selection area on the map. Rectangle and Circle only.+/// Geometry is stored in geographic coordinates so it survives pan/zoom.+struct MapShape {+ enum class Type { Rectangle, Circle };+ Type type = Type::Rectangle;++ // Rectangle: the axis-aligned geo bounds.+ // Circle: bounds is the bounding box of the circle (for quick union /+ // bbox use); centre + radius_km carry the true circle for point tests.+ double min_lat = 0, max_lat = 0, min_lng = 0, max_lng = 0;++ // Circle only.+ double centre_lat = 0, centre_lng = 0;+ double radius_km = 0;++ /// True if (lat,lng) lies inside this shape. Rectangle = bbox test;+ /// Circle = great-circle distance <= radius.+ bool contains(double lat, double lng) const;+};++/// Active map drawing tool. None disables drawing (normal pan/zoom).+enum class MapDrawMode { None, Rectangle, Circle };+/// Interactive world map widget backed by QGeoView (real OSM/CartoDB tiles)./// Supports pan, zoom, and colored marker pins at lat/lng coordinates.class WorldMapWidget : public QWidget {@@ -41,22 +66,53 @@ class WorldMapWidget : public QWidget {/// Auto-zoom to fit all current pins with paddingvoid fit_to_pins();+ // ── Drawing ─────────────────────────────────────────────────────────────+ /// Set the active draw tool. While a tool is active the map suppresses+ /// pan so a drag draws a shape instead. None restores normal navigation.+ void set_draw_mode(MapDrawMode mode);+ MapDrawMode draw_mode() const { return draw_mode_; }+ /// Remove all user-drawn shapes (emits shapes_changed).+ void clear_shapes();+ const QVector<MapShape>& shapes() const { return shapes_; }+signals:/// Emitted when a pin with `id != -1` is clicked. Carries the caller-/// assigned id so the consumer can resolve back to its own data.void pin_clicked(int id);+ /// Emitted whenever the set of drawn shapes changes (new shape finalized+ /// or shapes cleared). The consumer reads shapes() to react.+ void shapes_changed();protected:void resizeEvent(QResizeEvent* event) override;+ bool eventFilter(QObject* watched, QEvent* event) override;private:void rebuild_markers();+ void rebuild_shape_overlays();QImage make_marker_image(const QColor& color, double radius) const;+ /// Convert a viewport pixel (in the QGraphicsView) to geographic lat/lng.+ bool pixel_to_geo(const QPoint& viewport_px, double* out_lat, double* out_lng) const;+ /// Memoized wrapper over make_marker_image: pins sharing a (color, radius)+ /// reuse one rendered QImage instead of repainting an antialiased gradient+ /// each. Most pin sets use 1-2 distinct styles, so this collapses N paints+ /// to a couple regardless of pin count.+ const QImage& marker_image(const QColor& color, double radius) const;QGVMap* map_ = nullptr;QGVLayer* marker_layer_ = nullptr;+ QGVLayer* shape_layer_ = nullptr;QVector<MapPin> pins_;+ mutable QHash<QString, QImage> marker_cache_;bool map_ready_ = false;++ // Drawing state.+ MapDrawMode draw_mode_ = MapDrawMode::None;+ QVector<MapShape> shapes_;+ bool drawing_ = false;+ double drag_start_lat_ = 0, drag_start_lng_ = 0; // anchor of in-progress shape+ MapShape preview_shape_; // shape being dragged+ bool has_preview_ = false;};} // namespace fincept::ui